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 :param formula: list of clauses, a clause is pair of literals over X1,...,Xn for some n. a literal is an integer, for example -1 = not X1, 3 = X3 :returns: table with boolean assignment satisfying the formula or None :complexity: linear """ # num_variables is the number of variables num_variables = max(abs(clause[p]) for p in (0, 1) for clause in formula) graph = [[] for node in range(2 * num_variables)] for x_idx, y_idx in formula: # x_idx or y_idx graph[_vertex(-x_idx)].append(_vertex(y_idx)) # -x_idx => y_idx graph[_vertex(-y_idx)].append(_vertex(x_idx)) # -y_idx => x_idx <|code_end|> , predict the immediate next line with the help of imports: from tryalgo.strongly_connected_components import tarjan and context (classes, functions, sometimes code) from other files: # Path: tryalgo/strongly_connected_components.py # def tarjan(graph): # """Strongly connected components by Tarjan, iterative implementation # # :param graph: directed graph in listlist format, cannot be listdict # :returns: list of lists for each component # :complexity: linear # """ # n = len(graph) # dfs_num = [None] * n # dfs_min = [n] * n # waiting = [] # waits = [False] * n # invariant: waits[v] iff v in waiting # sccp = [] # list of detected components # dfs_time = 0 # times_seen = [-1] * n # for start in range(n): # if times_seen[start] == -1: # initiate path # times_seen[start] = 0 # to_visit = [start] # while to_visit: # node = to_visit[-1] # top of stack # if times_seen[node] == 0: # start process # dfs_num[node] = dfs_time # dfs_min[node] = dfs_time # dfs_time += 1 # waiting.append(node) # waits[node] = True # children = graph[node] # if times_seen[node] == len(children): # end of process # to_visit.pop() # remove from stack # dfs_min[node] = dfs_num[node] # compute dfs_min # for child in children: # if waits[child] and dfs_min[child] < dfs_min[node]: # dfs_min[node] = dfs_min[child] # if dfs_min[node] == dfs_num[node]: # representative # component = [] # make component # while True: # add nodes # u = waiting.pop() # waits[u] = False # component.append(u) # if u == node: # until repr. # break # sccp.append(component) # else: # child = children[times_seen[node]] # times_seen[node] += 1 # if times_seen[child] == -1: # not visited yet # times_seen[child] = 0 # to_visit.append(child) # return sccp . Output only the next line.
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 matrix of a tree :complexity: O(n log n), with n = len(graph) """ n = len(graph) dfs_trace = [] self.last = [None] * n to_visit = [(0, 0, None)] # node 0 is root succ = [0] * n while to_visit: level, node, father = to_visit[-1] self.last[node] = len(dfs_trace) dfs_trace.append((level, node)) if succ[node] < len(graph[node]) and \ graph[node][succ[node]] == father: succ[node] += 1 if succ[node] == len(graph[node]): to_visit.pop() else: neighbor = graph[node][succ[node]] succ[node] += 1 to_visit.append((level + 1, neighbor, node)) <|code_end|> , predict the immediate next line with the help of imports: from tryalgo.range_minimum_query import RangeMinQuery and context (classes, functions, sometimes code) from other files: # Path: tryalgo/range_minimum_query.py # class RangeMinQuery: # """Range minimum query # # maintains a table t, can read/write items t[i], # and query range_min(i,k) = min{ t[i], t[i + 1], ..., t[k - 1]} # :complexity: all operations in O(log n), for n = len(t) # """ # def __init__(self, t, INF=float('inf')): # self.INF = INF # self.N = 1 # while self.N < len(t): # find size N # self.N *= 2 # self.s = [self.INF] * (2 * self.N) # for i in range(len(t)): # store values of t # self.s[self.N + i] = t[i] # in the leaf nodes # for p in range(self.N - 1, 0, -1): # fill inner nodes # self.s[p] = min(self.s[2 * p], self.s[2 * p + 1]) # # def __getitem__(self, i): # return self.s[self.N + i] # # def __setitem__(self, i, v): # """ sets t[i] to v. # :complexity: O(log len(t)) # """ # p = self.N + i # self.s[p] = v # p //= 2 # climb up the tree # while p > 0: # update node # self.s[p] = min(self.s[2 * p], self.s[2 * p + 1]) # p //= 2 # # def range_min(self, i, k): # """:returns: min{ t[i], t[i + 1], ..., t[k - 1]} # :complexity: O(log len(t)) # """ # return self._range_min(1, 0, self.N, i, k) # # def _range_min(self, p, start, span, i, k): # """returns the minimum in t in the indexes [i, k) intersected # with [start, start + span). # p is the node associated to the later interval. # """ # if start + span <= i or k <= start: # disjoint intervals # return self.INF # if i <= start and start + span <= k: # contained intervals # return self.s[p] # left = self._range_min(2 * p, start, span // 2, # i, k) # right = self._range_min(2 * p + 1, start + span // 2, span // 2, # i, k) # return min(left, right) . Output only the next line.
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 :param graph: directed graph in listlist or listdict format :param capacity: in matrix format or same listdict graph :param int source: vertex :param int target: vertex :returns: skew symmetric flow matrix, flow value :complexity: :math:`O(|V|^2 |E|)` """ assert source != target <|code_end|> using the current file's imports: from collections import deque from sys import setrecursionlimit from tryalgo.graph import add_reverse_arcs and any relevant context from other files: # Path: tryalgo/graph.py # def add_reverse_arcs(graph, capac=None): # """Utility function for flow algorithms that need for every arc (u,v), # the existence of an (v,u) arc, by default with zero capacity. # graph can be in adjacency list, possibly with capacity matrix capac. # or graph can be in adjacency dictionary, then capac parameter is ignored. # # :param capac: arc capacity matrix # :param graph: in listlist representation, or in listdict representation, # in this case capac is ignored # :complexity: linear # :returns: nothing, but graph is modified # """ # for u, _ in enumerate(graph): # for v in graph[u]: # if u not in graph[v]: # if type(graph[v]) is list: # graph[v].append(u) # if capac: # capac[v][u] = 0 # else: # assert type(graph[v]) is dict # graph[v][u] = 0 . Output only the next line.
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 operator while (tok != '(' and ops and PRIORITY[ops[-1]] >= PRIORITY[tok]): right = vals.pop() left = vals.pop() vals.append((left, ops.pop(), right)) if tok == ')': ops.pop() # this is the corresponding '(' else: ops.append(tok) elif tok.isdigit(): # tok is an integer vals.append(int(tok)) else: # tok is an identifier vals.append(tok) return vals.pop() # snip} if __name__ == "__main__": # this main program is here to be tested on the online judge <|code_end|> . Write the next line using the current file imports: from tryalgo.our_std import readint, readstr and context from other files: # Path: tryalgo/our_std.py # def readint(): # """ # function to read an integer from stdin # """ # return int(stdin.readline()) # # def readstr(): # """ # function to read a string from stdin # """ # return stdin.readline().strip() , which may include functions, classes, or code. Output only the next line.
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 while (tok != '(' and ops and PRIORITY[ops[-1]] >= PRIORITY[tok]): right = vals.pop() left = vals.pop() vals.append((left, ops.pop(), right)) if tok == ')': ops.pop() # this is the corresponding '(' else: ops.append(tok) elif tok.isdigit(): # tok is an integer vals.append(int(tok)) else: # tok is an identifier vals.append(tok) return vals.pop() # snip} if __name__ == "__main__": # this main program is here to be tested on the online judge for test in range(readint()): cell = {} <|code_end|> using the current file's imports: from tryalgo.our_std import readint, readstr and any relevant context from other files: # Path: tryalgo/our_std.py # def readint(): # """ # function to read an integer from stdin # """ # return int(stdin.readline()) # # def readstr(): # """ # function to read a string from stdin # """ # return stdin.readline().strip() . Output only the next line.
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_cover(self): L = [([(0, 1)], 1), ([(0, 3), (1, 2)], 1), ([(0, 2), (1, 3)], 1), ([(0, 2), (2, 3)], 1), ([(0, 2), (3, 4)], 2), ([(0, 4), (1, 3), (2, 6), (5, 8), (7, 9), (9, 10)], 3)] for instance, res in L: <|code_end|> , predict the next line using imports from the current file: import unittest from tryalgo.interval_cover import _solve, interval_cover and context including class names, function names, and sometimes code from other files: # Path: tryalgo/interval_cover.py # def _solve(iles, rayon): # II = [] # for x, y in iles: # if y > rayon: # return -1 # island is too far # z = sqrt(rayon * rayon - y * y) # find the interval # II.append((x + z, x - z)) # II.sort() # sort by right side # sol = 0 # last = float('-inf') # for right, left in II: # if last < left: # uncovered interval # sol += 1 # last = right # put an antenna # return sol # # def interval_cover(I): # """Minimum interval cover # # :param I: list of closed intervals # :returns: minimum list of points covering all intervals # :complexity: O(n log n) # """ # S = [] # # sort by right endpoints # for start, end in sorted(I, key=lambda v: v[1]): # if not S or S[-1] < start: # S.append(end) # return S . Output only the next line.
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 in range(10)} # dict = associative array if tab[0] not in not_zero: difference = -convert(S[n - 1], ass) # do the addition for word in S[:n - 1]: difference += convert(word, ass) if difference == 0: # does it add up? count += 1 if not next_permutation(tab): break return count # snip} if __name__ == "__main__": if len(argv) > 1: L = argv[1:] if len(L) == 1: L = list(L[0]) while True: print(L) if not next_permutation(L): sys.exit(0) <|code_end|> , continue by predicting the next line. Consider current file imports: from sys import argv from tryalgo.our_std import readint, readstr import sys and context: # Path: tryalgo/our_std.py # def readint(): # """ # function to read an integer from stdin # """ # return int(stdin.readline()) # # def readstr(): # """ # function to read a string from stdin # """ # return stdin.readline().strip() which might include code, classes, or functions. Output only the next line.
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 range(10)} # dict = associative array if tab[0] not in not_zero: difference = -convert(S[n - 1], ass) # do the addition for word in S[:n - 1]: difference += convert(word, ass) if difference == 0: # does it add up? count += 1 if not next_permutation(tab): break return count # snip} if __name__ == "__main__": if len(argv) > 1: L = argv[1:] if len(L) == 1: L = list(L[0]) while True: print(L) if not next_permutation(L): sys.exit(0) n = readint() <|code_end|> , predict the next line using imports from the current file: from sys import argv from tryalgo.our_std import readint, readstr import sys and context including class names, function names, and sometimes code from other files: # Path: tryalgo/our_std.py # def readint(): # """ # function to read an integer from stdin # """ # return int(stdin.readline()) # # def readstr(): # """ # function to read a string from stdin # """ # return stdin.readline().strip() . Output only the next line.
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] - p[i][0] * p[i - 1][1] return A / 2. # snip} # snip{ is_simple # pylint: disable=too-many-locals def is_simple(polygon): """Test if a rectilinear polygon is is_simple :param polygon: list of points as (x,y) pairs along the closed polygon :returns: True if the segements do not intersect :complexity: O(n log n) for n=len(polygon) """ n = len(polygon) order = list(range(n)) order.sort(key=lambda i: polygon[i]) # lexicographic order rank_to_y = list(set(p[1] for p in polygon)) rank_to_y.sort() y_to_rank = {y: rank for rank, y in enumerate(rank_to_y)} <|code_end|> with the help of current file imports: from tryalgo.range_minimum_query import RangeMinQuery and context from other files: # Path: tryalgo/range_minimum_query.py # class RangeMinQuery: # """Range minimum query # # maintains a table t, can read/write items t[i], # and query range_min(i,k) = min{ t[i], t[i + 1], ..., t[k - 1]} # :complexity: all operations in O(log n), for n = len(t) # """ # def __init__(self, t, INF=float('inf')): # self.INF = INF # self.N = 1 # while self.N < len(t): # find size N # self.N *= 2 # self.s = [self.INF] * (2 * self.N) # for i in range(len(t)): # store values of t # self.s[self.N + i] = t[i] # in the leaf nodes # for p in range(self.N - 1, 0, -1): # fill inner nodes # self.s[p] = min(self.s[2 * p], self.s[2 * p + 1]) # # def __getitem__(self, i): # return self.s[self.N + i] # # def __setitem__(self, i, v): # """ sets t[i] to v. # :complexity: O(log len(t)) # """ # p = self.N + i # self.s[p] = v # p //= 2 # climb up the tree # while p > 0: # update node # self.s[p] = min(self.s[2 * p], self.s[2 * p + 1]) # p //= 2 # # def range_min(self, i, k): # """:returns: min{ t[i], t[i + 1], ..., t[k - 1]} # :complexity: O(log len(t)) # """ # return self._range_min(1, 0, self.N, i, k) # # def _range_min(self, p, start, span, i, k): # """returns the minimum in t in the indexes [i, k) intersected # with [start, start + span). # p is the node associated to the later interval. # """ # if start + span <= i or k <= start: # disjoint intervals # return self.INF # if i <= start and start + span <= k: # contained intervals # return self.s[p] # left = self._range_min(2 * p, start, span // 2, # i, k) # right = self._range_min(2 * p + 1, start + span // 2, span // 2, # i, k) # return min(left, right) , which may contain function names, class names, or code. Output only the next line.
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: `O(log((hi-lo)/gap))` """ while hi - lo > gap: step = (hi - lo) / 3. if f(lo + step) < f(lo + 2 * step): lo += step else: hi -= step return lo # pylint: disable=cell-var-from-loop if __name__ == "__main__": def volume(level): """ Computes the volume of a set of cuboids. """ vol = 0 for base, height, ground in rect: if base < level: vol += ground * min(level - base, height) return vol <|code_end|> , determine the next line of code. You have imports: from tryalgo.our_std import readint, readarray and context (class names, function names, or code) available: # Path: tryalgo/our_std.py # def readint(): # """ # function to read an integer from stdin # """ # return int(stdin.readline()) # # def readarray(typ): # """ # function to read an array # """ # return list(map(typ, stdin.readline().split())) . Output only the next line.
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(lo + 2 * step): lo += step else: hi -= step return lo # pylint: disable=cell-var-from-loop if __name__ == "__main__": def volume(level): """ Computes the volume of a set of cuboids. """ vol = 0 for base, height, ground in rect: if base < level: vol += ground * min(level - base, height) return vol for test in range(readint()): n = readint() rect = [] for _ in range(n): <|code_end|> , predict the next line using imports from the current file: from tryalgo.our_std import readint, readarray and context including class names, function names, and sometimes code from other files: # Path: tryalgo/our_std.py # def readint(): # """ # function to read an integer from stdin # """ # return int(stdin.readline()) # # def readarray(typ): # """ # function to read an array # """ # return list(map(typ, stdin.readline().split())) . Output only the next line.
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 next line with the help of imports: import unittest from unittest.mock import patch from mock import patch from tryalgo.our_std import readint, readstr, readmatrix, readarray and context (classes, functions, sometimes code) from other files: # Path: tryalgo/our_std.py # def readint(): # """ # function to read an integer from stdin # """ # return int(stdin.readline()) # # def readstr(): # """ # function to read a string from stdin # """ # return stdin.readline().strip() # # def readmatrix(n): # """ # function to read a matrix # """ # M = [] # for _ in range(n): # row = readarray(int) # assert len(row) == n # M.append(row) # return M # # def readarray(typ): # """ # function to read an array # """ # return list(map(typ, stdin.readline().split())) . Output only the next line.
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) def test_readstr(self): with patch('sys.stdin.readline', return_value=" 1 2 "): <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest from unittest.mock import patch from mock import patch from tryalgo.our_std import readint, readstr, readmatrix, readarray and context: # Path: tryalgo/our_std.py # def readint(): # """ # function to read an integer from stdin # """ # return int(stdin.readline()) # # def readstr(): # """ # function to read a string from stdin # """ # return stdin.readline().strip() # # def readmatrix(n): # """ # function to read a matrix # """ # M = [] # for _ in range(n): # row = readarray(int) # assert len(row) == n # M.append(row) # return M # # def readarray(typ): # """ # function to read an array # """ # return list(map(typ, stdin.readline().split())) which might include code, classes, or functions. Output only the next line.
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(readint(), 1) def test_readstr(self): with patch('sys.stdin.readline', return_value=" 1 2 "): self.assertEqual(readstr(), "1 2") def test_readarray(self): with patch('sys.stdin.readline', return_value="1 2 3"): self.assertEqual(readarray(int), [1, 2, 3]) def test_readmatrix(self): with patch('sys.stdin.readline', return_value="1 2 3"): <|code_end|> . Use current file imports: import unittest from unittest.mock import patch from mock import patch from tryalgo.our_std import readint, readstr, readmatrix, readarray and context (classes, functions, or code) from other files: # Path: tryalgo/our_std.py # def readint(): # """ # function to read an integer from stdin # """ # return int(stdin.readline()) # # def readstr(): # """ # function to read a string from stdin # """ # return stdin.readline().strip() # # def readmatrix(n): # """ # function to read a matrix # """ # M = [] # for _ in range(n): # row = readarray(int) # assert len(row) == n # M.append(row) # return M # # def readarray(typ): # """ # function to read an array # """ # return list(map(typ, stdin.readline().split())) . Output only the next line.
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(readint(), 1) def test_readstr(self): with patch('sys.stdin.readline', return_value=" 1 2 "): self.assertEqual(readstr(), "1 2") def test_readarray(self): with patch('sys.stdin.readline', return_value="1 2 3"): <|code_end|> . Use current file imports: import unittest from unittest.mock import patch from mock import patch from tryalgo.our_std import readint, readstr, readmatrix, readarray and context (classes, functions, or code) from other files: # Path: tryalgo/our_std.py # def readint(): # """ # function to read an integer from stdin # """ # return int(stdin.readline()) # # def readstr(): # """ # function to read a string from stdin # """ # return stdin.readline().strip() # # def readmatrix(n): # """ # function to read a matrix # """ # M = [] # for _ in range(n): # row = readarray(int) # assert len(row) == n # M.append(row) # return M # # def readarray(typ): # """ # function to read an array # """ # return list(map(typ, stdin.readline().split())) . Output only the next line.
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 Q: u = Q.popleft() for v in graph[u]: cuv = capacity[u][v] residual = cuv - flow[u][v] if residual > 0 and augm_path[v] is None: augm_path[v] = u # store predecessor A[v] = min(A[u], residual) if v == target: break Q.append(v) return (augm_path, A[target]) # augmenting path, min residual cap. def edmonds_karp(graph, capacity, source, target): """Maximum flow by Edmonds-Karp :param graph: directed graph in listlist or listdict format :param capacity: in matrix format or same listdict graph :param int source: vertex :param int target: vertex :returns: flow matrix, flow value :complexity: :math:`O(|V|*|E|^2)` """ <|code_end|> with the help of current file imports: from collections import deque from tryalgo.graph import add_reverse_arcs and context from other files: # Path: tryalgo/graph.py # def add_reverse_arcs(graph, capac=None): # """Utility function for flow algorithms that need for every arc (u,v), # the existence of an (v,u) arc, by default with zero capacity. # graph can be in adjacency list, possibly with capacity matrix capac. # or graph can be in adjacency dictionary, then capac parameter is ignored. # # :param capac: arc capacity matrix # :param graph: in listlist representation, or in listdict representation, # in this case capac is ignored # :complexity: linear # :returns: nothing, but graph is modified # """ # for u, _ in enumerate(graph): # for v in graph[u]: # if u not in graph[v]: # if type(graph[v]) is list: # graph[v].append(u) # if capac: # capac[v][u] = 0 # else: # assert type(graph[v]) is dict # graph[v][u] = 0 , which may contain function names, class names, or code. Output only the next line.
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 I: list of closed intervals :returns: minimum list of points covering all intervals :complexity: O(n log n) """ S = [] # sort by right endpoints for start, end in sorted(I, key=lambda v: v[1]): if not S or S[-1] < start: S.append(end) return S # snip} if __name__ == "__main__": # http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1360 testCase = 1 while True: <|code_end|> , predict the immediate next line with the help of imports: from sys import stdin from math import sqrt from tryalgo.our_std import readarray and context (classes, functions, sometimes code) from other files: # Path: tryalgo/our_std.py # def readarray(typ): # """ # function to read an array # """ # return list(map(typ, stdin.readline().split())) . Output only the next line.
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 solved :modifies: G will contain the solution :complexity: huge, but linear for usual published 9x9 grids """ global N, N2, N4 if len(G) == 16: # for a 16 x 16 sudoku grid N, N2, N4 = 4, 16, 256 e = N * N4 universe = e + 1 S = [[rc(a), rv(a), cv(a), bv(a)] for a in range(N4 * N2)] A = [e] for r in range(N2): for c in range(N2): if G[r][c] != 0: a = assignment(r, c, G[r][c] - 1) A += S[a] <|code_end|> . Use current file imports: from tryalgo.dancing_links import dancing_links and context (classes, functions, or code) from other files: # Path: tryalgo/dancing_links.py # def dancing_links(size_universe, sets): # """Exact set cover by the dancing links algorithm # # :param size_universe: universe = {0, 1, ..., size_universe - 1} # :param sets: list of sets # :returns: list of set indices partitioning the universe, or None # :complexity: huge # """ # header = Cell(None, None, 0, None) # building the cell structure # col = [] # for j in range(size_universe): # col.append(Cell(header, None, 0, None)) # for i, _ in enumerate(sets): # row = None # for j in sets[i]: # col[j].S += 1 # one more entry in this column # row = Cell(row, col[j], i, col[j]) # sol = [] # if solve(header, sol): # return sol # return None . Output only the next line.
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 a heap implementing item updates :param graph: adjacency list or adjacency dictionary of a directed graph :param weight: matrix or adjacency dictionary :assumes: weights are non-negatif and weights are infinite for non edges :param source: source vertex :type source: int :param target: if given, stops once distance to target found :type target: int :returns: distance table, precedence table :complexity: `O(|V| + |E|log|V|)` """ n = len(graph) assert all(weight[u][v] >= 0 for u in range(n) for v in graph[u]) prec = [None] * n dist = [float('inf')] * n dist[source] = 0 <|code_end|> . Write the next line using the current file imports: from heapq import heappop, heappush from tryalgo.our_heap import OurHeap and context from other files: # Path: tryalgo/our_heap.py # class OurHeap: # """ min heap # # * heap: is the actual heap, heap[1] = index of the smallest element # * rank: inverse of heap with rank[x]=i iff heap[i]=x # * n: size of the heap # # :complexity: init O(n log n), len O(1), # other operations O(log n) in expectation # and O(n) in worst case, due to the usage of a dictionary # """ # def __init__(self, items): # self.heap = [None] # index 0 will be ignored # self.rank = {} # for x in items: # self.push(x) # # def __len__(self): # return len(self.heap) - 1 # # def push(self, x): # """Insert new element x in the heap. # Assumption: x is not already in the heap""" # assert x not in self.rank # i = len(self.heap) # self.heap.append(x) # add a new leaf # self.rank[x] = i # self.up(i) # maintain heap order # # def pop(self): # """Remove and return smallest element""" # root = self.heap[1] # del self.rank[root] # x = self.heap.pop() # remove last leaf # if self: # if heap is not empty # self.heap[1] = x # move the last leaf # self.rank[x] = 1 # to the root # self.down(1) # maintain heap order # return root # # snip} # # # snip{ our_heap_up_down # def up(self, i): # """The value of heap[i] has decreased. Maintain heap invariant.""" # x = self.heap[i] # while i > 1 and x < self.heap[i // 2]: # self.heap[i] = self.heap[i // 2] # self.rank[self.heap[i // 2]] = i # i //= 2 # self.heap[i] = x # insertion index found # self.rank[x] = i # # def down(self, i): # """the value of heap[i] has increased. Maintain heap invariant.""" # x = self.heap[i] # n = len(self.heap) # while True: # left = 2 * i # climb down the tree # right = left + 1 # if (right < n and self.heap[right] < x and # self.heap[right] < self.heap[left]): # self.heap[i] = self.heap[right] # self.rank[self.heap[right]] = i # move right child up # i = right # elif left < n and self.heap[left] < x: # self.heap[i] = self.heap[left] # self.rank[self.heap[left]] = i # move left child up # i = left # else: # self.heap[i] = x # insertion index found # self.rank[x] = i # return # # def update(self, old, new): # """Replace an element in the heap # """ # i = self.rank[old] # change value at index i # del self.rank[old] # self.heap[i] = new # self.rank[new] = i # if old < new: # maintain heap order # self.down(i) # else: # self.up(i) , which may include functions, classes, or code. Output only the next line.
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, 8]] <|code_end|> . Use current file imports: import unittest from unittest.mock import patch from mock import patch from tryalgo.freivalds import freivalds, readint, readmatrix, readarray and context (classes, functions, or code) from other files: # Path: tryalgo/freivalds.py # def freivalds(A, B, C): # """Tests matrix product AB=C by Freivalds # # :param A: n by n numerical matrix # :param B: same # :param C: same # :returns: False with high probability if AB != C # # :complexity: # :math:`O(n^2)` # """ # n = len(A) # x = [randint(0, 1000000) for j in range(n)] # return mult(A, mult(B, x)) == mult(C, x) # # def readint(): # """ # function to read an integer from stdin # """ # return int(stdin.readline()) # # def readmatrix(n): # """ # function to read a matrix # """ # M = [] # for _ in range(n): # row = readarray(int) # assert len(row) == n # M.append(row) # return M # # def readarray(typ): # """ # function to read an array # """ # return list(map(typ, stdin.readline().split())) . Output only the next line.
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.assertTrue(freivalds(A, B, C)) # [!] might fail with small probability def test_readint(self): with patch('sys.stdin.readline', return_value="1"): <|code_end|> , determine the next line of code. You have imports: import unittest from unittest.mock import patch from mock import patch from tryalgo.freivalds import freivalds, readint, readmatrix, readarray and context (class names, function names, or code) available: # Path: tryalgo/freivalds.py # def freivalds(A, B, C): # """Tests matrix product AB=C by Freivalds # # :param A: n by n numerical matrix # :param B: same # :param C: same # :returns: False with high probability if AB != C # # :complexity: # :math:`O(n^2)` # """ # n = len(A) # x = [randint(0, 1000000) for j in range(n)] # return mult(A, mult(B, x)) == mult(C, x) # # def readint(): # """ # function to read an integer from stdin # """ # return int(stdin.readline()) # # def readmatrix(n): # """ # function to read a matrix # """ # M = [] # for _ in range(n): # row = readarray(int) # assert len(row) == n # M.append(row) # return M # # def readarray(typ): # """ # function to read an array # """ # return list(map(typ, stdin.readline().split())) . Output only the next line.
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 = [[5, 6], [7, 8]] self.assertTrue(freivalds(A, B, C)) # [!] might fail with small probability def test_readint(self): with patch('sys.stdin.readline', return_value="1"): self.assertEqual(readint(), 1) def test_readarray(self): with patch('sys.stdin.readline', return_value="1 2 3"): self.assertEqual(readarray(int), [1, 2, 3]) def test_readmatrix(self): with patch('sys.stdin.readline', return_value="1 2 3"): <|code_end|> using the current file's imports: import unittest from unittest.mock import patch from mock import patch from tryalgo.freivalds import freivalds, readint, readmatrix, readarray and any relevant context from other files: # Path: tryalgo/freivalds.py # def freivalds(A, B, C): # """Tests matrix product AB=C by Freivalds # # :param A: n by n numerical matrix # :param B: same # :param C: same # :returns: False with high probability if AB != C # # :complexity: # :math:`O(n^2)` # """ # n = len(A) # x = [randint(0, 1000000) for j in range(n)] # return mult(A, mult(B, x)) == mult(C, x) # # def readint(): # """ # function to read an integer from stdin # """ # return int(stdin.readline()) # # def readmatrix(n): # """ # function to read a matrix # """ # M = [] # for _ in range(n): # row = readarray(int) # assert len(row) == n # M.append(row) # return M # # def readarray(typ): # """ # function to read an array # """ # return list(map(typ, stdin.readline().split())) . Output only the next line.
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.assertTrue(freivalds(A, B, C)) # [!] might fail with small probability def test_readint(self): with patch('sys.stdin.readline', return_value="1"): self.assertEqual(readint(), 1) def test_readarray(self): with patch('sys.stdin.readline', return_value="1 2 3"): <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest from unittest.mock import patch from mock import patch from tryalgo.freivalds import freivalds, readint, readmatrix, readarray and context: # Path: tryalgo/freivalds.py # def freivalds(A, B, C): # """Tests matrix product AB=C by Freivalds # # :param A: n by n numerical matrix # :param B: same # :param C: same # :returns: False with high probability if AB != C # # :complexity: # :math:`O(n^2)` # """ # n = len(A) # x = [randint(0, 1000000) for j in range(n)] # return mult(A, mult(B, x)) == mult(C, x) # # def readint(): # """ # function to read an integer from stdin # """ # return int(stdin.readline()) # # def readmatrix(n): # """ # function to read a matrix # """ # M = [] # for _ in range(n): # row = readarray(int) # assert len(row) == n # M.append(row) # return M # # def readarray(typ): # """ # function to read an array # """ # return list(map(typ, stdin.readline().split())) which might include code, classes, or functions. Output only the next line.
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 10 11 weights = [[_, 1, _, 4, _, _, _, _, _, _, _, _], # 0 [1, _, 1, 3, _, _, _, _, _, _, _, _], # 1 [_, 1, _, _, 3, 8, _, _, _, _, _, _], # 2 [4, 3, _, _, _, 2, 2, _, _, _, _, _], # 3 [_, _, 3, _, _, _, _, 1, _, _, _, _], # 4 [_, _, 8, 2, _, _, _, 2, 7, _, _, _], # 5 [_, _, _, 2, _, _, _, _, 3, 2, _, _], # 6 [_, _, _, _, 1, 2, _, _, _, _, 3, _], # 7 [_, _, _, _, _, 7, 3, _, _, _, 2, _], # 8 [_, _, _, _, _, _, 2, _, _, _, _, 1], # 9 [_, _, _, _, _, _, _, 3, 2, _, _, _], #10 [_, _, _, _, _, _, _, _, _, 1, _, _]] #11 <|code_end|> . Use current file imports: (from tryalgo.dijkstra import dijkstra from tryalgo.graph import listlist_and_matrix_to_listdict) and context including class names, function names, or small code snippets from other files: # Path: tryalgo/dijkstra.py # def dijkstra(graph, weight, source=0, target=None): # """single source shortest paths by Dijkstra # # :param graph: directed graph in listlist or listdict format # :param weight: in matrix format or same listdict graph # :assumes: weights are non-negative # :param source: source vertex # :type source: int # :param target: if given, stops once distance to target found # :type target: int # # :returns: distance table, precedence table # :complexity: `O(|V| + |E|log|V|)` # """ # n = len(graph) # assert all(weight[u][v] >= 0 for u in range(n) for v in graph[u]) # prec = [None] * n # black = [False] * n # dist = [float('inf')] * n # dist[source] = 0 # heap = [(0, source)] # while heap: # dist_node, node = heappop(heap) # Closest node from source # if not black[node]: # black[node] = True # if node == target: # break # for neighbor in graph[node]: # dist_neighbor = dist_node + weight[node][neighbor] # if dist_neighbor < dist[neighbor]: # dist[neighbor] = dist_neighbor # prec[neighbor] = node # heappush(heap, (dist_neighbor, neighbor)) # return dist, prec # # Path: tryalgo/graph.py # def listlist_and_matrix_to_listdict(graph, weight=None): # """Transforms the weighted adjacency list representation of a graph # of type listlist + optional weight matrix # into the listdict representation # # :param graph: in listlist representation # :param weight: optional weight matrix # :returns: graph in listdict representation # :complexity: linear # """ # if weight: # return [{v: weight[u][v] for v in graph[u]} for u in range(len(graph))] # else: # return [{v: None for v in graph[u]} for u in range(len(graph))] . Output only the next line.
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, _, _, _, _, _, _, _, _], # 1 [_, 1, _, _, 3, 8, _, _, _, _, _, _], # 2 [4, 3, _, _, _, 2, 2, _, _, _, _, _], # 3 [_, _, 3, _, _, _, _, 1, _, _, _, _], # 4 [_, _, 8, 2, _, _, _, 2, 7, _, _, _], # 5 [_, _, _, 2, _, _, _, _, 3, 2, _, _], # 6 [_, _, _, _, 1, 2, _, _, _, _, 3, _], # 7 [_, _, _, _, _, 7, 3, _, _, _, 2, _], # 8 [_, _, _, _, _, _, 2, _, _, _, _, 1], # 9 [_, _, _, _, _, _, _, 3, 2, _, _, _], #10 [_, _, _, _, _, _, _, _, _, 1, _, _]] #11 dist, prec = dijkstra(graph, weights, source=0) print(dist[10]) print("%i %i %i %i %i %i" % (10, prec[10], prec[prec[10]], prec[prec[prec[10]]], prec[prec[prec[prec[10]]]], prec[prec[prec[prec[prec[10]]]]])) <|code_end|> . Write the next line using the current file imports: from tryalgo.dijkstra import dijkstra from tryalgo.graph import listlist_and_matrix_to_listdict and context from other files: # Path: tryalgo/dijkstra.py # def dijkstra(graph, weight, source=0, target=None): # """single source shortest paths by Dijkstra # # :param graph: directed graph in listlist or listdict format # :param weight: in matrix format or same listdict graph # :assumes: weights are non-negative # :param source: source vertex # :type source: int # :param target: if given, stops once distance to target found # :type target: int # # :returns: distance table, precedence table # :complexity: `O(|V| + |E|log|V|)` # """ # n = len(graph) # assert all(weight[u][v] >= 0 for u in range(n) for v in graph[u]) # prec = [None] * n # black = [False] * n # dist = [float('inf')] * n # dist[source] = 0 # heap = [(0, source)] # while heap: # dist_node, node = heappop(heap) # Closest node from source # if not black[node]: # black[node] = True # if node == target: # break # for neighbor in graph[node]: # dist_neighbor = dist_node + weight[node][neighbor] # if dist_neighbor < dist[neighbor]: # dist[neighbor] = dist_neighbor # prec[neighbor] = node # heappush(heap, (dist_neighbor, neighbor)) # return dist, prec # # Path: tryalgo/graph.py # def listlist_and_matrix_to_listdict(graph, weight=None): # """Transforms the weighted adjacency list representation of a graph # of type listlist + optional weight matrix # into the listdict representation # # :param graph: in listlist representation # :param weight: optional weight matrix # :returns: graph in listdict representation # :complexity: linear # """ # if weight: # return [{v: weight[u][v] for v in graph[u]} for u in range(len(graph))] # else: # return [{v: None for v in graph[u]} for u in range(len(graph))] , which may include functions, classes, or code. Output only the next line.
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 imports: import unittest from tryalgo.arithm import inv, pgcd, binom, binom_modulo and context (class names, function names, or code) available: # Path: tryalgo/arithm.py # def inv(a, p): # """Inverse of a in :math:`{mathbb Z}_p` # # :param a,p: non-negative integers # :complexity: O(log a + log p) # """ # return bezout(a, p)[0] % p # # def pgcd(a, b): # """Greatest common divisor for a and b # # :param a,b: non-negative integers # :complexity: O(log a + log b) # """ # return a if b == 0 else pgcd(b, a % b) # # def binom(n, k): # """Binomial coefficients for :math:`n choose k` # # :param n,k: non-negative integers # :complexity: O(k) # """ # prod = 1 # for i in range(k): # prod = (prod * (n - i)) // (i + 1) # return prod # # def binom_modulo(n, k, p): # """Binomial coefficients for :math:`n choose k`, modulo p # # :param n,k: non-negative integers # :complexity: O(k) # """ # prod = 1 # for i in range(k): # prod = (prod * (n - i) * inv(i + 1, p)) % p # return prod . Output only the next line.
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) def test_binom(self): <|code_end|> using the current file's imports: import unittest from tryalgo.arithm import inv, pgcd, binom, binom_modulo and any relevant context from other files: # Path: tryalgo/arithm.py # def inv(a, p): # """Inverse of a in :math:`{mathbb Z}_p` # # :param a,p: non-negative integers # :complexity: O(log a + log p) # """ # return bezout(a, p)[0] % p # # def pgcd(a, b): # """Greatest common divisor for a and b # # :param a,b: non-negative integers # :complexity: O(log a + log b) # """ # return a if b == 0 else pgcd(b, a % b) # # def binom(n, k): # """Binomial coefficients for :math:`n choose k` # # :param n,k: non-negative integers # :complexity: O(k) # """ # prod = 1 # for i in range(k): # prod = (prod * (n - i)) // (i + 1) # return prod # # def binom_modulo(n, k, p): # """Binomial coefficients for :math:`n choose k`, modulo p # # :param n,k: non-negative integers # :complexity: O(k) # """ # prod = 1 # for i in range(k): # prod = (prod * (n - i) * inv(i + 1, p)) % p # return prod . Output only the next line.
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(4, 2), 6) def test_binom_modulo(self): <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest from tryalgo.arithm import inv, pgcd, binom, binom_modulo and context: # Path: tryalgo/arithm.py # def inv(a, p): # """Inverse of a in :math:`{mathbb Z}_p` # # :param a,p: non-negative integers # :complexity: O(log a + log p) # """ # return bezout(a, p)[0] % p # # def pgcd(a, b): # """Greatest common divisor for a and b # # :param a,b: non-negative integers # :complexity: O(log a + log b) # """ # return a if b == 0 else pgcd(b, a % b) # # def binom(n, k): # """Binomial coefficients for :math:`n choose k` # # :param n,k: non-negative integers # :complexity: O(k) # """ # prod = 1 # for i in range(k): # prod = (prod * (n - i)) // (i + 1) # return prod # # def binom_modulo(n, k, p): # """Binomial coefficients for :math:`n choose k`, modulo p # # :param n,k: non-negative integers # :complexity: O(k) # """ # prod = 1 # for i in range(k): # prod = (prod * (n - i) * inv(i + 1, p)) % p # return prod which might include code, classes, or functions. Output only the next line.
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 onBoundary = False infDescent = False self.log.info(self.header) self.log.info('-' * len(self.header)) while not (exitOptimal or exitIter or exitUser) and \ not onBoundary and not infDescent: k += 1 Hp = H * p pHp = np.dot(p, Hp) self.log.info(self.fmt % (k, ry, pHp)) # Compute steplength to the boundary. if radius is not None: <|code_end|> using the current file's imports: from nlp.tools.utils import to_boundary from nlp.tools.exceptions import UserExitRequest from math import sqrt import numpy as np import logging and any relevant context from other files: # Path: nlp/tools/utils.py # def to_boundary(x, p, delta, xx=None): # u"""Compute a solution of the quadratic trust region equation. # # Return the largest (non-negative) solution of # ‖x + σ p‖ = Δ. # # The code is only guaranteed to produce a non-negative solution # if ‖x‖ ≤ Δ, and p != 0. # If the trust region equation has no solution, σ is set to 0. # # :keywords: # :xx: squared norm of argument `x`. # """ # 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**2 + pp * (d2 - xx) # rad = sqrt(max(rad, 0.0)) # # if px > 0: # sigma = (d2 - xx) / (px + rad) # elif rad > 0: # sigma = (rad - px) / pp # else: # sigma = 0 # return sigma # # Path: nlp/tools/exceptions.py # class UserExitRequest(Exception): # """Exception that the caller can use to request clean exit.""" # # pass . Output only the next line.
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) beta = ry_next / ry p *= beta p -= y # p = -y + beta * p ry = ry_next # Transfer useful quantities for post iteration. self.pHp = pHp self.r = r self.y = y self.p = p self.step = s self.step_norm2 = snorm2 self.ry = ry self.alpha = alpha self.beta = beta sqrtry = sqrt(ry) snorm2 = np.dot(s, s) try: self.post_iteration() <|code_end|> , determine the next line of code. You have imports: from nlp.tools.utils import to_boundary from nlp.tools.exceptions import UserExitRequest from math import sqrt import numpy as np import logging and context (class names, function names, or code) available: # Path: nlp/tools/utils.py # def to_boundary(x, p, delta, xx=None): # u"""Compute a solution of the quadratic trust region equation. # # Return the largest (non-negative) solution of # ‖x + σ p‖ = Δ. # # The code is only guaranteed to produce a non-negative solution # if ‖x‖ ≤ Δ, and p != 0. # If the trust region equation has no solution, σ is set to 0. # # :keywords: # :xx: squared norm of argument `x`. # """ # 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**2 + pp * (d2 - xx) # rad = sqrt(max(rad, 0.0)) # # if px > 0: # sigma = (d2 - xx) / (px + rad) # elif rad > 0: # sigma = (rad - px) / pp # else: # sigma = 0 # return sigma # # Path: nlp/tools/exceptions.py # class UserExitRequest(Exception): # """Exception that the caller can use to request clean exit.""" # # pass . Output only the next line.
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. Thuente Line search algorithms with guaranteed sufficient decrease ACM Transactions on Mathematical Software (TOMS) Volume 20 Issue 3, pp 286-0307, 1994 DOI http://dx.doi.org/10.1145/192115.192132 """ <|code_end|> , predict the next line using imports from the current file: from math import sqrt from nlp.ls.linesearch import LineSearch, LineSearchFailure from nlp.ls._strong_wolfe_linesearch import dcsrch import numpy as np and context including class names, function names, and sometimes code from other files: # Path: nlp/ls/linesearch.py # class LineSearch(object): # class ArmijoLineSearch(LineSearch): # class ArmijoWolfeLineSearch(ArmijoLineSearch): # def __init__(self, linemodel, name="Generic Linesearch", **kwargs): # def linemodel(self): # def name(self): # def value(self): # def step(self): # def stepmin(self): # def trial_value(self): # def iterate(self): # def slope(self): # def check_slope(self, slope): # def __iter__(self): # def __next__(self): # def next(self): # def __init__(self, *args, **kwargs): # def ftol(self): # def bkmax(self): # def decr(self): # def bk(self): # def next(self): # def __init__(self, *args, **kwargs): # def gtol(self): # def wmax(self): # def incr(self): # def trial_slope(self): # def next(self): . Output only the next line.
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.finfo(np.double).eps) self.__ftol = max(min(kwargs.get("ftol", 1.0e-4), 1 - sqeps), sqeps) self.__gtol = min(max(kwargs.get("gtol", 0.9), self.ftol + sqeps), 1 - sqeps) self.__xtol = kwargs.get("xtol", 1.0e-10) self._lb = kwargs.get("lb", 0.0) self._ub = kwargs.get("ub", max(4 * min(self.step, 1.0), -0.1 * self.value / self.slope / self.ftol)) self._trial_slope = self.linemodel.grad(self.step, x=self.iterate) self.__task = "START" self.__isave = np.empty(2, dtype=np.int32) self.__dsave = np.empty(13, dtype=np.double) self._step, self.__task, self.__isave, self.__dsave = \ dcsrch(self._step, self._value, self._slope, self.ftol, self.gtol, self.xtol, self.__task, self.lb, self.ub, self.__isave, self.__dsave) if self.__task[:2] != "FG": <|code_end|> , predict the immediate next line with the help of imports: from math import sqrt from nlp.ls.linesearch import LineSearch, LineSearchFailure from nlp.ls._strong_wolfe_linesearch import dcsrch import numpy as np and context (classes, functions, sometimes code) from other files: # Path: nlp/ls/linesearch.py # class LineSearch(object): # class ArmijoLineSearch(LineSearch): # class ArmijoWolfeLineSearch(ArmijoLineSearch): # def __init__(self, linemodel, name="Generic Linesearch", **kwargs): # def linemodel(self): # def name(self): # def value(self): # def step(self): # def stepmin(self): # def trial_value(self): # def iterate(self): # def slope(self): # def check_slope(self, slope): # def __iter__(self): # def __next__(self): # def next(self): # def __init__(self, *args, **kwargs): # def ftol(self): # def bkmax(self): # def decr(self): # def bk(self): # def next(self): # def __init__(self, *args, **kwargs): # def gtol(self): # def wmax(self): # def incr(self): # def trial_slope(self): # def next(self): . Output only the next line.
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: from unittest import TestCase from nlp.model.nlpmodel import QPModel, LPModel from pykrylov.linop.linop import LinearOperator, linop_from_ndarray import numpy as np and context (class names, function names, or code) available: # Path: nlp/model/nlpmodel.py # class QPModel(NLPModel): # u"""Generic class to represent a quadratic programming (QP) problem. # # minimize cᵀx + 1/2 xᵀHx # subject to L ≤ A x ≤ U # l ≤ x ≤ u. # """ # # def __init__(self, c, H, A=None, name='GenericQP', **kwargs): # """Initialize a QP with linear term `c`, Hessian `H` and Jacobian `A`. # # :parameters: # :c: Numpy array to represent the linear objective # :A: linear operator to represent the constraint matrix. # It must be possible to perform the operations `A*x` # and `A.T*y` for Numpy arrays `x` and `y` of appropriate size. # If `A` is `None`, it will be replaced with an empty linear # operator. # :H: linear operator to represent the objective Hessian. # It must be possible to perform the operation `H*x` # for a Numpy array `x` of appropriate size. The operator `H` # should be symmetric. # # See the documentation of `NLPModel` for futher information. # """ # # Basic checks. # n = c.shape[0] # if A is None: # m = 0 # self.A = LinearOperator(n, 0, # lambda x: np.empty((0, 1)), # matvec_transp=lambda y: np.empty((n, 0)), # dtype=np.float) # else: # if A.shape[1] != n or H.shape[0] != n or H.shape[1] != n: # raise ValueError('Shapes are inconsistent') # m = A.shape[0] # self.A = A # # super(QPModel, self).__init__(n=n, m=m, name=name, **kwargs) # self.c = c # self.H = H # # # Default classification of constraints # self._lin = range(self.m) # Linear constraints # self._nln = [] # Nonlinear constraints # self._net = [] # Network constraints # self._nlin = len(self.lin) # Number of linear constraints # self._nnln = len(self.nln) # Number of nonlinear constraints # self._nnet = len(self.net) # Number of network constraints # # def obj(self, x): # """Evaluate the objective function at x.""" # cHx = self.hprod(x, 0, x) # cHx *= 0.5 # cHx += self.c # return np.dot(cHx, x) # # def grad(self, x): # """Evaluate the objective gradient at x.""" # Hx = self.hprod(x, 0, x) # Hx += self.c # return Hx # # def cons(self, x): # """Evaluate the constraints at x.""" # if isinstance(self.A, np.ndarray): # return np.dot(self.A, x) # return self.A * x # # def A(self, x): # """Evaluate the constraints Jacobian at x.""" # return self.A # # def jac(self, x): # """Evaluate the constraints Jacobian at x.""" # return self.A # # def jprod(self, x, p): # """Evaluate Jacobian-vector product at x with p.""" # return self.cons(p) # # def jtprod(self, x, p): # """Evaluate transposed-Jacobian-vector product at x with p.""" # if isinstance(self.A, np.ndarray): # return np.dot(self.A.T, p) # return self.A.T * p # # def hess(self, x, z): # """Evaluate Lagrangian Hessian at (x, z).""" # return self.H # # def hprod(self, x, z, p): # """Hessian-vector product. # # Evaluate matrix-vector product between the Hessian of the Lagrangian at # (x, z) and p. # """ # if isinstance(self.H, np.ndarray): # return np.dot(self.H, p) # return self.H * p # # class LPModel(QPModel): # u"""Generic class to represent a linear programming (LP) problem. # # minimize cᵀx # subject to L ≤ A x ≤ U # l ≤ x ≤ u. # """ # # def __init__(self, c, A=None, name='GenericLP', **kwargs): # """Initialize a LP with linear term `c` and Jacobian `A`. # # :parameters: # :c: Numpy array to represent the linear objective # :A: linear operator to represent the constraint matrix. # It must be possible to perform the operations `A*x` # and `A.T*y` for Numpy arrays `x` and `y` of appropriate size. # # See the documentation of `NLPModel` for futher information. # """ # n = c.shape[0] # H = LinearOperator(n, n, # lambda x: np.zeros(n), # symmetric=True, # dtype=np.float) # super(LPModel, self).__init__(c, H, A, name=name, **kwargs) # # def obj(self, x): # """Evaluate the objective function at x.""" # return np.dot(self.c, x) # # def grad(self, x): # """Evaluate the objective gradient at x.""" # return self.c . Output only the next line.
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**2 + pp * (d2 - xx) rad = sqrt(max(rad, 0.0)) if px > 0: sigma = (d2 - xx) / (px + rad) elif rad > 0: sigma = (rad - px) / pp else: sigma = 0 return sigma def projected_gradient_norm2(x, g, l, u): """Compute the Euclidean norm of the projected gradient at x.""" lower = where(x == l) upper = where(x == u) pg = g.copy() pg[lower] = np.minimum(g[lower], 0) pg[upper] = np.maximum(g[upper], 0) <|code_end|> , predict the next line using imports from the current file: import numpy as np import logging from math import copysign, sqrt from nlp.tools.norms import norm2 and context including class names, function names, and sometimes code from other files: # Path: nlp/tools/norms.py # def norm2(x): # """Compute 2-norm of `x`.""" # if len(x) > 0: # return norm(x) # return 0.0 . Output only the next line.
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: r = range(self.n) P.put(1, r, r) # for i in range(self.n): # P[i,i] = 1 P[self.n:, :self.n] = self.A # Add regularization if requested. if self.dreg > 0.0: r = range(self.n, self.n + self.m) P.put(-self.dreg, r, r) msg = 'Factorizing projection matrix ' msg += '(size %-d, nnz = %-d)...' % (P.shape[0], P.nnz) self.log.debug(msg) self.t_fact = cputime() self.proj = LBLContext(P) self.t_fact = cputime() - self.t_fact self.log.debug('... done (%-5.2fs)' % self.t_fact) self.factorized = True return def check_accurate(self): """Verify constraints consistency and residual accuracy.""" <|code_end|> , predict the immediate next line with the help of imports: from pysparse.sparse import spmatrix from hsl.solvers.pyma57 import PyMa57Solver as LBLContext from hsl.solvers.pyma27 import PyMa27Solver as LBLContext from nlp.tools import norms from nlp.tools.timing import cputime import logging and context (classes, functions, sometimes code) from other files: # Path: nlp/tools/norms.py # def norm1(x): # def norm2(x): # def normp(x, p): # def norm_infty(x): # def normest(A, tol=1.0e-6, maxits=100): # A = np.random.randn(n, m) # A = np.random.rand(n, n) # A = .5 * (A.T + A) # # Path: nlp/tools/timing.py # def cputime(): # """Return the user CPU time since the start of the process.""" # return resource.getrusage(resource.RUSAGE_SELF)[0] . Output only the next line.
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('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: r = range(self.n) P.put(1, r, r) # for i in range(self.n): # P[i,i] = 1 P[self.n:, :self.n] = self.A # Add regularization if requested. if self.dreg > 0.0: r = range(self.n, self.n + self.m) P.put(-self.dreg, r, r) msg = 'Factorizing projection matrix ' msg += '(size %-d, nnz = %-d)...' % (P.shape[0], P.nnz) self.log.debug(msg) <|code_end|> . Use current file imports: (from pysparse.sparse import spmatrix from hsl.solvers.pyma57 import PyMa57Solver as LBLContext from hsl.solvers.pyma27 import PyMa27Solver as LBLContext from nlp.tools import norms from nlp.tools.timing import cputime import logging) and context including class names, function names, or small code snippets from other files: # Path: nlp/tools/norms.py # def norm1(x): # def norm2(x): # def normp(x, p): # def norm_infty(x): # def normest(A, tol=1.0e-6, maxits=100): # A = np.random.randn(n, m) # A = np.random.rand(n, n) # A = .5 * (A.T + A) # # Path: nlp/tools/timing.py # def cputime(): # """Return the user CPU time since the start of the process.""" # return resource.getrusage(resource.RUSAGE_SELF)[0] . Output only the next line.
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) - 2 * (1 - x[1:-1]) return g def diags(self, x): n = self.nvar d = np.empty(n) d[:-1] = 800 * x[:-1]**2 - 400 * (x[1:] - x[:-1]**2) + 2 d[1:] += 200 d[-1] = 200 o = -400 * x[:-1] return (d, o) def hess(self, x, z): (d, o) = self.diags(x) return np.diag(d) + np.diag(o, 1) + np.diag(o, -1) def hprod(self, x, z, v): (d, o) = self.diags(x) hv = d * v hv[1:] += o * x[1:] hv[:-1] += o * x[:-1] return hv <|code_end|> . Use current file imports: import numpy as np from nlp.model.nlpmodel import UnconstrainedNLPModel from nlp.model.qnmodel import QuasiNewtonModel and context (classes, functions, or code) from other files: # Path: nlp/model/nlpmodel.py # class UnconstrainedNLPModel(NLPModel): # """Generic class to represent an unconstrained problem.""" # # def __init__(self, nvar, **kwargs): # """Initialize an unconstrained problem with ``nvar`` variables. # # See the documentation of :class:`NLPModel` for more information. # """ # # Discard options related to constrained problems. # kwargs.pop('m', None) # kwargs.pop('ncon', None) # kwargs.pop('Lcon', None) # kwargs.pop('Ucon', None) # kwargs.pop('Lvar', None) # kwargs.pop('Uvar', None) # super(UnconstrainedNLPModel, self).__init__(nvar, **kwargs) # # def cons(self, x): # """Evaluate the constraints at x.""" # return np.zeros(self.m, dtype=np.float) # # def jprod(self, x, v): # """Evaluate Jacobian-vector product at x with p.""" # return np.zeros(self.m, dtype=np.float) # # def jtprod(self, x, v): # """Evaluate transposed-Jacobian-vector product at x with p.""" # return np.zeros(self.n, dtype=np.float) # # Path: nlp/model/qnmodel.py # class QuasiNewtonModel(NLPModel): # """`NLPModel with a quasi-Newton Hessian approximation.""" # # def __init__(self, *args, **kwargs): # """Instantiate a model with quasi-Newton Hessian approximation. # # :keywords: # :H: the `class` of a quasi-Newton linear operator. # This keyword is mandatory. # # Keywords accepted by the quasi-Newton class will be passed # directly to its constructor. # """ # super(QuasiNewtonModel, self).__init__(*args, **kwargs) # qn_cls = kwargs.pop('H') # self._H = qn_cls(self.nvar, **kwargs) # # @property # def H(self): # """Quasi-Newton Hessian approximation.""" # return self._H # # def hess(self, *args, **kwargs): # """Evaluate Lagrangian Hessian at (x, z). # # This is an alias for `self.H`. # """ # return self.H # # def hop(self, *args, **kwargs): # """Obtain Lagrangian Hessian at (x, z) as a linear operator. # # This is an alias for `self.H`. # """ # return self.H # # def hprod(self, x, z, v, **kwargs): # """Hessian-vector product.""" # return self.H * v . Output only the next line.
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), sqeps) self.__bkmax = max(kwargs.get("bkmax", 20), 0) self.__eps1 = self.__eps2 = sqrt(eps) / 100 self._bk = 0 self._last_step = None self._last_trial_value = None return @property def ftol(self): return self.__ftol @property def bkmax(self): return self.__bkmax @property def bk(self): return self._bk def next(self): if self.trial_value <= self.value + self.step * self.ftol * self.slope: raise StopIteration() self._bk += 1 if self._bk > self.__bkmax: <|code_end|> . Use current file imports: from math import sqrt from nlp.ls.linesearch import LineSearch, LineSearchFailure import numpy as np and context (classes, functions, or code) from other files: # Path: nlp/ls/linesearch.py # class LineSearch(object): # class ArmijoLineSearch(LineSearch): # class ArmijoWolfeLineSearch(ArmijoLineSearch): # def __init__(self, linemodel, name="Generic Linesearch", **kwargs): # def linemodel(self): # def name(self): # def value(self): # def step(self): # def stepmin(self): # def trial_value(self): # def iterate(self): # def slope(self): # def check_slope(self, slope): # def __iter__(self): # def __next__(self): # def next(self): # def __init__(self, *args, **kwargs): # def ftol(self): # def bkmax(self): # def decr(self): # def bk(self): # def next(self): # def __init__(self, *args, **kwargs): # def gtol(self): # def wmax(self): # def incr(self): # def trial_slope(self): # def next(self): . Output only the next line.
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, default=5, dest="npairs", help="quasi-Newton memory") parser.add_argument("-b", "--backtrack", action="store_true", dest="ny", default=False, help="backtrack along rejected trust-region step") parser.add_argument("-i", "--iter", type=int, default=100, dest="maxiter", help="maximum number of iterations") # Parse command-line arguments. (args, other) = parser.parse_known_args() opts = {} # Import appropriate components. if args.sr1: opts["H"] = QNOperator opts["npairs"] = args.npairs opts["scaling"] = True else: nprobs = len(other) if nprobs == 0: raise ValueError("Please supply problem name as argument") # Create root logger. <|code_end|> , generate the next line using the imports in this file: import sys import logging from argparse import ArgumentParser from nlp.tools.logs import config_logger from nlp.model.pysparsemodel import QnPySparseAmplModel as Model from nlp.optimize.funnel import QNFunnel as Funnel from pykrylov.linop import CompactLSR1Operator as QNOperator from nlp.model.pysparsemodel import PySparseAmplModel as Model from nlp.optimize.funnel import Funnel and context (functions, classes, or occasionally code) from other files: # Path: nlp/tools/logs.py # def config_logger(name, format='%(message)s', datefmt=None, # stream=sys.stdout, level=logging.INFO, # filename=None, filemode='w', filelevel=None, # propagate=False): # """Basic configuration for the logging system. # # Similar to logging.basicConfig but the logger `name` is configurable and # both a file output and a stream output can be created. Returns a logger # object. # # The default behaviour is to create a StreamHandler which writes to # sys.stdout, set a formatter using the format string, and add the handler to # the `name` logger. # # :parameters: # # :name: Logger name # :format: handler format string (default=``%(message)s``) # :datefmt: handler date/time format specifier # :stream: initialize the StreamHandler using ``stream`` # (None disables the stream, default=``sys.stdout``) # :level: logger level (default=``INFO``). # :filename: create FileHandler using ``filename`` (default=``None``) # :filemode: open ``filename`` with specified filemode (``w`` or ``a``) # :filelevel: logger level for file logger (default=``level``) # :propagate: propagate message to parent (default=``False``) # """ # # Get a logger for the specified name # logger = logging.getLogger(name) # logger.setLevel(level) # logger.propagate = propagate # # # Remove existing handlers, otherwise multiple handlers can accrue # for hdlr in logger.handlers: # logger.removeHandler(hdlr) # # # Add handlers. Add NullHandler if no file or stream output so that # # modules don't emit a warning about no handler. # if not (filename or stream): # logger.addHandler(logging.NullHandler()) # # if filename: # hdlr = logging.FileHandler(filename, filemode) # if filelevel is None: # filelevel = level # hdlr.setLevel(filelevel) # # if stream: # hdlr = logging.StreamHandler(stream) # hdlr.setLevel(level) # # hdlr.setFormatter(logging.Formatter(format)) # logger.addHandler(hdlr) # # return logger . Output only the next line.
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('-c', '--column', action='store', type='int', default=2, dest='datacol', help='column containing the metrics') parser.add_option('-l', '--linear', action='store_false', dest='logscale', default=True, help='Use linear scale for x axis') parser.add_option('-s', '--sep', action='store', type='string', dest='sep', default=r'\s+', help='column separator (as a regexp)') parser.add_option('-t', '--title', action='store', type='string', dest='title', default='Deathmatch', help='plot title') parser.add_option('-b', '--bw', action='store_true', dest='bw', default=False, help='plot in shades of gray') # Parse command-line options. (options, args) = parser.parse_args() <|code_end|> . Write the next line using the current file imports: from nlp.tools.pprof import PerformanceProfile from optparse import OptionParser and context from other files: # Path: nlp/tools/pprof.py # class PerformanceProfile(object): # u"""Draw performance profile of Dolan and Moré.""" # # def __init__(self, solvers, **opts): # r"""Initialize a :class:`PerformanceProfile` instance. # # :parameters: # :solvers: a list of file names containing solver statistics. # Failures must be indicated with negative statistics. # :options: a dictionary of options. Currently recognized options are # listed below. # # :keywords: # :datacol: the (1-based) column index containing the relevant # metric in the solver files. # :logscale: True if log-scale ratios are requested. # :sep: the column separator as a regexp (default: r'\s+'). # :bw: True if a black and white plot is requested. # :title: string containing the plot title. # # :returns: # A :class:`PerformanceProfile` object on which `plot()` may be # called. # """ # self.solvers = solvers # self.options = default_options.copy() # for opt in opts: # self.options[opt] = opts[opt] # self.metrics = [] # A list of lists. # self.ratios = None # # map(self.add_solver, solvers) # self.compute_ratios() # # def add_solver(self, fname): # """Collect metrics for each solver.""" # comment = re.compile(r'^[\s]*[%#]') # column = re.compile(self.options['sep']) # # # Grab the column from the file. # metrics = [] # with open(fname, 'r') as fp: # for line in fp: # if not comment.match(line): # line = line.strip() # cols = column.split(line) # data = atof(cols[self.options['datacol'] - 1]) # metrics.append(data) # # self.metrics.append(metrics) # if len(metrics) != len(self.metrics[0]): # raise ValueError('All solvers must have same number of problems.') # # def compute_ratios(self): # """Compute performance ratios.""" # self.ratios = np.array(self.metrics, dtype=np.float) # nsolvs, nprobs = self.ratios.shape # # # Scale each problem metric by the best performance across solvers. # for prob in range(nprobs): # metrics = self.ratios[:, prob] # try: # # There are no > 0 vals if all solvers fail on this problem. # best = metrics[metrics > 0].min() # self.ratios[:, prob] /= best # except: # pass # # # Turn failures into large metrics. # self.max_ratio = self.ratios.max() # self.ratios[self.ratios < 0] = 2 * self.max_ratio # # # Sort the performance of each solver (in place). # for solv in range(nsolvs): # self.ratios[solv, :].sort() # # def plot(self): # """Draw performance profile.""" # import matplotlib.pyplot as plt # nsolvs, nprobs = self.ratios.shape # y = np.arange(nprobs, dtype=np.float) / nprobs # grays = ['0.0', '0.5', '0.8', '0.2', '0.6', '0.9', '0.4', '0.95'] # ngrays = len(grays) # # xmax = 1.1 * self.max_ratio # if self.options['logscale']: # xmax = max(xmax, 2) # # pltcmd = plt.semilogx if self.options['logscale'] else plt.plot # for solv in range(nsolvs): # pltargs = () # if self.options['bw']: # pltargs = (grays[solv % ngrays],) # # Draw profile tail all the way. # self.ratios[solv, -1] = xmax # line, = pltcmd(self.ratios[solv, :], y, # linewidth=2, # drawstyle='steps-pre', # antialiased=True, # alpha=0.75, # *pltargs) # line.set_label(self.solvers[solv]) # # plt.legend(loc='lower right') # ax = plt.gca() # if self.options['logscale']: # ax.set_xscale('log', basex=2) # xmax = max(xmax, 2) # ax.set_xlim([1, xmax]) # ax.set_ylim([0, 1.1]) # ax.set_xlabel('Within this factor of the best') # ax.set_ylabel('Proportion of problems') # if self.options['title'] is not None: # ax.set_title(self.options['title']) # plt.show() , which may include functions, classes, or code. Output only the next line.
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 (computed if not supplied) :slope: initial slope (computed if not supplied) :trial_value: function value at `x + t*d` (computed if not supplied) :name: linesearch procedure name. """ self.__linemodel = linemodel self.__name = name self._value = kwargs.get("value", None) if self._value is None: self._value = linemodel.obj(0) self._slope = kwargs.get("slope", None) if self._slope is None: self._slope = linemodel.grad(0) self.check_slope(self.slope) self._step0 = max(kwargs.get("step", 1.0), 0) self._step = self._step0 self._stepmin = sqrt(eps) / 100 if self._step <= self.stepmin: <|code_end|> , predict the next line using imports from the current file: from math import sqrt from nlp.tools.exceptions import LineSearchFailure import numpy as np and context including class names, function names, and sometimes code from other files: # Path: nlp/tools/exceptions.py # class LineSearchFailure(Exception): # """Exception raised when a linesearch fails.""" # # pass . Output only the next line.
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=100, dest="maxiter", help="maximum number of iterations") # Parse command-line arguments. (args, other) = parser.parse_known_args() if args.armijo: else: nprobs = len(other) if nprobs == 0: raise ValueError("Please supply problem name as argument") # Create root logger. logger = config_logger("nlp", "%(name)-3s %(levelname)-5s %(message)s") # Create LBFGS logger. slv_log = config_logger("nlp.lbfgs", "%(name)-9s %(levelname)-5s %(message)s", level=logging.WARN if nprobs > 1 else logging.INFO) logger.info("%10s %5s %6s %8s %8s %6s %6s %5s %7s", "name", "nvar", "iter", "f", u"‖∇f‖", "#f", u"#∇f", "stat", "time") for problem in other: <|code_end|> . Write the next line using the current file imports: import logging import sys from argparse import ArgumentParser from nlp.model.amplmodel import QNAmplModel from nlp.tools.logs import config_logger from pykrylov.linop import InverseLBFGSOperator from nlp.optimize.lbfgs import LBFGS from nlp.optimize.lbfgs import WolfeLBFGS as LBFGS and context from other files: # Path: nlp/model/amplmodel.py # class QNAmplModel(QuasiNewtonModel, AmplModel): # """AMPL model with quasi-Newton Hessian approximation.""" # pass # All the work is done by the parent classes. # # Path: nlp/tools/logs.py # def config_logger(name, format='%(message)s', datefmt=None, # stream=sys.stdout, level=logging.INFO, # filename=None, filemode='w', filelevel=None, # propagate=False): # """Basic configuration for the logging system. # # Similar to logging.basicConfig but the logger `name` is configurable and # both a file output and a stream output can be created. Returns a logger # object. # # The default behaviour is to create a StreamHandler which writes to # sys.stdout, set a formatter using the format string, and add the handler to # the `name` logger. # # :parameters: # # :name: Logger name # :format: handler format string (default=``%(message)s``) # :datefmt: handler date/time format specifier # :stream: initialize the StreamHandler using ``stream`` # (None disables the stream, default=``sys.stdout``) # :level: logger level (default=``INFO``). # :filename: create FileHandler using ``filename`` (default=``None``) # :filemode: open ``filename`` with specified filemode (``w`` or ``a``) # :filelevel: logger level for file logger (default=``level``) # :propagate: propagate message to parent (default=``False``) # """ # # Get a logger for the specified name # logger = logging.getLogger(name) # logger.setLevel(level) # logger.propagate = propagate # # # Remove existing handlers, otherwise multiple handlers can accrue # for hdlr in logger.handlers: # logger.removeHandler(hdlr) # # # Add handlers. Add NullHandler if no file or stream output so that # # modules don't emit a warning about no handler. # if not (filename or stream): # logger.addHandler(logging.NullHandler()) # # if filename: # hdlr = logging.FileHandler(filename, filemode) # if filelevel is None: # filelevel = level # hdlr.setLevel(filelevel) # # if stream: # hdlr = logging.StreamHandler(stream) # hdlr.setLevel(level) # # hdlr.setFormatter(logging.Formatter(format)) # logger.addHandler(hdlr) # # return logger , which may include functions, classes, or code. Output only the next line.
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-based limited-memory BFGS method in inverse form.""" # Define allowed command-line options. parser = ArgumentParser(description=desc) parser.add_argument("-p", "--pairs", type=int, 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=100, dest="maxiter", help="maximum number of iterations") # Parse command-line arguments. (args, other) = parser.parse_known_args() if args.armijo: else: nprobs = len(other) if nprobs == 0: raise ValueError("Please supply problem name as argument") # Create root logger. <|code_end|> , generate the next line using the imports in this file: import logging import sys from argparse import ArgumentParser from nlp.model.amplmodel import QNAmplModel from nlp.tools.logs import config_logger from pykrylov.linop import InverseLBFGSOperator from nlp.optimize.lbfgs import LBFGS from nlp.optimize.lbfgs import WolfeLBFGS as LBFGS and context (functions, classes, or occasionally code) from other files: # Path: nlp/model/amplmodel.py # class QNAmplModel(QuasiNewtonModel, AmplModel): # """AMPL model with quasi-Newton Hessian approximation.""" # pass # All the work is done by the parent classes. # # Path: nlp/tools/logs.py # def config_logger(name, format='%(message)s', datefmt=None, # stream=sys.stdout, level=logging.INFO, # filename=None, filemode='w', filelevel=None, # propagate=False): # """Basic configuration for the logging system. # # Similar to logging.basicConfig but the logger `name` is configurable and # both a file output and a stream output can be created. Returns a logger # object. # # The default behaviour is to create a StreamHandler which writes to # sys.stdout, set a formatter using the format string, and add the handler to # the `name` logger. # # :parameters: # # :name: Logger name # :format: handler format string (default=``%(message)s``) # :datefmt: handler date/time format specifier # :stream: initialize the StreamHandler using ``stream`` # (None disables the stream, default=``sys.stdout``) # :level: logger level (default=``INFO``). # :filename: create FileHandler using ``filename`` (default=``None``) # :filemode: open ``filename`` with specified filemode (``w`` or ``a``) # :filelevel: logger level for file logger (default=``level``) # :propagate: propagate message to parent (default=``False``) # """ # # Get a logger for the specified name # logger = logging.getLogger(name) # logger.setLevel(level) # logger.propagate = propagate # # # Remove existing handlers, otherwise multiple handlers can accrue # for hdlr in logger.handlers: # logger.removeHandler(hdlr) # # # Add handlers. Add NullHandler if no file or stream output so that # # modules don't emit a warning about no handler. # if not (filename or stream): # logger.addHandler(logging.NullHandler()) # # if filename: # hdlr = logging.FileHandler(filename, filemode) # if filelevel is None: # filelevel = level # hdlr.setLevel(filelevel) # # if stream: # hdlr = logging.StreamHandler(stream) # hdlr.setLevel(level) # # hdlr.setFormatter(logging.Formatter(format)) # logger.addHandler(hdlr) # # return logger . Output only the next line.
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 create_update_object(self, parents, data): return UpdateObject(parents, data) def create_root_object(self, gref): <|code_end|> . Write the next line using the current file imports: import unittest import tempfile import shutil from groundstation.objects.root_object import RootObject from groundstation.objects.update_object import UpdateObject and context from other files: # Path: groundstation/objects/root_object.py # class RootObject(base_object.BaseObject): # data_members = ["id", "channel", "protocol"] # # def __init__(self, id, channel, protocol): # self.id = id # self.channel = channel # self.protocol = protocol # self._sha1 = None # # @staticmethod # def from_object(obj): # """Convert an object straight from Git into a RootObject""" # protobuf = root_object_pb2.RootObject() # protobuf.ParseFromString(obj) # return RootObject(protobuf.id, protobuf.channel, protobuf.protocol) # # def as_object(self): # """Convert a RootObject into data suitable to write into the database # as a Git object""" # protobuf = root_object_pb2.RootObject() # for member in self.data_members: # setattr(protobuf, member, getattr(self, member)) # return protobuf.SerializeToString() # # def as_json(self): # return { # "id": self.id, # "channel": self.channel, # "protocol": self.protocol # } # # Path: groundstation/objects/update_object.py # class UpdateObject(base_object.BaseObject): # data_members = ["parents", "data"] # # def __init__(self, parents, data): # self.parents = parents # self.data = data # self._sha1 = None # # @staticmethod # def from_object(obj): # """Convert an object straight from Git into a RootObject""" # protobuf = update_object_pb2.UpdateObject() # protobuf.ParseFromString(obj) # return UpdateObject(protobuf.parents, protobuf.data) # # def as_object(self): # """Convert a RootObject into data suitable to write into the database # as a Git object""" # protobuf = update_object_pb2.UpdateObject() # protobuf.parents.extend(self.parents) # protobuf.data = self.data # return protobuf.SerializeToString() , which may include functions, classes, or code. Output only the next line.
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(self.path) def create_update_object(self, parents, data): <|code_end|> with the help of current file imports: import unittest import tempfile import shutil from groundstation.objects.root_object import RootObject from groundstation.objects.update_object import UpdateObject and context from other files: # Path: groundstation/objects/root_object.py # class RootObject(base_object.BaseObject): # data_members = ["id", "channel", "protocol"] # # def __init__(self, id, channel, protocol): # self.id = id # self.channel = channel # self.protocol = protocol # self._sha1 = None # # @staticmethod # def from_object(obj): # """Convert an object straight from Git into a RootObject""" # protobuf = root_object_pb2.RootObject() # protobuf.ParseFromString(obj) # return RootObject(protobuf.id, protobuf.channel, protobuf.protocol) # # def as_object(self): # """Convert a RootObject into data suitable to write into the database # as a Git object""" # protobuf = root_object_pb2.RootObject() # for member in self.data_members: # setattr(protobuf, member, getattr(self, member)) # return protobuf.SerializeToString() # # def as_json(self): # return { # "id": self.id, # "channel": self.channel, # "protocol": self.protocol # } # # Path: groundstation/objects/update_object.py # class UpdateObject(base_object.BaseObject): # data_members = ["parents", "data"] # # def __init__(self, parents, data): # self.parents = parents # self.data = data # self._sha1 = None # # @staticmethod # def from_object(obj): # """Convert an object straight from Git into a RootObject""" # protobuf = update_object_pb2.UpdateObject() # protobuf.ParseFromString(obj) # return UpdateObject(protobuf.parents, protobuf.data) # # def as_object(self): # """Convert a RootObject into data suitable to write into the database # as a Git object""" # protobuf = update_object_pb2.UpdateObject() # protobuf.parents.extend(self.parents) # protobuf.data = self.data # return protobuf.SerializeToString() , which may contain function names, class names, or code. Output only the next line.
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 Deferred, defer_until and context (classes, functions, or code) from other files: # Path: groundstation/deferred.py # class Deferred(object): # def __init__(self, at, thunk): # self.at = at # self.thunk = thunk # # def run(self): # self.thunk() # # def defer_until(at): # def make_deferred(thunk): # return Deferred(at, thunk) # return make_deferred . Output only the next line.
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.station.has_ready_deferreds()) def test_unready_deferred(self): now = time.time() deferred = Deferred(now + 60, None) self.station.register_deferred(deferred) self.assertEqual(len(self.station.deferreds), 1) self.assertFalse(self.station.has_ready_deferreds()) def test_handle_deferred(self): now = time.time() ret = [0] for i in xrange(10): # sys.stderr.write("Registering deferred %i" % i) @self.station.register_deferred <|code_end|> , continue by predicting the next line. Consider current file imports: import time import sys from support.station_fixture import StationTestCase from groundstation.deferred import Deferred, defer_until and context: # Path: groundstation/deferred.py # class Deferred(object): # def __init__(self, at, thunk): # self.at = at # self.thunk = thunk # # def run(self): # self.thunk() # # def defer_until(at): # def make_deferred(thunk): # return Deferred(at, thunk) # return make_deferred which might include code, classes, or functions. Output only the next line.
@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 GitObject from groundstation import logger and context from other files: # Path: groundstation/proto/git_object_pb2.py # class GitObject(_message.Message): # __metaclass__ = _reflection.GeneratedProtocolMessageType # DESCRIPTOR = _GITOBJECT # # # @@protoc_insertion_point(class_scope:GitObject) # # Path: groundstation/logger.py # LEVEL = getattr(logging, os.getenv("GROUNDSTATION_DEBUG")) # LEVEL = logging.DEBUG # CONSOLE_FORMATTER = _get_formatter() # CONSOLE_HANDLER = _get_console_handler() # LOGGERS = {} # Cache for instanciated loggers # def fix_oid(oid): # def _get_formatter(): # def _get_console_handler(): # def getLogger(name): # Not threadsafe , which may contain function names, class names, or code. Output only the next line.
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_fixture from groundstation.gref import Gref from support.object_fixture import update_object, root_object from groundstation.crypto.rsa import RSAAdaptor, RSAPrivateAdaptor import groundstation.store and any relevant context from other files: # Path: groundstation/gref.py # class Gref(object): # def __init__(self, store, channel, identifier): # self.store = store # self.channel = channel.replace("/", "_") # assert valid_path(self.channel), "Invalid channel" # self.identifier = identifier # assert valid_path(self.identifier), "Invalid identifier" # self._node_path = os.path.join(self.store.gref_path(), # self.channel, # self.identifier) # # def __str__(self): # return "%s/%s" % (self.channel, self.identifier) # # def exists(self): # return os.path.exists(self._node_path) # # def tips(self): # return os.listdir(self._node_path) # # def node_path(self): # if not self.exists(): # os.makedirs(self._node_path) # # return self._node_path # # def write_tip(self, tip, signature): # if signature: # signature = str(signature[0]) # tip_path = self.tip_path(tip) # open(tip_path, 'a').close() # fh = open(tip_path, 'r+') # fh.seek(0) # fh.write(signature) # 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_path(tip), 'r') as fh: # data = fh.read() # if not data: # return "" # return (int(data),) # except IOError: # return "" # # def remove_tip(self, tip, silent=False): # try: # os.unlink(os.path.join(self.tip_path(tip))) # except: # if not silent: # raise # # def direct_parents(self, tip): # """Return all parents of `tip` in the order they're written into the # object""" # obj = object_factory.hydrate_object(self.store[tip].data) # if isinstance(obj, RootObject): # # Roots can't have parents # return [] # elif isinstance(obj, UpdateObject): # return obj.parents # else: # raise "Unknown object hydrated %s" % (str(type(obj))) # # def parents(self, tips=None): # """Return all ancestors of `tip`, in an undefined order""" # # XXX This will asplode the stack at some point # parents = set() # this_iter = (tips or self.tips()) # while this_iter: # tip = this_iter.pop() # tips_parents = self.direct_parents(tip) # parents = parents.union(set(tips_parents)) # this_iter.extend(tips_parents) # return parents # # def marshall(self, crypto_adaptor=None): # """Marshalls the gref into something renderable: # { # "thread": An ordered thread of UpdateObjects. Ordering is # arbitraryish. # "roots": The root nodes of this gref. # "tips": The string names of the tips used to marshall # } # """ # thread = [] # root_nodes = [] # visited_nodes = set() # tips = [] # signatures = {} # # # TODO Big issues will smash the stack # def _process(node): # if node in visited_nodes: # log.debug("Bailing on visited node: %s" % (node)) # return # visited_nodes.add(node) # # if crypto_adaptor: # signature = self.get_signature(node) # if signature: # signatures[node] = crypto_adaptor.verify(node, signature) # # obj = object_factory.hydrate_object(self.store[node].data) # if isinstance(obj, RootObject): # We've found a root # root_nodes.append(obj) # return # for tip in obj.parents: # _process(tip) # thread.insert(0, obj) # # for tip in self: # tips.append(tip) # log.debug("Descending into %s" % (tip)) # _process(tip) # return { # "thread": thread, # "roots": root_nodes, # "tips": tips, # "signatures": signatures # } # # def as_dict(self): # return { # "channel": self.channel, # "identifier": self.identifier, # "node_path": self._node_path, # "tips": self.tips() # } # # Path: groundstation/crypto/rsa.py # class RSAAdaptor(object): # def __init__(self, keyset): # """Initialize an RSAAdaptor # # keyset = a dict of identifiers to public keys to test signatures # against # """ # self.keyset = self._render_keyset(keyset) # # def verify(self, data, signature): # assert len(data) == 40, "We only sign sha1 hashes" # for keyname in self.keyset: # key = self.keyset[keyname] # if key.verify(str(data), signature): # return keyname # return False # # def _render_keyset(self, keyset): # return {i: convert_pubkey(keyset[i]) for i in keyset} # # class RSAPrivateAdaptor(object): # def __init__(self, key): # self.key = convert_privkey(key) # # def sign(self, data): # assert len(data) == 40, "We only sign sha1 hashes" # return self.key.sign(data, None) . Output only the next line.
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) elif _type == TYPE_UPDATE: return UpdateObject.from_object(protobuf) <|code_end|> , determine the next line of code. You have imports: from groundstation.objects.base_object_pb2 import BaseObject, \ ROOT as TYPE_ROOT, \ UPDATE as TYPE_UPDATE, \ UNSET as TYPE_UNSET from groundstation.objects.root_object import RootObject from groundstation.objects.update_object import UpdateObject and context (class names, function names, or code) available: # Path: groundstation/objects/base_object_pb2.py # class BaseObject(_message.Message): # __metaclass__ = _reflection.GeneratedProtocolMessageType # DESCRIPTOR = _BASEOBJECT # # # @@protoc_insertion_point(class_scope:BaseObject) # # ROOT = 1 # # UPDATE = 2 # # UNSET = 0 # # Path: groundstation/objects/root_object.py # class RootObject(base_object.BaseObject): # data_members = ["id", "channel", "protocol"] # # def __init__(self, id, channel, protocol): # self.id = id # self.channel = channel # self.protocol = protocol # self._sha1 = None # # @staticmethod # def from_object(obj): # """Convert an object straight from Git into a RootObject""" # protobuf = root_object_pb2.RootObject() # protobuf.ParseFromString(obj) # return RootObject(protobuf.id, protobuf.channel, protobuf.protocol) # # def as_object(self): # """Convert a RootObject into data suitable to write into the database # as a Git object""" # protobuf = root_object_pb2.RootObject() # for member in self.data_members: # setattr(protobuf, member, getattr(self, member)) # return protobuf.SerializeToString() # # def as_json(self): # return { # "id": self.id, # "channel": self.channel, # "protocol": self.protocol # } # # Path: groundstation/objects/update_object.py # class UpdateObject(base_object.BaseObject): # data_members = ["parents", "data"] # # def __init__(self, parents, data): # self.parents = parents # self.data = data # self._sha1 = None # # @staticmethod # def from_object(obj): # """Convert an object straight from Git into a RootObject""" # protobuf = update_object_pb2.UpdateObject() # protobuf.ParseFromString(obj) # return UpdateObject(protobuf.parents, protobuf.data) # # def as_object(self): # """Convert a RootObject into data suitable to write into the database # as a Git object""" # protobuf = update_object_pb2.UpdateObject() # protobuf.parents.extend(self.parents) # protobuf.data = self.data # return protobuf.SerializeToString() . Output only the next line.
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. Consider current file imports: from groundstation.objects.base_object_pb2 import BaseObject, \ ROOT as TYPE_ROOT, \ UPDATE as TYPE_UPDATE, \ UNSET as TYPE_UNSET from groundstation.objects.root_object import RootObject from groundstation.objects.update_object import UpdateObject and context: # Path: groundstation/objects/base_object_pb2.py # class BaseObject(_message.Message): # __metaclass__ = _reflection.GeneratedProtocolMessageType # DESCRIPTOR = _BASEOBJECT # # # @@protoc_insertion_point(class_scope:BaseObject) # # ROOT = 1 # # UPDATE = 2 # # UNSET = 0 # # Path: groundstation/objects/root_object.py # class RootObject(base_object.BaseObject): # data_members = ["id", "channel", "protocol"] # # def __init__(self, id, channel, protocol): # self.id = id # self.channel = channel # self.protocol = protocol # self._sha1 = None # # @staticmethod # def from_object(obj): # """Convert an object straight from Git into a RootObject""" # protobuf = root_object_pb2.RootObject() # protobuf.ParseFromString(obj) # return RootObject(protobuf.id, protobuf.channel, protobuf.protocol) # # def as_object(self): # """Convert a RootObject into data suitable to write into the database # as a Git object""" # protobuf = root_object_pb2.RootObject() # for member in self.data_members: # setattr(protobuf, member, getattr(self, member)) # return protobuf.SerializeToString() # # def as_json(self): # return { # "id": self.id, # "channel": self.channel, # "protocol": self.protocol # } # # Path: groundstation/objects/update_object.py # class UpdateObject(base_object.BaseObject): # data_members = ["parents", "data"] # # def __init__(self, parents, data): # self.parents = parents # self.data = data # self._sha1 = None # # @staticmethod # def from_object(obj): # """Convert an object straight from Git into a RootObject""" # protobuf = update_object_pb2.UpdateObject() # protobuf.ParseFromString(obj) # return UpdateObject(protobuf.parents, protobuf.data) # # def as_object(self): # """Convert a RootObject into data suitable to write into the database # as a Git object""" # protobuf = update_object_pb2.UpdateObject() # protobuf.parents.extend(self.parents) # protobuf.data = self.data # return protobuf.SerializeToString() which might include code, classes, or functions. Output only the next line.
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_object(protobuf) elif _type == TYPE_UPDATE: <|code_end|> with the help of current file imports: from groundstation.objects.base_object_pb2 import BaseObject, \ ROOT as TYPE_ROOT, \ UPDATE as TYPE_UPDATE, \ UNSET as TYPE_UNSET from groundstation.objects.root_object import RootObject from groundstation.objects.update_object import UpdateObject and context from other files: # Path: groundstation/objects/base_object_pb2.py # class BaseObject(_message.Message): # __metaclass__ = _reflection.GeneratedProtocolMessageType # DESCRIPTOR = _BASEOBJECT # # # @@protoc_insertion_point(class_scope:BaseObject) # # ROOT = 1 # # UPDATE = 2 # # UNSET = 0 # # Path: groundstation/objects/root_object.py # class RootObject(base_object.BaseObject): # data_members = ["id", "channel", "protocol"] # # def __init__(self, id, channel, protocol): # self.id = id # self.channel = channel # self.protocol = protocol # self._sha1 = None # # @staticmethod # def from_object(obj): # """Convert an object straight from Git into a RootObject""" # protobuf = root_object_pb2.RootObject() # protobuf.ParseFromString(obj) # return RootObject(protobuf.id, protobuf.channel, protobuf.protocol) # # def as_object(self): # """Convert a RootObject into data suitable to write into the database # as a Git object""" # protobuf = root_object_pb2.RootObject() # for member in self.data_members: # setattr(protobuf, member, getattr(self, member)) # return protobuf.SerializeToString() # # def as_json(self): # return { # "id": self.id, # "channel": self.channel, # "protocol": self.protocol # } # # Path: groundstation/objects/update_object.py # class UpdateObject(base_object.BaseObject): # data_members = ["parents", "data"] # # def __init__(self, parents, data): # self.parents = parents # self.data = data # self._sha1 = None # # @staticmethod # def from_object(obj): # """Convert an object straight from Git into a RootObject""" # protobuf = update_object_pb2.UpdateObject() # protobuf.ParseFromString(obj) # return UpdateObject(protobuf.parents, protobuf.data) # # def as_object(self): # """Convert a RootObject into data suitable to write into the database # as a Git object""" # protobuf = update_object_pb2.UpdateObject() # protobuf.parents.extend(self.parents) # protobuf.data = self.data # return protobuf.SerializeToString() , which may contain function names, class names, or code. Output only the next line.
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, valid_path import groundstation.store and context: # Path: groundstation/gref.py # class Gref(object): # def __init__(self, store, channel, identifier): # self.store = store # self.channel = channel.replace("/", "_") # assert valid_path(self.channel), "Invalid channel" # self.identifier = identifier # assert valid_path(self.identifier), "Invalid identifier" # self._node_path = os.path.join(self.store.gref_path(), # self.channel, # self.identifier) # # def __str__(self): # return "%s/%s" % (self.channel, self.identifier) # # def exists(self): # return os.path.exists(self._node_path) # # def tips(self): # return os.listdir(self._node_path) # # def node_path(self): # if not self.exists(): # os.makedirs(self._node_path) # # return self._node_path # # def write_tip(self, tip, signature): # if signature: # signature = str(signature[0]) # tip_path = self.tip_path(tip) # open(tip_path, 'a').close() # fh = open(tip_path, 'r+') # fh.seek(0) # fh.write(signature) # 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_path(tip), 'r') as fh: # data = fh.read() # if not data: # return "" # return (int(data),) # except IOError: # return "" # # def remove_tip(self, tip, silent=False): # try: # os.unlink(os.path.join(self.tip_path(tip))) # except: # if not silent: # raise # # def direct_parents(self, tip): # """Return all parents of `tip` in the order they're written into the # object""" # obj = object_factory.hydrate_object(self.store[tip].data) # if isinstance(obj, RootObject): # # Roots can't have parents # return [] # elif isinstance(obj, UpdateObject): # return obj.parents # else: # raise "Unknown object hydrated %s" % (str(type(obj))) # # def parents(self, tips=None): # """Return all ancestors of `tip`, in an undefined order""" # # XXX This will asplode the stack at some point # parents = set() # this_iter = (tips or self.tips()) # while this_iter: # tip = this_iter.pop() # tips_parents = self.direct_parents(tip) # parents = parents.union(set(tips_parents)) # this_iter.extend(tips_parents) # return parents # # def marshall(self, crypto_adaptor=None): # """Marshalls the gref into something renderable: # { # "thread": An ordered thread of UpdateObjects. Ordering is # arbitraryish. # "roots": The root nodes of this gref. # "tips": The string names of the tips used to marshall # } # """ # thread = [] # root_nodes = [] # visited_nodes = set() # tips = [] # signatures = {} # # # TODO Big issues will smash the stack # def _process(node): # if node in visited_nodes: # log.debug("Bailing on visited node: %s" % (node)) # return # visited_nodes.add(node) # # if crypto_adaptor: # signature = self.get_signature(node) # if signature: # signatures[node] = crypto_adaptor.verify(node, signature) # # obj = object_factory.hydrate_object(self.store[node].data) # if isinstance(obj, RootObject): # We've found a root # root_nodes.append(obj) # return # for tip in obj.parents: # _process(tip) # thread.insert(0, obj) # # for tip in self: # tips.append(tip) # log.debug("Descending into %s" % (tip)) # _process(tip) # return { # "thread": thread, # "roots": root_nodes, # "tips": tips, # "signatures": signatures # } # # def as_dict(self): # return { # "channel": self.channel, # "identifier": self.identifier, # "node_path": self._node_path, # "tips": self.tips() # } # # def valid_path(path): # test_path = os.path.join("/", path) # return os.path.realpath(test_path) == test_path which might include code, classes, or functions. Output only the next line.
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()) signature = (17**23,) gref.write_tip(oid, signature) self.assertEqual(signature, gref.get_signature(oid)) def test_direct_parents(self): gref = Gref(self.repo, "testchannel", "test_write_tip") root = self.create_root_object(gref) root_oid = self.repo.create_blob(root.as_object()) first_tier = [] for i in xrange(5): obj = self.create_update_object([root_oid], "test_%i") oid = self.repo.create_blob(obj.as_object()) first_tier.append(oid) final = self.create_update_object(first_tier, "final object") final_oid = self.repo.create_blob(final.as_object()) gref.write_tip(final_oid, "") self.assertEqual(gref.direct_parents(final_oid), first_tier) def test_valid_path_works(self): <|code_end|> , generate the next line using the imports in this file: from support import store_fixture from groundstation.gref import Gref, valid_path import groundstation.store and context (functions, classes, or occasionally code) from other files: # Path: groundstation/gref.py # class Gref(object): # def __init__(self, store, channel, identifier): # self.store = store # self.channel = channel.replace("/", "_") # assert valid_path(self.channel), "Invalid channel" # self.identifier = identifier # assert valid_path(self.identifier), "Invalid identifier" # self._node_path = os.path.join(self.store.gref_path(), # self.channel, # self.identifier) # # def __str__(self): # return "%s/%s" % (self.channel, self.identifier) # # def exists(self): # return os.path.exists(self._node_path) # # def tips(self): # return os.listdir(self._node_path) # # def node_path(self): # if not self.exists(): # os.makedirs(self._node_path) # # return self._node_path # # def write_tip(self, tip, signature): # if signature: # signature = str(signature[0]) # tip_path = self.tip_path(tip) # open(tip_path, 'a').close() # fh = open(tip_path, 'r+') # fh.seek(0) # fh.write(signature) # 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_path(tip), 'r') as fh: # data = fh.read() # if not data: # return "" # return (int(data),) # except IOError: # return "" # # def remove_tip(self, tip, silent=False): # try: # os.unlink(os.path.join(self.tip_path(tip))) # except: # if not silent: # raise # # def direct_parents(self, tip): # """Return all parents of `tip` in the order they're written into the # object""" # obj = object_factory.hydrate_object(self.store[tip].data) # if isinstance(obj, RootObject): # # Roots can't have parents # return [] # elif isinstance(obj, UpdateObject): # return obj.parents # else: # raise "Unknown object hydrated %s" % (str(type(obj))) # # def parents(self, tips=None): # """Return all ancestors of `tip`, in an undefined order""" # # XXX This will asplode the stack at some point # parents = set() # this_iter = (tips or self.tips()) # while this_iter: # tip = this_iter.pop() # tips_parents = self.direct_parents(tip) # parents = parents.union(set(tips_parents)) # this_iter.extend(tips_parents) # return parents # # def marshall(self, crypto_adaptor=None): # """Marshalls the gref into something renderable: # { # "thread": An ordered thread of UpdateObjects. Ordering is # arbitraryish. # "roots": The root nodes of this gref. # "tips": The string names of the tips used to marshall # } # """ # thread = [] # root_nodes = [] # visited_nodes = set() # tips = [] # signatures = {} # # # TODO Big issues will smash the stack # def _process(node): # if node in visited_nodes: # log.debug("Bailing on visited node: %s" % (node)) # return # visited_nodes.add(node) # # if crypto_adaptor: # signature = self.get_signature(node) # if signature: # signatures[node] = crypto_adaptor.verify(node, signature) # # obj = object_factory.hydrate_object(self.store[node].data) # if isinstance(obj, RootObject): # We've found a root # root_nodes.append(obj) # return # for tip in obj.parents: # _process(tip) # thread.insert(0, obj) # # for tip in self: # tips.append(tip) # log.debug("Descending into %s" % (tip)) # _process(tip) # return { # "thread": thread, # "roots": root_nodes, # "tips": tips, # "signatures": signatures # } # # def as_dict(self): # return { # "channel": self.channel, # "identifier": self.identifier, # "node_path": self._node_path, # "tips": self.tips() # } # # def valid_path(path): # test_path = os.path.join("/", path) # return os.path.realpath(test_path) == test_path . Output only the next line.
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(StationIntegrationFixture): def test_send_objects(self): read_sockets = [] write_sockets = [] def tick(): return select.select(read_sockets, write_sockets, [], 1) addr = os.path.join(self.dir, "listener") listener = TestListener(addr) read_sockets.append(listener) client = TestClient(addr) write_sockets.append(client) (sread, swrite, _) = tick() # Handle our listener self.assertEqual(len(sread), 1) <|code_end|> . Use current file imports: import os import socket import select import unittest import tempfile import shutil from groundstation.peer_socket import PeerSocket from integration_fixture import StationIntegrationFixture, \ TestListener, \ TestClient and context (classes, functions, or code) from other files: # Path: groundstation/peer_socket.py # class PeerSocket(StreamSocket): # """Wrapper for a peer who just connected, or one we've connected to # # Since the communication protocol should be implicitly bidirectional, the # factory methods should be the only instanciation methods""" # # def __init__(self, conn, peer): # self._sock = conn # super(PeerSocket, self).__init__() # self.peer = peer # # @classmethod # def from_accept(klass, args): # return klass(*args) # # @classmethod # def from_connect(klass, args): # return klass(*args) # # def __repr__(self): # return "<%s: from %s>" % (self.__class__, self.peer) # # # Wrap StreamSocket's send and recv in exception handling # def send(self, *args, **kwargs): # try: # return super(PeerSocket, self).send(*args, **kwargs) # except socket.error as e: # self.close_and_finalise() # # def recv(self, *args, **kwargs): # try: # return super(PeerSocket, self).recv(*args, **kwargs) # except socket.error as e: # self.close_and_finalise() . Output only the next line.
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 elif header_byte_count == 2: header_bytes[1] |= (char_value & 0xf) header_byte_count += 1 elif header_byte_count == 3: header_bytes[1] |= (char_value & 0xf) << 4 header_byte_count += 1 header_length = struct.unpack(">h", ''.join(map(chr, header_bytes)))[0] log.info("Reading %d bytes of payload" % header_length) payload = reset_payload() elif header_byte_count == 4: log.warning("Got header bytes while still expecting payload") payload.append(char) else: # Payload byte if header_length == 0: log.warning("Got payload bytes when expecting header") payload.append(char) if len(payload) % 8 == 0: log.info("Got %d bytes so far" % (len(payload))) if len(payload) == header_length: log.info("Got all of object") decoded = base64.b64decode(''.join(payload)) log.info("Writing payload to DB") oid = self.station.write(decoded) log.info("Wrote object, got: %s" % (repr(oid))) <|code_end|> using the current file's imports: import struct import base64 import quietnet.listen as listen from groundstation.gref import Gref, Tip from groundstation import logger and any relevant context from other files: # Path: groundstation/gref.py # def valid_path(path): # def __init__(self, store, channel, identifier): # def __str__(self): # def exists(self): # def tips(self): # def node_path(self): # def write_tip(self, tip, signature): # def tip_path(self, tip): # def __iter__(self): # def get_signature(self, tip): # def remove_tip(self, tip, silent=False): # def direct_parents(self, tip): # def parents(self, tips=None): # def marshall(self, crypto_adaptor=None): # def _process(node): # def as_dict(self): # class Gref(object): # # Path: groundstation/logger.py # LEVEL = getattr(logging, os.getenv("GROUNDSTATION_DEBUG")) # LEVEL = logging.DEBUG # CONSOLE_FORMATTER = _get_formatter() # CONSOLE_HANDLER = _get_console_handler() # LOGGERS = {} # Cache for instanciated loggers # def fix_oid(oid): # def _get_formatter(): # def _get_console_handler(): # def getLogger(name): # Not threadsafe . Output only the next line.
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) header_byte_count += 1 elif header_byte_count == 3: header_bytes[1] |= (char_value & 0xf) << 4 header_byte_count += 1 header_length = struct.unpack(">h", ''.join(map(chr, header_bytes)))[0] log.info("Reading %d bytes of payload" % header_length) payload = reset_payload() elif header_byte_count == 4: log.warning("Got header bytes while still expecting payload") payload.append(char) else: # Payload byte if header_length == 0: log.warning("Got payload bytes when expecting header") payload.append(char) if len(payload) % 8 == 0: log.info("Got %d bytes so far" % (len(payload))) if len(payload) == header_length: log.info("Got all of object") decoded = base64.b64decode(''.join(payload)) log.info("Writing payload to DB") oid = self.station.write(decoded) log.info("Wrote object, got: %s" % (repr(oid))) Gref(self.station.store, "soundstation", "demo") try: <|code_end|> using the current file's imports: import struct import base64 import quietnet.listen as listen from groundstation.gref import Gref, Tip from groundstation import logger and any relevant context from other files: # Path: groundstation/gref.py # def valid_path(path): # def __init__(self, store, channel, identifier): # def __str__(self): # def exists(self): # def tips(self): # def node_path(self): # def write_tip(self, tip, signature): # def tip_path(self, tip): # def __iter__(self): # def get_signature(self, tip): # def remove_tip(self, tip, silent=False): # def direct_parents(self, tip): # def parents(self, tips=None): # def marshall(self, crypto_adaptor=None): # def _process(node): # def as_dict(self): # class Gref(object): # # Path: groundstation/logger.py # LEVEL = getattr(logging, os.getenv("GROUNDSTATION_DEBUG")) # LEVEL = logging.DEBUG # CONSOLE_FORMATTER = _get_formatter() # CONSOLE_HANDLER = _get_console_handler() # LOGGERS = {} # Cache for instanciated loggers # def fix_oid(oid): # def _get_formatter(): # def _get_console_handler(): # def getLogger(name): # Not threadsafe . Output only the next line.
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.extend(parents) update.data = "butts" if not weak: update.type = TYPE_UPDATE return update class TypeOfTestCase(unittest.TestCase): def test_strongly_typed_root(self): root_str = new_root_object(False).SerializeToString() self.assertEqual(object_factory.type_of(root_str), TYPE_ROOT) def test_weakly_typed_root(self): root_str = new_root_object(True).SerializeToString() <|code_end|> , predict the immediate next line with the help of imports: import unittest import groundstation.objects.object_factory as object_factory from groundstation.objects.base_object_pb2 import BaseObject, \ ROOT as TYPE_ROOT, \ UPDATE as TYPE_UPDATE, \ UNSET as TYPE_UNSET from groundstation.objects.root_object_pb2 import RootObject from groundstation.objects.update_object_pb2 import UpdateObject and context (classes, functions, sometimes code) from other files: # Path: groundstation/objects/base_object_pb2.py # class BaseObject(_message.Message): # __metaclass__ = _reflection.GeneratedProtocolMessageType # DESCRIPTOR = _BASEOBJECT # # # @@protoc_insertion_point(class_scope:BaseObject) # # ROOT = 1 # # UPDATE = 2 # # UNSET = 0 # # Path: groundstation/objects/root_object_pb2.py # class RootObject(_message.Message): # __metaclass__ = _reflection.GeneratedProtocolMessageType # DESCRIPTOR = _ROOTOBJECT # # # @@protoc_insertion_point(class_scope:RootObject) # # Path: groundstation/objects/update_object_pb2.py # class UpdateObject(_message.Message): # __metaclass__ = _reflection.GeneratedProtocolMessageType # DESCRIPTOR = _UPDATEOBJECT # # # @@protoc_insertion_point(class_scope:UpdateObject) . Output only the next line.
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 current file's imports: import unittest import groundstation.objects.object_factory as object_factory from groundstation.objects.base_object_pb2 import BaseObject, \ ROOT as TYPE_ROOT, \ UPDATE as TYPE_UPDATE, \ UNSET as TYPE_UNSET from groundstation.objects.root_object_pb2 import RootObject from groundstation.objects.update_object_pb2 import UpdateObject and any relevant context from other files: # Path: groundstation/objects/base_object_pb2.py # class BaseObject(_message.Message): # __metaclass__ = _reflection.GeneratedProtocolMessageType # DESCRIPTOR = _BASEOBJECT # # # @@protoc_insertion_point(class_scope:BaseObject) # # ROOT = 1 # # UPDATE = 2 # # UNSET = 0 # # Path: groundstation/objects/root_object_pb2.py # class RootObject(_message.Message): # __metaclass__ = _reflection.GeneratedProtocolMessageType # DESCRIPTOR = _ROOTOBJECT # # # @@protoc_insertion_point(class_scope:RootObject) # # Path: groundstation/objects/update_object_pb2.py # class UpdateObject(_message.Message): # __metaclass__ = _reflection.GeneratedProtocolMessageType # DESCRIPTOR = _UPDATEOBJECT # # # @@protoc_insertion_point(class_scope:UpdateObject) . Output only the next line.
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_object import UpdateObject and context (functions, classes, or occasionally code) from other files: # Path: groundstation/objects/root_object.py # class RootObject(base_object.BaseObject): # data_members = ["id", "channel", "protocol"] # # def __init__(self, id, channel, protocol): # self.id = id # self.channel = channel # self.protocol = protocol # self._sha1 = None # # @staticmethod # def from_object(obj): # """Convert an object straight from Git into a RootObject""" # protobuf = root_object_pb2.RootObject() # protobuf.ParseFromString(obj) # return RootObject(protobuf.id, protobuf.channel, protobuf.protocol) # # def as_object(self): # """Convert a RootObject into data suitable to write into the database # as a Git object""" # protobuf = root_object_pb2.RootObject() # for member in self.data_members: # setattr(protobuf, member, getattr(self, member)) # return protobuf.SerializeToString() # # def as_json(self): # return { # "id": self.id, # "channel": self.channel, # "protocol": self.protocol # } # # Path: groundstation/objects/update_object.py # class UpdateObject(base_object.BaseObject): # data_members = ["parents", "data"] # # def __init__(self, parents, data): # self.parents = parents # self.data = data # self._sha1 = None # # @staticmethod # def from_object(obj): # """Convert an object straight from Git into a RootObject""" # protobuf = update_object_pb2.UpdateObject() # protobuf.ParseFromString(obj) # return UpdateObject(protobuf.parents, protobuf.data) # # def as_object(self): # """Convert a RootObject into data suitable to write into the database # as a Git object""" # protobuf = update_object_pb2.UpdateObject() # protobuf.parents.extend(self.parents) # protobuf.data = self.data # return protobuf.SerializeToString() . Output only the next line.
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 and context (class names, function names, or code) available: # Path: groundstation/node.py # class Node(object): # def __init__(self): # self.uuid = uuid.uuid1() # self.name = str(self.uuid) # log.info("Node started with id %s" % self.name) # # Path: groundstation/station.py # class Station(object): # def __init__(self, path, identity): # self.identity = identity # self.store = store.STORAGE_BACKENDS[settings.STORAGE_BACKEND](path) # self.gizmo_factory = GizmoFactory(self, identity) # self.identity_cache = {} # self.registry = RequestRegistry() # self.iterators = [] # self.deferreds = [] # # @staticmethod # def from_env(identity): # if "GROUNDSTATION_HOME" in os.environ: # return Station(os.getenv("GROUNDSTATION_HOME"), identity) # else: # station_path = os.path.expanduser("~/.groundstation") # return Station(station_path, identity) # # def get_crypto_adaptor(self): # return RSAAdaptor(self.store.get_public_keys()) # # def get_private_crypto_adaptor(self, keyname): # return RSAPrivateAdaptor(self.store.get_private_key(keyname)) # # def get_request(self, request_id): # return self.registry[request_id] # # def register_request(self, request): # log.debug("Registering request %s" % (str(request.id))) # self.registry.register(request) # # def free_request(self, request): # log.debug("Freeing request %s" % (str(request.id))) # return self.registry.free(request) # # def register_iter(self, iterator): # log.info("Registering iterator %s" % (repr(iterator))) # self.iterators.append(iterator()) # # def register_deferred(self, deferred): # log.info("Registering deferred %s" % (repr(deferred))) # self.deferreds.append(deferred) # # def has_ready_iterators(self): # return len(self.iterators) > 0 # # def has_ready_deferreds(self): # now = time.time() # for i in self.deferreds: # if i.at < now: # return True # return False # # def handle_iters(self): # for i in self.iterators: # try: # i.next() # except StopIteration: # self.iterators.remove(i) # # def handle_deferreds(self): # now = time.time() # new_deferreds = [] # while self.deferreds: # i = self.deferreds.pop(0) # if i.at < now: # i.run() # else: # new_deferreds.append(i) # [self.deferreds.append(i) for i in new_deferreds] # # def channels(self): # return os.listdir(self.store.gref_path()) # # channels = {} # # for channel in os.listdir(self.store.gref_path()): # # channels["channel"] = Channel(self.store, channel) # # def create_channel(self, channel_name): # try: # os.mkdir(os.path.join(self.store.gref_path(), channel_name)) # return True # except OSError: # return False # # def grefs(self, channel): # channel_path = os.path.join(self.store.gref_path(), channel) # if not groundstation.utils.is_dir(channel_path): # raise NonExistantChannel() # grefs = [] # for id in groundstation.utils.find_leaf_dirs(channel_path, True): # grefs.append(Gref(self.store, channel, id)) # return grefs # # # Delegate some methods to the store # def write(self, obj): # log.info("Writing object to db") # oid = self.store.create_blob(obj) # log.info("Wrote object %s" % oid) # return oid # # def objects(self): # return self.store.objects() # # def __getitem__(self, key): # return self.store.__getitem__(key) # # def __contains__(self, item): # return self.store.__contains__(item) # # End delegates to store # # def update_gref(self, gref, tips, parents=[]): # log.debug("updating %s - %s => %s" % (gref.channel, gref.identifier, tips)) # node_path = gref.node_path() # tip_oids = [] # for tip in tips: # gref.write_tip(tip.tip, tip.signature) # tip_oids.append(tip.tip) # if parents is True: # parents = gref.parents(tip_oids) # for parent in parents: # gref.remove_tip(parent, True) # # def recently_queried(self, identity): # """CAS the cache status of a given identity. # # Returns False if you should query them.""" # val = str(identity) # if val not in self.identity_cache: # self.mark_queried(identity) # return False # else: # if self.identity_cache[val] + settings.DEFAULT_CACHE_LIFETIME > time.time(): # return True # else: # self.mark_queried(identity) # return False # # def mark_queried(self, identity): # val = str(identity) # self.identity_cache[val] = time.time() # # def get_hash(self, prefix): # # TODO This depends heavily on the order that objects() returns # sha = hashlib.sha1() # for oid in sorted(self.objects()): # name = groundstation.utils.oid2hex(oid) # if name.startswith(prefix): # sha.update(name) # return sha.digest() . Output only the next line.
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 the station for gizmo_factory in the constructor listobjects = groundstation.transfer.request.Request("LISTALLOBJECTS", station=self.station, stream=self.stream) self.station.register_request(listobjects) self.stream.enqueue(listobjects) else: log.info("object cache for %s still valid" % (self.origin)) log.info("Handling LISTALLOBJECTS") payload = [groundstation.utils.oid2hex(i) for i in self.station.objects()] <|code_end|> , continue by predicting the next line. Consider current file imports: import groundstation.transfer.request import groundstation.proto.object_list_pb2 import groundstation.utils from groundstation import settings from groundstation import logger and context: # Path: groundstation/settings.py # PORT=1248 # Port to listen on (udp+tcp) # BEACON_TIMEOUT=5 # 5 second timeout between beacons # DEFAULT_BUFSIZE=8192 # 8k bytes # DEFAULT_CACHE_LIFETIME=30 # 30 Seconds # STORAGE_BACKEND="git" # LISTALLOBJECTS_CHUNK_THRESHOLD=1024 # LISTALLCHANNELS_RETRY_TIMEOUT=5 # CLOSEWAIT_TIMEOUT=240 # 2MSL # # Path: groundstation/logger.py # LEVEL = getattr(logging, os.getenv("GROUNDSTATION_DEBUG")) # LEVEL = logging.DEBUG # CONSOLE_FORMATTER = _get_formatter() # CONSOLE_HANDLER = _get_console_handler() # LOGGERS = {} # Cache for instanciated loggers # def fix_oid(oid): # def _get_formatter(): # def _get_console_handler(): # def getLogger(name): # Not threadsafe which might include code, classes, or functions. Output only the next line.
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" ) hydrated_root = object_factory.hydrate_object(root.as_object()) self.assertTrue(isinstance(hydrated_root, RootObject)) class TestUpdateObject(unittest.TestCase): def test_hydate_update_with_1_parent(self): <|code_end|> . Use current file imports: (import unittest import groundstation.objects.object_factory as object_factory from groundstation.objects.root_object import RootObject from groundstation.objects.update_object import UpdateObject) and context including class names, function names, or small code snippets from other files: # Path: groundstation/objects/root_object.py # class RootObject(base_object.BaseObject): # data_members = ["id", "channel", "protocol"] # # def __init__(self, id, channel, protocol): # self.id = id # self.channel = channel # self.protocol = protocol # self._sha1 = None # # @staticmethod # def from_object(obj): # """Convert an object straight from Git into a RootObject""" # protobuf = root_object_pb2.RootObject() # protobuf.ParseFromString(obj) # return RootObject(protobuf.id, protobuf.channel, protobuf.protocol) # # def as_object(self): # """Convert a RootObject into data suitable to write into the database # as a Git object""" # protobuf = root_object_pb2.RootObject() # for member in self.data_members: # setattr(protobuf, member, getattr(self, member)) # return protobuf.SerializeToString() # # def as_json(self): # return { # "id": self.id, # "channel": self.channel, # "protocol": self.protocol # } # # Path: groundstation/objects/update_object.py # class UpdateObject(base_object.BaseObject): # data_members = ["parents", "data"] # # def __init__(self, parents, data): # self.parents = parents # self.data = data # self._sha1 = None # # @staticmethod # def from_object(obj): # """Convert an object straight from Git into a RootObject""" # protobuf = update_object_pb2.UpdateObject() # protobuf.ParseFromString(obj) # return UpdateObject(protobuf.parents, protobuf.data) # # def as_object(self): # """Convert a RootObject into data suitable to write into the database # as a Git object""" # protobuf = update_object_pb2.UpdateObject() # protobuf.parents.extend(self.parents) # protobuf.data = self.data # return protobuf.SerializeToString() . Output only the next line.
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) self.assertFalse(key.has_private()) def test_convertes_privkey_to_pem(self): key = convert_privkey(crypto_fixture.valid_key) self.assertIsInstance(key, RSA._RSAobj) self.assertTrue(key.has_private()) def test_barfs_on_invalid_keys(self): self.assertRaises(TypeError, convert_pubkey, crypto_fixture.invalid_pubkey) def test_initializes_with_keyset(self): <|code_end|> , predict the immediate next line with the help of imports: import unittest from Crypto.PublicKey import RSA from support import crypto_fixture from groundstation.crypto.rsa import RSAAdaptor, RSAPrivateAdaptor from groundstation.crypto.rsa import convert_privkey, convert_pubkey from groundstation.crypto.rsa import materialise_exponent, materialise_numeric and context (classes, functions, sometimes code) from other files: # Path: groundstation/crypto/rsa.py # class RSAAdaptor(object): # def __init__(self, keyset): # """Initialize an RSAAdaptor # # keyset = a dict of identifiers to public keys to test signatures # against # """ # self.keyset = self._render_keyset(keyset) # # def verify(self, data, signature): # assert len(data) == 40, "We only sign sha1 hashes" # for keyname in self.keyset: # key = self.keyset[keyname] # if key.verify(str(data), signature): # return keyname # return False # # def _render_keyset(self, keyset): # return {i: convert_pubkey(keyset[i]) for i in keyset} # # class RSAPrivateAdaptor(object): # def __init__(self, key): # self.key = convert_privkey(key) # # def sign(self, data): # assert len(data) == 40, "We only sign sha1 hashes" # return self.key.sign(data, None) # # Path: groundstation/crypto/rsa.py # def convert_privkey(key): # pkey = RSA.importKey(key) # assert pkey.has_private() # return pkey # # def convert_pubkey(key): # # get the second field from the public key file. # # import pdb; pdb.set_trace() # keydata = base64.b64decode(key.split(None)[1]) # # parts = [] # while keydata: # # read the length of the data # dlen = struct.unpack('>I', keydata[:4])[0] # # # read in <length> bytes # data, keydata = keydata[4:dlen+4], keydata[4+dlen:] # # parts.append(data) # exponent = materialise(parts[1]) # numeric = materialise(parts[2]) # # return RSA.construct((long(numeric), long(exponent))) # # Path: groundstation/crypto/rsa.py # def materialise(n): # def convert_pubkey(key): # def convert_privkey(key): # def __init__(self, keyset): # def verify(self, data, signature): # def _render_keyset(self, keyset): # def __init__(self, key): # def sign(self, data): # class RSAAdaptor(object): # class RSAPrivateAdaptor(object): . Output only the next line.
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.assertFalse(key.has_private()) def test_convertes_privkey_to_pem(self): key = convert_privkey(crypto_fixture.valid_key) self.assertIsInstance(key, RSA._RSAobj) self.assertTrue(key.has_private()) def test_barfs_on_invalid_keys(self): self.assertRaises(TypeError, convert_pubkey, crypto_fixture.invalid_pubkey) def test_initializes_with_keyset(self): 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, RSAAdaptor) def test_signs_data(self): <|code_end|> , determine the next line of code. You have imports: import unittest from Crypto.PublicKey import RSA from support import crypto_fixture from groundstation.crypto.rsa import RSAAdaptor, RSAPrivateAdaptor from groundstation.crypto.rsa import convert_privkey, convert_pubkey from groundstation.crypto.rsa import materialise_exponent, materialise_numeric and context (class names, function names, or code) available: # Path: groundstation/crypto/rsa.py # class RSAAdaptor(object): # def __init__(self, keyset): # """Initialize an RSAAdaptor # # keyset = a dict of identifiers to public keys to test signatures # against # """ # self.keyset = self._render_keyset(keyset) # # def verify(self, data, signature): # assert len(data) == 40, "We only sign sha1 hashes" # for keyname in self.keyset: # key = self.keyset[keyname] # if key.verify(str(data), signature): # return keyname # return False # # def _render_keyset(self, keyset): # return {i: convert_pubkey(keyset[i]) for i in keyset} # # class RSAPrivateAdaptor(object): # def __init__(self, key): # self.key = convert_privkey(key) # # def sign(self, data): # assert len(data) == 40, "We only sign sha1 hashes" # return self.key.sign(data, None) # # Path: groundstation/crypto/rsa.py # def convert_privkey(key): # pkey = RSA.importKey(key) # assert pkey.has_private() # return pkey # # def convert_pubkey(key): # # get the second field from the public key file. # # import pdb; pdb.set_trace() # keydata = base64.b64decode(key.split(None)[1]) # # parts = [] # while keydata: # # read the length of the data # dlen = struct.unpack('>I', keydata[:4])[0] # # # read in <length> bytes # data, keydata = keydata[4:dlen+4], keydata[4+dlen:] # # parts.append(data) # exponent = materialise(parts[1]) # numeric = materialise(parts[2]) # # return RSA.construct((long(numeric), long(exponent))) # # Path: groundstation/crypto/rsa.py # def materialise(n): # def convert_pubkey(key): # def convert_privkey(key): # def __init__(self, keyset): # def verify(self, data, signature): # def _render_keyset(self, keyset): # def __init__(self, key): # def sign(self, data): # class RSAAdaptor(object): # class RSAPrivateAdaptor(object): . Output only the next line.
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) self.assertFalse(key.has_private()) def test_convertes_privkey_to_pem(self): <|code_end|> . Write the next line using the current file imports: import unittest from Crypto.PublicKey import RSA from support import crypto_fixture from groundstation.crypto.rsa import RSAAdaptor, RSAPrivateAdaptor from groundstation.crypto.rsa import convert_privkey, convert_pubkey from groundstation.crypto.rsa import materialise_exponent, materialise_numeric and context from other files: # Path: groundstation/crypto/rsa.py # class RSAAdaptor(object): # def __init__(self, keyset): # """Initialize an RSAAdaptor # # keyset = a dict of identifiers to public keys to test signatures # against # """ # self.keyset = self._render_keyset(keyset) # # def verify(self, data, signature): # assert len(data) == 40, "We only sign sha1 hashes" # for keyname in self.keyset: # key = self.keyset[keyname] # if key.verify(str(data), signature): # return keyname # return False # # def _render_keyset(self, keyset): # return {i: convert_pubkey(keyset[i]) for i in keyset} # # class RSAPrivateAdaptor(object): # def __init__(self, key): # self.key = convert_privkey(key) # # def sign(self, data): # assert len(data) == 40, "We only sign sha1 hashes" # return self.key.sign(data, None) # # Path: groundstation/crypto/rsa.py # def convert_privkey(key): # pkey = RSA.importKey(key) # assert pkey.has_private() # return pkey # # def convert_pubkey(key): # # get the second field from the public key file. # # import pdb; pdb.set_trace() # keydata = base64.b64decode(key.split(None)[1]) # # parts = [] # while keydata: # # read the length of the data # dlen = struct.unpack('>I', keydata[:4])[0] # # # read in <length> bytes # data, keydata = keydata[4:dlen+4], keydata[4+dlen:] # # parts.append(data) # exponent = materialise(parts[1]) # numeric = materialise(parts[2]) # # return RSA.construct((long(numeric), long(exponent))) # # Path: groundstation/crypto/rsa.py # def materialise(n): # def convert_pubkey(key): # def convert_privkey(key): # def __init__(self, keyset): # def verify(self, data, signature): # def _render_keyset(self, keyset): # def __init__(self, key): # def sign(self, data): # class RSAAdaptor(object): # class RSAPrivateAdaptor(object): , which may include functions, classes, or code. Output only the next line.
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.PublicKey import RSA from support import crypto_fixture from groundstation.crypto.rsa import RSAAdaptor, RSAPrivateAdaptor from groundstation.crypto.rsa import convert_privkey, convert_pubkey from groundstation.crypto.rsa import materialise_exponent, materialise_numeric and context: # Path: groundstation/crypto/rsa.py # class RSAAdaptor(object): # def __init__(self, keyset): # """Initialize an RSAAdaptor # # keyset = a dict of identifiers to public keys to test signatures # against # """ # self.keyset = self._render_keyset(keyset) # # def verify(self, data, signature): # assert len(data) == 40, "We only sign sha1 hashes" # for keyname in self.keyset: # key = self.keyset[keyname] # if key.verify(str(data), signature): # return keyname # return False # # def _render_keyset(self, keyset): # return {i: convert_pubkey(keyset[i]) for i in keyset} # # class RSAPrivateAdaptor(object): # def __init__(self, key): # self.key = convert_privkey(key) # # def sign(self, data): # assert len(data) == 40, "We only sign sha1 hashes" # return self.key.sign(data, None) # # Path: groundstation/crypto/rsa.py # def convert_privkey(key): # pkey = RSA.importKey(key) # assert pkey.has_private() # return pkey # # def convert_pubkey(key): # # get the second field from the public key file. # # import pdb; pdb.set_trace() # keydata = base64.b64decode(key.split(None)[1]) # # parts = [] # while keydata: # # read the length of the data # dlen = struct.unpack('>I', keydata[:4])[0] # # # read in <length> bytes # data, keydata = keydata[4:dlen+4], keydata[4+dlen:] # # parts.append(data) # exponent = materialise(parts[1]) # numeric = materialise(parts[2]) # # return RSA.construct((long(numeric), long(exponent))) # # Path: groundstation/crypto/rsa.py # def materialise(n): # def convert_pubkey(key): # def convert_privkey(key): # def __init__(self, keyset): # def verify(self, data, signature): # def _render_keyset(self, keyset): # def __init__(self, key): # def sign(self, data): # class RSAAdaptor(object): # class RSAPrivateAdaptor(object): which might include code, classes, or functions. Output only the next line.
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, RSAAdaptor) def test_signs_data(self): adaptor = RSAPrivateAdaptor(crypto_fixture.valid_key) signature = adaptor.sign(crypto_fixture.sample_data) self.assertEqual(signature, crypto_fixture.signatures["sample_data"]["valid_key"]) def test_verifies_data(self): adaptor = RSAAdaptor({"key1": crypto_fixture.valid_pubkey}) self.assertEqual("key1", adaptor.verify( crypto_fixture.sample_data, crypto_fixture.signatures["sample_data"]["valid_key"] )) def test_returns_false_for_unverified_data(self): adaptor = RSAAdaptor({"key1": crypto_fixture.passphrase_pubkey}) self.assertFalse(adaptor.verify( crypto_fixture.sample_data, crypto_fixture.signatures["sample_data"]["valid_key"] )) def test_materialise_helpers(self): self.assertEqual(crypto_fixture.materialize_out, <|code_end|> . Write the next line using the current file imports: import unittest from Crypto.PublicKey import RSA from support import crypto_fixture from groundstation.crypto.rsa import RSAAdaptor, RSAPrivateAdaptor from groundstation.crypto.rsa import convert_privkey, convert_pubkey from groundstation.crypto.rsa import materialise_exponent, materialise_numeric and context from other files: # Path: groundstation/crypto/rsa.py # class RSAAdaptor(object): # def __init__(self, keyset): # """Initialize an RSAAdaptor # # keyset = a dict of identifiers to public keys to test signatures # against # """ # self.keyset = self._render_keyset(keyset) # # def verify(self, data, signature): # assert len(data) == 40, "We only sign sha1 hashes" # for keyname in self.keyset: # key = self.keyset[keyname] # if key.verify(str(data), signature): # return keyname # return False # # def _render_keyset(self, keyset): # return {i: convert_pubkey(keyset[i]) for i in keyset} # # class RSAPrivateAdaptor(object): # def __init__(self, key): # self.key = convert_privkey(key) # # def sign(self, data): # assert len(data) == 40, "We only sign sha1 hashes" # return self.key.sign(data, None) # # Path: groundstation/crypto/rsa.py # def convert_privkey(key): # pkey = RSA.importKey(key) # assert pkey.has_private() # return pkey # # def convert_pubkey(key): # # get the second field from the public key file. # # import pdb; pdb.set_trace() # keydata = base64.b64decode(key.split(None)[1]) # # parts = [] # while keydata: # # read the length of the data # dlen = struct.unpack('>I', keydata[:4])[0] # # # read in <length> bytes # data, keydata = keydata[4:dlen+4], keydata[4+dlen:] # # parts.append(data) # exponent = materialise(parts[1]) # numeric = materialise(parts[2]) # # return RSA.construct((long(numeric), long(exponent))) # # Path: groundstation/crypto/rsa.py # def materialise(n): # def convert_pubkey(key): # def convert_privkey(key): # def __init__(self, keyset): # def verify(self, data, signature): # def _render_keyset(self, keyset): # def __init__(self, key): # def sign(self, data): # class RSAAdaptor(object): # class RSAPrivateAdaptor(object): , which may include functions, classes, or code. Output only the next line.
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 = RSAPrivateAdaptor(crypto_fixture.valid_key) signature = adaptor.sign(crypto_fixture.sample_data) self.assertEqual(signature, crypto_fixture.signatures["sample_data"]["valid_key"]) def test_verifies_data(self): adaptor = RSAAdaptor({"key1": crypto_fixture.valid_pubkey}) self.assertEqual("key1", adaptor.verify( crypto_fixture.sample_data, crypto_fixture.signatures["sample_data"]["valid_key"] )) def test_returns_false_for_unverified_data(self): adaptor = RSAAdaptor({"key1": crypto_fixture.passphrase_pubkey}) self.assertFalse(adaptor.verify( crypto_fixture.sample_data, crypto_fixture.signatures["sample_data"]["valid_key"] )) def test_materialise_helpers(self): self.assertEqual(crypto_fixture.materialize_out, materialise_exponent(crypto_fixture.materialize_in)) self.assertEqual(crypto_fixture.materialize_out, <|code_end|> with the help of current file imports: import unittest from Crypto.PublicKey import RSA from support import crypto_fixture from groundstation.crypto.rsa import RSAAdaptor, RSAPrivateAdaptor from groundstation.crypto.rsa import convert_privkey, convert_pubkey from groundstation.crypto.rsa import materialise_exponent, materialise_numeric and context from other files: # Path: groundstation/crypto/rsa.py # class RSAAdaptor(object): # def __init__(self, keyset): # """Initialize an RSAAdaptor # # keyset = a dict of identifiers to public keys to test signatures # against # """ # self.keyset = self._render_keyset(keyset) # # def verify(self, data, signature): # assert len(data) == 40, "We only sign sha1 hashes" # for keyname in self.keyset: # key = self.keyset[keyname] # if key.verify(str(data), signature): # return keyname # return False # # def _render_keyset(self, keyset): # return {i: convert_pubkey(keyset[i]) for i in keyset} # # class RSAPrivateAdaptor(object): # def __init__(self, key): # self.key = convert_privkey(key) # # def sign(self, data): # assert len(data) == 40, "We only sign sha1 hashes" # return self.key.sign(data, None) # # Path: groundstation/crypto/rsa.py # def convert_privkey(key): # pkey = RSA.importKey(key) # assert pkey.has_private() # return pkey # # def convert_pubkey(key): # # get the second field from the public key file. # # import pdb; pdb.set_trace() # keydata = base64.b64decode(key.split(None)[1]) # # parts = [] # while keydata: # # read the length of the data # dlen = struct.unpack('>I', keydata[:4])[0] # # # read in <length> bytes # data, keydata = keydata[4:dlen+4], keydata[4+dlen:] # # parts.append(data) # exponent = materialise(parts[1]) # numeric = materialise(parts[2]) # # return RSA.construct((long(numeric), long(exponent))) # # Path: groundstation/crypto/rsa.py # def materialise(n): # def convert_pubkey(key): # def convert_privkey(key): # def __init__(self, keyset): # def verify(self, data, signature): # def _render_keyset(self, keyset): # def __init__(self, key): # def sign(self, data): # class RSAAdaptor(object): # class RSAPrivateAdaptor(object): , which may contain function names, class names, or code. Output only the next line.
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_encoded(self): # Create an encoder with the default codes <|code_end|> . Use current file imports: (import unittest import random from groundstation.ue_encoder import UnambiguousEncoder) and context including class names, function names, or small code snippets from other files: # Path: groundstation/ue_encoder.py # class UnambiguousEncoder(object): # def __init__(self, codes=DEFAULT_LOOKUP): # self.codes = codes # # def encode(self, cat, buf): # """ Encodes from LSB""" # # if cat not in self.codes: # raise UnknownCodeCategory("Unknown code category: %s" % cat) # code = self.codes[cat] # # out = [] # bit = 1 # for i in buf: # # Map the bits onto the binary code # for bit in range(8): # f = i & (1 << bit) # idx = 1 if f else 0 # val = code.code[idx] # out.append(val) # # return out # # def decode(self, cat, buf): # if cat not in self.codes: # raise UnknownCodeCategory("Unknown code category: %s" % cat) # code = self.codes[cat] # # out = [] # values = chunks(8, buf) # # # Slice off 8 byte chunks because we're encoding from LSB # for chunk in values: # bit = 0 # this = 0 # for byt in chunk: # if code.lookup(byt): # this |= (1 << bit) # bit += 1 # out.append(this) # # return out . Output only the next line.
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.tmpdir = tempfile.mkdtemp() self.node = groundstation.node.Node() <|code_end|> , predict the immediate next line with the help of imports: import unittest import tempfile import shutil import uuid import groundstation.node import groundstation.transfer.response import groundstation.transfer.request from groundstation.station import Station and context (classes, functions, sometimes code) from other files: # Path: groundstation/station.py # class Station(object): # def __init__(self, path, identity): # self.identity = identity # self.store = store.STORAGE_BACKENDS[settings.STORAGE_BACKEND](path) # self.gizmo_factory = GizmoFactory(self, identity) # self.identity_cache = {} # self.registry = RequestRegistry() # self.iterators = [] # self.deferreds = [] # # @staticmethod # def from_env(identity): # if "GROUNDSTATION_HOME" in os.environ: # return Station(os.getenv("GROUNDSTATION_HOME"), identity) # else: # station_path = os.path.expanduser("~/.groundstation") # return Station(station_path, identity) # # def get_crypto_adaptor(self): # return RSAAdaptor(self.store.get_public_keys()) # # def get_private_crypto_adaptor(self, keyname): # return RSAPrivateAdaptor(self.store.get_private_key(keyname)) # # def get_request(self, request_id): # return self.registry[request_id] # # def register_request(self, request): # log.debug("Registering request %s" % (str(request.id))) # self.registry.register(request) # # def free_request(self, request): # log.debug("Freeing request %s" % (str(request.id))) # return self.registry.free(request) # # def register_iter(self, iterator): # log.info("Registering iterator %s" % (repr(iterator))) # self.iterators.append(iterator()) # # def register_deferred(self, deferred): # log.info("Registering deferred %s" % (repr(deferred))) # self.deferreds.append(deferred) # # def has_ready_iterators(self): # return len(self.iterators) > 0 # # def has_ready_deferreds(self): # now = time.time() # for i in self.deferreds: # if i.at < now: # return True # return False # # def handle_iters(self): # for i in self.iterators: # try: # i.next() # except StopIteration: # self.iterators.remove(i) # # def handle_deferreds(self): # now = time.time() # new_deferreds = [] # while self.deferreds: # i = self.deferreds.pop(0) # if i.at < now: # i.run() # else: # new_deferreds.append(i) # [self.deferreds.append(i) for i in new_deferreds] # # def channels(self): # return os.listdir(self.store.gref_path()) # # channels = {} # # for channel in os.listdir(self.store.gref_path()): # # channels["channel"] = Channel(self.store, channel) # # def create_channel(self, channel_name): # try: # os.mkdir(os.path.join(self.store.gref_path(), channel_name)) # return True # except OSError: # return False # # def grefs(self, channel): # channel_path = os.path.join(self.store.gref_path(), channel) # if not groundstation.utils.is_dir(channel_path): # raise NonExistantChannel() # grefs = [] # for id in groundstation.utils.find_leaf_dirs(channel_path, True): # grefs.append(Gref(self.store, channel, id)) # return grefs # # # Delegate some methods to the store # def write(self, obj): # log.info("Writing object to db") # oid = self.store.create_blob(obj) # log.info("Wrote object %s" % oid) # return oid # # def objects(self): # return self.store.objects() # # def __getitem__(self, key): # return self.store.__getitem__(key) # # def __contains__(self, item): # return self.store.__contains__(item) # # End delegates to store # # def update_gref(self, gref, tips, parents=[]): # log.debug("updating %s - %s => %s" % (gref.channel, gref.identifier, tips)) # node_path = gref.node_path() # tip_oids = [] # for tip in tips: # gref.write_tip(tip.tip, tip.signature) # tip_oids.append(tip.tip) # if parents is True: # parents = gref.parents(tip_oids) # for parent in parents: # gref.remove_tip(parent, True) # # def recently_queried(self, identity): # """CAS the cache status of a given identity. # # Returns False if you should query them.""" # val = str(identity) # if val not in self.identity_cache: # self.mark_queried(identity) # return False # else: # if self.identity_cache[val] + settings.DEFAULT_CACHE_LIFETIME > time.time(): # return True # else: # self.mark_queried(identity) # return False # # def mark_queried(self, identity): # val = str(identity) # self.identity_cache[val] = time.time() # # def get_hash(self, prefix): # # TODO This depends heavily on the order that objects() returns # sha = hashlib.sha1() # for oid in sorted(self.objects()): # name = groundstation.utils.oid2hex(oid) # if name.startswith(prefix): # sha.update(name) # return sha.digest() . Output only the next line.
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|> , generate the next line using the imports in this file: import groundstation.proto.channel_list_pb2 from groundstation.gref import Gref from groundstation import logger and context (functions, classes, or occasionally code) from other files: # Path: groundstation/gref.py # class Gref(object): # def __init__(self, store, channel, identifier): # self.store = store # self.channel = channel.replace("/", "_") # assert valid_path(self.channel), "Invalid channel" # self.identifier = identifier # assert valid_path(self.identifier), "Invalid identifier" # self._node_path = os.path.join(self.store.gref_path(), # self.channel, # self.identifier) # # def __str__(self): # return "%s/%s" % (self.channel, self.identifier) # # def exists(self): # return os.path.exists(self._node_path) # # def tips(self): # return os.listdir(self._node_path) # # def node_path(self): # if not self.exists(): # os.makedirs(self._node_path) # # return self._node_path # # def write_tip(self, tip, signature): # if signature: # signature = str(signature[0]) # tip_path = self.tip_path(tip) # open(tip_path, 'a').close() # fh = open(tip_path, 'r+') # fh.seek(0) # fh.write(signature) # 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_path(tip), 'r') as fh: # data = fh.read() # if not data: # return "" # return (int(data),) # except IOError: # return "" # # def remove_tip(self, tip, silent=False): # try: # os.unlink(os.path.join(self.tip_path(tip))) # except: # if not silent: # raise # # def direct_parents(self, tip): # """Return all parents of `tip` in the order they're written into the # object""" # obj = object_factory.hydrate_object(self.store[tip].data) # if isinstance(obj, RootObject): # # Roots can't have parents # return [] # elif isinstance(obj, UpdateObject): # return obj.parents # else: # raise "Unknown object hydrated %s" % (str(type(obj))) # # def parents(self, tips=None): # """Return all ancestors of `tip`, in an undefined order""" # # XXX This will asplode the stack at some point # parents = set() # this_iter = (tips or self.tips()) # while this_iter: # tip = this_iter.pop() # tips_parents = self.direct_parents(tip) # parents = parents.union(set(tips_parents)) # this_iter.extend(tips_parents) # return parents # # def marshall(self, crypto_adaptor=None): # """Marshalls the gref into something renderable: # { # "thread": An ordered thread of UpdateObjects. Ordering is # arbitraryish. # "roots": The root nodes of this gref. # "tips": The string names of the tips used to marshall # } # """ # thread = [] # root_nodes = [] # visited_nodes = set() # tips = [] # signatures = {} # # # TODO Big issues will smash the stack # def _process(node): # if node in visited_nodes: # log.debug("Bailing on visited node: %s" % (node)) # return # visited_nodes.add(node) # # if crypto_adaptor: # signature = self.get_signature(node) # if signature: # signatures[node] = crypto_adaptor.verify(node, signature) # # obj = object_factory.hydrate_object(self.store[node].data) # if isinstance(obj, RootObject): # We've found a root # root_nodes.append(obj) # return # for tip in obj.parents: # _process(tip) # thread.insert(0, obj) # # for tip in self: # tips.append(tip) # log.debug("Descending into %s" % (tip)) # _process(tip) # return { # "thread": thread, # "roots": root_nodes, # "tips": tips, # "signatures": signatures # } # # def as_dict(self): # return { # "channel": self.channel, # "identifier": self.identifier, # "node_path": self._node_path, # "tips": self.tips() # } # # Path: groundstation/logger.py # LEVEL = getattr(logging, os.getenv("GROUNDSTATION_DEBUG")) # LEVEL = logging.DEBUG # CONSOLE_FORMATTER = _get_formatter() # CONSOLE_HANDLER = _get_console_handler() # LOGGERS = {} # Cache for instanciated loggers # def fix_oid(oid): # def _get_formatter(): # def _get_console_handler(): # def getLogger(name): # Not threadsafe . Output only the next line.
_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: data = fh.read() if not data: return "" return (int(data),) except IOError: return "" def remove_tip(self, tip, silent=False): try: os.unlink(os.path.join(self.tip_path(tip))) except: if not silent: raise def direct_parents(self, tip): """Return all parents of `tip` in the order they're written into the object""" obj = object_factory.hydrate_object(self.store[tip].data) if isinstance(obj, RootObject): # Roots can't have parents return [] <|code_end|> with the help of current file imports: import os import groundstation.objects.object_factory as object_factory import logger from collections import namedtuple from groundstation.objects.update_object import UpdateObject from groundstation.objects.root_object import RootObject and context from other files: # Path: groundstation/objects/update_object.py # class UpdateObject(base_object.BaseObject): # data_members = ["parents", "data"] # # def __init__(self, parents, data): # self.parents = parents # self.data = data # self._sha1 = None # # @staticmethod # def from_object(obj): # """Convert an object straight from Git into a RootObject""" # protobuf = update_object_pb2.UpdateObject() # protobuf.ParseFromString(obj) # return UpdateObject(protobuf.parents, protobuf.data) # # def as_object(self): # """Convert a RootObject into data suitable to write into the database # as a Git object""" # protobuf = update_object_pb2.UpdateObject() # protobuf.parents.extend(self.parents) # protobuf.data = self.data # return protobuf.SerializeToString() # # Path: groundstation/objects/root_object.py # class RootObject(base_object.BaseObject): # data_members = ["id", "channel", "protocol"] # # def __init__(self, id, channel, protocol): # self.id = id # self.channel = channel # self.protocol = protocol # self._sha1 = None # # @staticmethod # def from_object(obj): # """Convert an object straight from Git into a RootObject""" # protobuf = root_object_pb2.RootObject() # protobuf.ParseFromString(obj) # return RootObject(protobuf.id, protobuf.channel, protobuf.protocol) # # def as_object(self): # """Convert a RootObject into data suitable to write into the database # as a Git object""" # protobuf = root_object_pb2.RootObject() # for member in self.data_members: # setattr(protobuf, member, getattr(self, member)) # return protobuf.SerializeToString() # # def as_json(self): # return { # "id": self.id, # "channel": self.channel, # "protocol": self.protocol # } , which may contain function names, class names, or code. Output only the next line.
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_path(tip), 'r') as fh: data = fh.read() if not data: return "" return (int(data),) except IOError: return "" def remove_tip(self, tip, silent=False): try: os.unlink(os.path.join(self.tip_path(tip))) except: if not silent: raise def direct_parents(self, tip): """Return all parents of `tip` in the order they're written into the object""" obj = object_factory.hydrate_object(self.store[tip].data) <|code_end|> . Use current file imports: (import os import groundstation.objects.object_factory as object_factory import logger from collections import namedtuple from groundstation.objects.update_object import UpdateObject from groundstation.objects.root_object import RootObject) and context including class names, function names, or small code snippets from other files: # Path: groundstation/objects/update_object.py # class UpdateObject(base_object.BaseObject): # data_members = ["parents", "data"] # # def __init__(self, parents, data): # self.parents = parents # self.data = data # self._sha1 = None # # @staticmethod # def from_object(obj): # """Convert an object straight from Git into a RootObject""" # protobuf = update_object_pb2.UpdateObject() # protobuf.ParseFromString(obj) # return UpdateObject(protobuf.parents, protobuf.data) # # def as_object(self): # """Convert a RootObject into data suitable to write into the database # as a Git object""" # protobuf = update_object_pb2.UpdateObject() # protobuf.parents.extend(self.parents) # protobuf.data = self.data # return protobuf.SerializeToString() # # Path: groundstation/objects/root_object.py # class RootObject(base_object.BaseObject): # data_members = ["id", "channel", "protocol"] # # def __init__(self, id, channel, protocol): # self.id = id # self.channel = channel # self.protocol = protocol # self._sha1 = None # # @staticmethod # def from_object(obj): # """Convert an object straight from Git into a RootObject""" # protobuf = root_object_pb2.RootObject() # protobuf.ParseFromString(obj) # return RootObject(protobuf.id, protobuf.channel, protobuf.protocol) # # def as_object(self): # """Convert a RootObject into data suitable to write into the database # as a Git object""" # protobuf = root_object_pb2.RootObject() # for member in self.data_members: # setattr(protobuf, member, getattr(self, member)) # return protobuf.SerializeToString() # # def as_json(self): # return { # "id": self.id, # "channel": self.channel, # "protocol": self.protocol # } . Output only the next line.
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.ChannelList() proto_channels.ParseFromString(self.payload) for channel in proto_channels.channels: for gref in channel.grefs: <|code_end|> . Use current file imports: (import groundstation.proto.channel_list_pb2 from groundstation import logger from groundstation.gref import Gref, Tip) and context including class names, function names, or small code snippets from other files: # Path: groundstation/logger.py # LEVEL = getattr(logging, os.getenv("GROUNDSTATION_DEBUG")) # LEVEL = logging.DEBUG # CONSOLE_FORMATTER = _get_formatter() # CONSOLE_HANDLER = _get_console_handler() # LOGGERS = {} # Cache for instanciated loggers # def fix_oid(oid): # def _get_formatter(): # def _get_console_handler(): # def getLogger(name): # Not threadsafe # # Path: groundstation/gref.py # def valid_path(path): # def __init__(self, store, channel, identifier): # def __str__(self): # def exists(self): # def tips(self): # def node_path(self): # def write_tip(self, tip, signature): # def tip_path(self, tip): # def __iter__(self): # def get_signature(self, tip): # def remove_tip(self, tip, silent=False): # def direct_parents(self, tip): # def parents(self, tips=None): # def marshall(self, crypto_adaptor=None): # def _process(node): # def as_dict(self): # class Gref(object): . Output only the next line.
_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 = groundstation.proto.channel_list_pb2.ChannelList() proto_channels.ParseFromString(self.payload) for channel in proto_channels.channels: for gref in channel.grefs: _gref = Gref(self.station.store, channel.channelname, gref.identifier) # Create a tip object to avoid upsetting fileutils <|code_end|> , predict the next line using imports from the current file: import groundstation.proto.channel_list_pb2 from groundstation import logger from groundstation.gref import Gref, Tip and context including class names, function names, and sometimes code from other files: # Path: groundstation/logger.py # LEVEL = getattr(logging, os.getenv("GROUNDSTATION_DEBUG")) # LEVEL = logging.DEBUG # CONSOLE_FORMATTER = _get_formatter() # CONSOLE_HANDLER = _get_console_handler() # LOGGERS = {} # Cache for instanciated loggers # def fix_oid(oid): # def _get_formatter(): # def _get_console_handler(): # def getLogger(name): # Not threadsafe # # Path: groundstation/gref.py # def valid_path(path): # def __init__(self, store, channel, identifier): # def __str__(self): # def exists(self): # def tips(self): # def node_path(self): # def write_tip(self, tip, signature): # def tip_path(self, tip): # def __iter__(self): # def get_signature(self, tip): # def remove_tip(self, tip, silent=False): # def direct_parents(self, tip): # def parents(self, tips=None): # def marshall(self, crypto_adaptor=None): # def _process(node): # def as_dict(self): # class Gref(object): . Output only the next line.
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 from groundstation import logger) and context including class names, function names, or small code snippets from other files: # Path: groundstation/proto/git_object_pb2.py # class GitObject(_message.Message): # __metaclass__ = _reflection.GeneratedProtocolMessageType # DESCRIPTOR = _GITOBJECT # # # @@protoc_insertion_point(class_scope:GitObject) # # Path: groundstation/logger.py # LEVEL = getattr(logging, os.getenv("GROUNDSTATION_DEBUG")) # LEVEL = logging.DEBUG # CONSOLE_FORMATTER = _get_formatter() # CONSOLE_HANDLER = _get_console_handler() # LOGGERS = {} # Cache for instanciated loggers # def fix_oid(oid): # def _get_formatter(): # def _get_console_handler(): # def getLogger(name): # Not threadsafe . Output only the next line.
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 = payload_buffer[:segment_length] payload_buffer = payload_buffer[segment_length:] log.debug("RECV %i bytes from %s" % # XXX Ignore, subclasses set .peer (len(data), self.peer)) self.packet_queue.insert(0, data) tmp_buffer = payload_buffer # Bail if we emptied the buffer else: # We haven't touched tmp_buffer, it is therefore safe to save # back to the classbuffer if iterations == 0: log.warn("Didn't construct a single full payload!") break self.buffer = tmp_buffer @staticmethod def serialize(payload): if isinstance(payload, Response): return payload.SerializeToString() else: return payload def recv_to_buffer(self): try: <|code_end|> using the current file's imports: import socket import errno import groundstation.logger from groundstation import settings from groundstation.transfer.response import Response from socket_closed_exception import SocketClosedException and any relevant context from other files: # Path: groundstation/settings.py # PORT=1248 # Port to listen on (udp+tcp) # BEACON_TIMEOUT=5 # 5 second timeout between beacons # DEFAULT_BUFSIZE=8192 # 8k bytes # DEFAULT_CACHE_LIFETIME=30 # 30 Seconds # STORAGE_BACKEND="git" # LISTALLOBJECTS_CHUNK_THRESHOLD=1024 # LISTALLCHANNELS_RETRY_TIMEOUT=5 # CLOSEWAIT_TIMEOUT=240 # 2MSL # # Path: groundstation/transfer/response.py # class Response(object): # def __init__(self, response_to, verb, payload, station=None, stream=None, origin=None): # self.type = "RESPONSE" # self.id = response_to # self.station = station # self.stream = stream # self.verb = verb # self.payload = payload # # if origin: # # self.origin = uuid.UUID(origin) # self.origin = origin # # def _Request(self, *args, **kwargs): # kwargs['station'] = self.station # req = groundstation.transfer.request.Request(*args, **kwargs) # self.station.register_request(req) # return req # # @classmethod # def from_gizmo(klass, gizmo, station, stream): # log.debug("Hydrating a response from gizmo") # return Response(gizmo.id, gizmo.verb, gizmo.payload, station, stream, gizmo.stationid) # # def SerializeToString(self): # gizmo = self.station.gizmo_factory.gizmo() # gizmo.id = str(self.id) # gizmo.type = Gizmo.RESPONSE # gizmo.verb = self.verb # if self.payload: # gizmo.payload = self.payload # return gizmo.SerializeToString() # # def process(self): # if self.verb not in self.VALID_RESPONSES: # raise Exception("Invalid Response verb: %s" % (self.verb)) # # self.VALID_RESPONSES[self.verb](self) # # VALID_RESPONSES = { # "TRANSFER": response_handlers.handle_transfer, # "DESCRIBEOBJECTS": response_handlers.handle_describeobjects, # "DESCRIBECHANNELS": response_handlers.handle_describechannels, # "TERMINATE": response_handlers.handle_terminate, # } # # @property # def payload(self): # return self._payload # @payload.setter # def payload(self, value): # self._payload = str(value) . Output only the next line.
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_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 = payload_buffer[:segment_length] payload_buffer = payload_buffer[segment_length:] log.debug("RECV %i bytes from %s" % # XXX Ignore, subclasses set .peer (len(data), self.peer)) self.packet_queue.insert(0, data) tmp_buffer = payload_buffer # Bail if we emptied the buffer else: # We haven't touched tmp_buffer, it is therefore safe to save # back to the classbuffer if iterations == 0: log.warn("Didn't construct a single full payload!") break self.buffer = tmp_buffer @staticmethod def serialize(payload): <|code_end|> , predict the next line using imports from the current file: import socket import errno import groundstation.logger from groundstation import settings from groundstation.transfer.response import Response from socket_closed_exception import SocketClosedException and context including class names, function names, and sometimes code from other files: # Path: groundstation/settings.py # PORT=1248 # Port to listen on (udp+tcp) # BEACON_TIMEOUT=5 # 5 second timeout between beacons # DEFAULT_BUFSIZE=8192 # 8k bytes # DEFAULT_CACHE_LIFETIME=30 # 30 Seconds # STORAGE_BACKEND="git" # LISTALLOBJECTS_CHUNK_THRESHOLD=1024 # LISTALLCHANNELS_RETRY_TIMEOUT=5 # CLOSEWAIT_TIMEOUT=240 # 2MSL # # Path: groundstation/transfer/response.py # class Response(object): # def __init__(self, response_to, verb, payload, station=None, stream=None, origin=None): # self.type = "RESPONSE" # self.id = response_to # self.station = station # self.stream = stream # self.verb = verb # self.payload = payload # # if origin: # # self.origin = uuid.UUID(origin) # self.origin = origin # # def _Request(self, *args, **kwargs): # kwargs['station'] = self.station # req = groundstation.transfer.request.Request(*args, **kwargs) # self.station.register_request(req) # return req # # @classmethod # def from_gizmo(klass, gizmo, station, stream): # log.debug("Hydrating a response from gizmo") # return Response(gizmo.id, gizmo.verb, gizmo.payload, station, stream, gizmo.stationid) # # def SerializeToString(self): # gizmo = self.station.gizmo_factory.gizmo() # gizmo.id = str(self.id) # gizmo.type = Gizmo.RESPONSE # gizmo.verb = self.verb # if self.payload: # gizmo.payload = self.payload # return gizmo.SerializeToString() # # def process(self): # if self.verb not in self.VALID_RESPONSES: # raise Exception("Invalid Response verb: %s" % (self.verb)) # # self.VALID_RESPONSES[self.verb](self) # # VALID_RESPONSES = { # "TRANSFER": response_handlers.handle_transfer, # "DESCRIBEOBJECTS": response_handlers.handle_describeobjects, # "DESCRIBECHANNELS": response_handlers.handle_describechannels, # "TERMINATE": response_handlers.handle_terminate, # } # # @property # def payload(self): # return self._payload # @payload.setter # def payload(self, value): # self._payload = str(value) . Output only the next line.
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 line using imports from the current file: from ..resource import BaseResource from ..servers.ncbi import NCBI import sh and context including class names, function names, and sometimes code from other files: # Path: cosmid/resource.py # class BaseResource(object): # """ # A Resource represents a local genomics resource that can be on the file # system or destined to be downloaded. # """ # def __init__(self): # super(BaseResource, self).__init__() # # The server for the resource # self.server = None # # # The keyword for the resource # self.id = "resource" # # def versions(self): # """ # <public> Returns a list of version tags for availble resource versions. # # :returns: List of supported resource releases # :rtype: list # """ # return [] # # def latest(self): # """ # <public> Returns the version tag for the latest availble version of the # resource. # # :returns: The most up-to-date release tag # """ # return "" # # def newer(self, current, challenger): # """ # <public> Compares two different version tags and returns ``True`` if the # `challenger` is newer than the `current` tag. # # :param str current: Version tag to compare against # :param str challenger: Version tag to compare with # :returns: ANS: Challenger is newer than current # :rtype: bool # """ # return current > challenger # # def paths(self, version): # """ # <public> Returns the full download path matching the given ``version`` tag. # # :param str version: Version tag of the release # :returns: List of full paths for included files # :rtype: list # """ # return [] # # def postClone(self, cloned_files, target_dir, version): # """ # <public> This callback method will be called once the files in the resource # have been successfully downloaded. The paths to the files will be provided # as a list to the method. # # This can be used as a way to rename, unzip, or concat files; generally # post process them to prepare them for the user. # # :param list cloned_files: List of paths to the downloaded resource files # :param str target_dir: Path to resource directory # :param object version: Version of the resource that was downloaded # # .. versionadded:: 0.3.0 # """ # return 0 # # Path: cosmid/servers/ncbi.py # class NCBI(FTP): # """docstring for NCBI""" # def __init__(self): # super(NCBI, self).__init__("ftp.ncbi.nlm.nih.gov", "anonymous", "") . Output only the next line.
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 imports: from ..resource import BaseResource from ..servers.ncbi import NCBI import sh and context from other files: # Path: cosmid/resource.py # class BaseResource(object): # """ # A Resource represents a local genomics resource that can be on the file # system or destined to be downloaded. # """ # def __init__(self): # super(BaseResource, self).__init__() # # The server for the resource # self.server = None # # # The keyword for the resource # self.id = "resource" # # def versions(self): # """ # <public> Returns a list of version tags for availble resource versions. # # :returns: List of supported resource releases # :rtype: list # """ # return [] # # def latest(self): # """ # <public> Returns the version tag for the latest availble version of the # resource. # # :returns: The most up-to-date release tag # """ # return "" # # def newer(self, current, challenger): # """ # <public> Compares two different version tags and returns ``True`` if the # `challenger` is newer than the `current` tag. # # :param str current: Version tag to compare against # :param str challenger: Version tag to compare with # :returns: ANS: Challenger is newer than current # :rtype: bool # """ # return current > challenger # # def paths(self, version): # """ # <public> Returns the full download path matching the given ``version`` tag. # # :param str version: Version tag of the release # :returns: List of full paths for included files # :rtype: list # """ # return [] # # def postClone(self, cloned_files, target_dir, version): # """ # <public> This callback method will be called once the files in the resource # have been successfully downloaded. The paths to the files will be provided # as a list to the method. # # This can be used as a way to rename, unzip, or concat files; generally # post process them to prepare them for the user. # # :param list cloned_files: List of paths to the downloaded resource files # :param str target_dir: Path to resource directory # :param object version: Version of the resource that was downloaded # # .. versionadded:: 0.3.0 # """ # return 0 # # Path: cosmid/servers/ncbi.py # class NCBI(FTP): # """docstring for NCBI""" # def __init__(self): # super(NCBI, self).__init__("ftp.ncbi.nlm.nih.gov", "anonymous", "") , which may include functions, classes, or code. Output only the next line.
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 current file imports: from ..resource import BaseResource from ..servers.thousandg import ThousandG and context from other files: # Path: cosmid/resource.py # class BaseResource(object): # """ # A Resource represents a local genomics resource that can be on the file # system or destined to be downloaded. # """ # def __init__(self): # super(BaseResource, self).__init__() # # The server for the resource # self.server = None # # # The keyword for the resource # self.id = "resource" # # def versions(self): # """ # <public> Returns a list of version tags for availble resource versions. # # :returns: List of supported resource releases # :rtype: list # """ # return [] # # def latest(self): # """ # <public> Returns the version tag for the latest availble version of the # resource. # # :returns: The most up-to-date release tag # """ # return "" # # def newer(self, current, challenger): # """ # <public> Compares two different version tags and returns ``True`` if the # `challenger` is newer than the `current` tag. # # :param str current: Version tag to compare against # :param str challenger: Version tag to compare with # :returns: ANS: Challenger is newer than current # :rtype: bool # """ # return current > challenger # # def paths(self, version): # """ # <public> Returns the full download path matching the given ``version`` tag. # # :param str version: Version tag of the release # :returns: List of full paths for included files # :rtype: list # """ # return [] # # def postClone(self, cloned_files, target_dir, version): # """ # <public> This callback method will be called once the files in the resource # have been successfully downloaded. The paths to the files will be provided # as a list to the method. # # This can be used as a way to rename, unzip, or concat files; generally # post process them to prepare them for the user. # # :param list cloned_files: List of paths to the downloaded resource files # :param str target_dir: Path to resource directory # :param object version: Version of the resource that was downloaded # # .. versionadded:: 0.3.0 # """ # return 0 # # Path: cosmid/servers/thousandg.py # class ThousandG(FTP): # """docstring for EBI 1000 Genomes FTP""" # def __init__(self): # super(ThousandG, self).__init__("ftp-trace.ncbi.nih.gov", "anonymous", "") , which may contain function names, class names, or code. Output only the next line.
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 current file imports: (from ..resource import BaseResource from ..servers.ucsc import UCSC import sh) and context including class names, function names, or small code snippets from other files: # Path: cosmid/resource.py # class BaseResource(object): # """ # A Resource represents a local genomics resource that can be on the file # system or destined to be downloaded. # """ # def __init__(self): # super(BaseResource, self).__init__() # # The server for the resource # self.server = None # # # The keyword for the resource # self.id = "resource" # # def versions(self): # """ # <public> Returns a list of version tags for availble resource versions. # # :returns: List of supported resource releases # :rtype: list # """ # return [] # # def latest(self): # """ # <public> Returns the version tag for the latest availble version of the # resource. # # :returns: The most up-to-date release tag # """ # return "" # # def newer(self, current, challenger): # """ # <public> Compares two different version tags and returns ``True`` if the # `challenger` is newer than the `current` tag. # # :param str current: Version tag to compare against # :param str challenger: Version tag to compare with # :returns: ANS: Challenger is newer than current # :rtype: bool # """ # return current > challenger # # def paths(self, version): # """ # <public> Returns the full download path matching the given ``version`` tag. # # :param str version: Version tag of the release # :returns: List of full paths for included files # :rtype: list # """ # return [] # # def postClone(self, cloned_files, target_dir, version): # """ # <public> This callback method will be called once the files in the resource # have been successfully downloaded. The paths to the files will be provided # as a list to the method. # # This can be used as a way to rename, unzip, or concat files; generally # post process them to prepare them for the user. # # :param list cloned_files: List of paths to the downloaded resource files # :param str target_dir: Path to resource directory # :param object version: Version of the resource that was downloaded # # .. versionadded:: 0.3.0 # """ # return 0 # # Path: cosmid/servers/ucsc.py # class UCSC(FTP): # """docstring for UCSC""" # def __init__(self): # super(UCSC, self).__init__("hgdownload.cse.ucsc.edu", "anonymous", "email") . Output only the next line.
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 the help of current file imports: from ..resource import BaseResource from ..servers.gatk import GATK import sh and context from other files: # Path: cosmid/resource.py # class BaseResource(object): # """ # A Resource represents a local genomics resource that can be on the file # system or destined to be downloaded. # """ # def __init__(self): # super(BaseResource, self).__init__() # # The server for the resource # self.server = None # # # The keyword for the resource # self.id = "resource" # # def versions(self): # """ # <public> Returns a list of version tags for availble resource versions. # # :returns: List of supported resource releases # :rtype: list # """ # return [] # # def latest(self): # """ # <public> Returns the version tag for the latest availble version of the # resource. # # :returns: The most up-to-date release tag # """ # return "" # # def newer(self, current, challenger): # """ # <public> Compares two different version tags and returns ``True`` if the # `challenger` is newer than the `current` tag. # # :param str current: Version tag to compare against # :param str challenger: Version tag to compare with # :returns: ANS: Challenger is newer than current # :rtype: bool # """ # return current > challenger # # def paths(self, version): # """ # <public> Returns the full download path matching the given ``version`` tag. # # :param str version: Version tag of the release # :returns: List of full paths for included files # :rtype: list # """ # return [] # # def postClone(self, cloned_files, target_dir, version): # """ # <public> This callback method will be called once the files in the resource # have been successfully downloaded. The paths to the files will be provided # as a list to the method. # # This can be used as a way to rename, unzip, or concat files; generally # post process them to prepare them for the user. # # :param list cloned_files: List of paths to the downloaded resource files # :param str target_dir: Path to resource directory # :param object version: Version of the resource that was downloaded # # .. versionadded:: 0.3.0 # """ # return 0 # # Path: cosmid/servers/gatk.py # class GATK(FTP): # """docstring for NCBI""" # def __init__(self): # super(GATK, self).__init__("ftp.broadinstitute.org", # "gsapubftp-anonymous", "") , which may contain function names, class names, or code. Output only the next line.
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_assembly" <|code_end|> , predict the next line using imports from the current file: from ..resource import BaseResource from ..servers.ensembl import Ensembl import sh and context including class names, function names, and sometimes code from other files: # Path: cosmid/resource.py # class BaseResource(object): # """ # A Resource represents a local genomics resource that can be on the file # system or destined to be downloaded. # """ # def __init__(self): # super(BaseResource, self).__init__() # # The server for the resource # self.server = None # # # The keyword for the resource # self.id = "resource" # # def versions(self): # """ # <public> Returns a list of version tags for availble resource versions. # # :returns: List of supported resource releases # :rtype: list # """ # return [] # # def latest(self): # """ # <public> Returns the version tag for the latest availble version of the # resource. # # :returns: The most up-to-date release tag # """ # return "" # # def newer(self, current, challenger): # """ # <public> Compares two different version tags and returns ``True`` if the # `challenger` is newer than the `current` tag. # # :param str current: Version tag to compare against # :param str challenger: Version tag to compare with # :returns: ANS: Challenger is newer than current # :rtype: bool # """ # return current > challenger # # def paths(self, version): # """ # <public> Returns the full download path matching the given ``version`` tag. # # :param str version: Version tag of the release # :returns: List of full paths for included files # :rtype: list # """ # return [] # # def postClone(self, cloned_files, target_dir, version): # """ # <public> This callback method will be called once the files in the resource # have been successfully downloaded. The paths to the files will be provided # as a list to the method. # # This can be used as a way to rename, unzip, or concat files; generally # post process them to prepare them for the user. # # :param list cloned_files: List of paths to the downloaded resource files # :param str target_dir: Path to resource directory # :param object version: Version of the resource that was downloaded # # .. versionadded:: 0.3.0 # """ # return 0 # # Path: cosmid/servers/ensembl.py # class Ensembl(FTP): # """docstring for Ensembl""" # def __init__(self): # super(Ensembl, self).__init__("ftp.ensembl.org", "anonymous", "") . Output only the next line.
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_end|> , determine the next line of code. You have imports: from ..resource import BaseResource from ..servers.ncbi import NCBI and context (class names, function names, or code) available: # Path: cosmid/resource.py # class BaseResource(object): # """ # A Resource represents a local genomics resource that can be on the file # system or destined to be downloaded. # """ # def __init__(self): # super(BaseResource, self).__init__() # # The server for the resource # self.server = None # # # The keyword for the resource # self.id = "resource" # # def versions(self): # """ # <public> Returns a list of version tags for availble resource versions. # # :returns: List of supported resource releases # :rtype: list # """ # return [] # # def latest(self): # """ # <public> Returns the version tag for the latest availble version of the # resource. # # :returns: The most up-to-date release tag # """ # return "" # # def newer(self, current, challenger): # """ # <public> Compares two different version tags and returns ``True`` if the # `challenger` is newer than the `current` tag. # # :param str current: Version tag to compare against # :param str challenger: Version tag to compare with # :returns: ANS: Challenger is newer than current # :rtype: bool # """ # return current > challenger # # def paths(self, version): # """ # <public> Returns the full download path matching the given ``version`` tag. # # :param str version: Version tag of the release # :returns: List of full paths for included files # :rtype: list # """ # return [] # # def postClone(self, cloned_files, target_dir, version): # """ # <public> This callback method will be called once the files in the resource # have been successfully downloaded. The paths to the files will be provided # as a list to the method. # # This can be used as a way to rename, unzip, or concat files; generally # post process them to prepare them for the user. # # :param list cloned_files: List of paths to the downloaded resource files # :param str target_dir: Path to resource directory # :param object version: Version of the resource that was downloaded # # .. versionadded:: 0.3.0 # """ # return 0 # # Path: cosmid/servers/ncbi.py # class NCBI(FTP): # """docstring for NCBI""" # def __init__(self): # super(NCBI, self).__init__("ftp.ncbi.nlm.nih.gov", "anonymous", "") . Output only the next line.
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) def create_app(debug, database_url): app = Flask(__name__) app.secret_key = os.environ.get('SECRET_KEY', 'development_fallback') app.debug = debug (app.db_session, app.db_metadata, app.db_engine) = init_db(database_url) create_bundles(app) <|code_end|> , predict the immediate next line with the help of imports: import os from flask import Flask from webassets.loaders import PythonLoader from flask.ext.assets import Environment from views import create_views from database import init_db and context (classes, functions, sometimes code) from other files: # Path: views.py # def create_views(app): # # create_filters(app) # create_login_views(app) # # @app.before_request # def before_request(): # g.user = current_user # # @app.route('/') # def index(): # if current_user.is_authenticated(): # return redirect(url_for('trips')) # return render_template('index.html') # # @app.route('/editprofile', methods=['GET', 'POST']) # def editprofile(): # if request.method == 'GET': # return render_template( # 'editprofile.html', # user=current_user, # errors={}, # edit=True # ) # # if request.form['password'] and request.form['password'] != '': # current_user.set_password( # request.form['password'], # request.form['password2'] # ) # current_user.email = request.form['email'], # current_user.fullname = request.form['fullname'] # # if current_user.validate(): # current_app.db_session.add(current_user) # current_app.db_session.commit() # flash('Profilen ble oppdatert!') # # return render_template( # 'editprofile.html', # errors=current_user.validation_errors, # user=current_user, # edit=True # ) # # @app.route('/trips') # @login_required # def trips(): # trips = [trip.serialize_with_point() for trip in current_user.trips] # return render_template('trips.html', trips=json.dumps(trips)) # # ALLOWED_EXTENSIONS = set(['gpx']) # # def allowed_file(filename): # return '.' in filename and \ # filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS # # @app.route('/upload', methods=['GET', 'POST']) # @login_required # def upload(): # errors = {} # data = {} # if request.method == 'POST': # # file = request.files['file'] # title = request.form['title'] # type = request.form['type'] # description = request.form['description'] # # if not title or title == '': # errors['title'] = 'Oppgi en tittel' # if not file: # errors['file'] = u'Du må angi en fil.' # elif not allowed_file(file.filename): # errors['file'] = u'Ugyldig filtype! (må være en av %s)' % \ # ', '.join(ALLOWED_EXTENSIONS) # data['title'] = title # data['type'] = type # data['description'] = description # if not errors: # try: # points = parse_gpx(file) # trip = Trip( # user=current_user, # title=title, # description=description, # type=type, # start=points[0].time, # stop=points[-1].time, # ) # trip.points = points # current_app.db_session.add(trip) # current_app.db_session.commit() # flash(u'Turen ble lagret!') # return redirect(url_for('trip_detail', id=trip.id)) # except ValueError: # flash(u'Filen du lastet opp er ikke gyldig GPX!') # # return render_template( # 'upload.html', # trip_types=TRIP_TYPES, # errors=errors, # data=data # ) # # @app.route('/trips/<int:id>') # def trip_detail(id): # # trip = current_app.db_session.query(Trip).get(id) # if not trip: # abort(404) # return render_template( # 'trip_detail.html', # trip=trip, # trip_types=TRIP_TYPES, # geom=json.dumps(mapping(trip.geom)) # ) # # Path: database.py # def init_db(connection_string="sqlite://", echo=False): # engine = create_engine(connection_string, convert_unicode=True, echo=echo) # db_session = scoped_session(sessionmaker(autocommit=False, # autoflush=False, # bind=engine)) # # Base.query = db_session.query_property() # # return db_session, Base.metadata, engine . Output only the next line.
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 create_app(debug, database_url): app = Flask(__name__) app.secret_key = os.environ.get('SECRET_KEY', 'development_fallback') app.debug = debug <|code_end|> , determine the next line of code. You have imports: import os from flask import Flask from webassets.loaders import PythonLoader from flask.ext.assets import Environment from views import create_views from database import init_db and context (class names, function names, or code) available: # Path: views.py # def create_views(app): # # create_filters(app) # create_login_views(app) # # @app.before_request # def before_request(): # g.user = current_user # # @app.route('/') # def index(): # if current_user.is_authenticated(): # return redirect(url_for('trips')) # return render_template('index.html') # # @app.route('/editprofile', methods=['GET', 'POST']) # def editprofile(): # if request.method == 'GET': # return render_template( # 'editprofile.html', # user=current_user, # errors={}, # edit=True # ) # # if request.form['password'] and request.form['password'] != '': # current_user.set_password( # request.form['password'], # request.form['password2'] # ) # current_user.email = request.form['email'], # current_user.fullname = request.form['fullname'] # # if current_user.validate(): # current_app.db_session.add(current_user) # current_app.db_session.commit() # flash('Profilen ble oppdatert!') # # return render_template( # 'editprofile.html', # errors=current_user.validation_errors, # user=current_user, # edit=True # ) # # @app.route('/trips') # @login_required # def trips(): # trips = [trip.serialize_with_point() for trip in current_user.trips] # return render_template('trips.html', trips=json.dumps(trips)) # # ALLOWED_EXTENSIONS = set(['gpx']) # # def allowed_file(filename): # return '.' in filename and \ # filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS # # @app.route('/upload', methods=['GET', 'POST']) # @login_required # def upload(): # errors = {} # data = {} # if request.method == 'POST': # # file = request.files['file'] # title = request.form['title'] # type = request.form['type'] # description = request.form['description'] # # if not title or title == '': # errors['title'] = 'Oppgi en tittel' # if not file: # errors['file'] = u'Du må angi en fil.' # elif not allowed_file(file.filename): # errors['file'] = u'Ugyldig filtype! (må være en av %s)' % \ # ', '.join(ALLOWED_EXTENSIONS) # data['title'] = title # data['type'] = type # data['description'] = description # if not errors: # try: # points = parse_gpx(file) # trip = Trip( # user=current_user, # title=title, # description=description, # type=type, # start=points[0].time, # stop=points[-1].time, # ) # trip.points = points # current_app.db_session.add(trip) # current_app.db_session.commit() # flash(u'Turen ble lagret!') # return redirect(url_for('trip_detail', id=trip.id)) # except ValueError: # flash(u'Filen du lastet opp er ikke gyldig GPX!') # # return render_template( # 'upload.html', # trip_types=TRIP_TYPES, # errors=errors, # data=data # ) # # @app.route('/trips/<int:id>') # def trip_detail(id): # # trip = current_app.db_session.query(Trip).get(id) # if not trip: # abort(404) # return render_template( # 'trip_detail.html', # trip=trip, # trip_types=TRIP_TYPES, # geom=json.dumps(mapping(trip.geom)) # ) # # Path: database.py # def init_db(connection_string="sqlite://", echo=False): # engine = create_engine(connection_string, convert_unicode=True, echo=echo) # db_session = scoped_session(sessionmaker(autocommit=False, # autoflush=False, # bind=engine)) # # Base.query = db_session.query_property() # # return db_session, Base.metadata, engine . Output only the next line.
(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 redirect(url_for('editprofile')) if request.method == 'GET': <|code_end|> , generate the next line using the imports in this file: from flask import (redirect, url_for, request, render_template, current_app, flash) from flask.ext.login import (LoginManager, logout_user, login_user, current_user) from models import User, get_user_by_username and context (functions, classes, or occasionally code) from other files: # Path: models.py # class User(Base): # validation_errors = None # __tablename__ = 'users' # __table_args__ = {'schema': 'mineturer'} # id = Column('userid', Integer, primary_key=True) # username = Column('username', String(20), unique=True, index=True) # bcrypt_pwd = Column('bcrypt_pwd', String) # fullname = Column('fullname', String(50)) # enabled = Column('enabled', Boolean) # email = Column('email', String(50), unique=True, index=True) # trips = relationship( # 'Trip', # backref='mineturer.user', # order_by='desc(Trip.start)' # ) # # def __init__(self, username=None, password=None, password2=None, # email=None, fullname=None): # self.validation_errors = {} # self.username = username # self.fullname = fullname # self.set_password(password, password2) # self.email = email # # def set_password(self, password, password2): # if not self.validation_errors: # self.validation_errors = {} # # if not password and not self.id: # self.validation_errors['password'] = 'Fyll inn passord' # if not password2 and not self.id: # self.validation_errors['password2'] = 'Sett passord igjen' # if password != password2: # self.validation_errors['password2'] = 'Passordene er ulike' # if self.validation_errors: # return # # if password: # sha1_hashed = hashlib.sha1(password).hexdigest() # self.bcrypt_pwd = bcrypt.hashpw(sha1_hashed, bcrypt.gensalt()) # # def is_authenticated(self): # return True # # def is_active(self): # return self.enabled # # def is_anonymous(self): # return False # # def get_id(self): # return unicode(self.id) # # def password_ok(self, password): # # sha1_hashed = hashlib.sha1(password).hexdigest() # # bcrypt_hashed = bcrypt.hashpw( # sha1_hashed, # self.bcrypt_pwd.encode('utf-8') # ) # return bcrypt_hashed == self.bcrypt_pwd # # def validate(self): # # if not self.validation_errors: # self.validation_errors = {} # # if not self.id and not self.username: # self.validation_errors['username'] = 'Fyll inn brukernavn' # # if not self.id and not self.fullname: # self.validation_errors['fullname'] = 'Fyll inn navn' # # if not self.id and not self.email: # self.validation_errors['email'] = 'Fyll inn epost' # # if not self.id and get_user_by_username(self.username): # self.validation_errors['username'] = 'Brukernavnet er opptatt' # # if self.validation_errors: # return False # return True # # def __repr__(self): # return '<User %r>' % (self.username) # # def get_user_by_username(username): # return User.query.filter_by( # username=username, # ).first() . Output only the next line.
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å opprettet en bruker!') return redirect(request.args.get('next') or url_for('index')) else: return render_template( 'register.html', errors=user.validation_errors, user=user ) @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'GET': return render_template('login.html') username = request.form['username'] password = request.form['password'] remember_me = False if 'remember_me' in request.form: remember_me = True <|code_end|> with the help of current file imports: from flask import (redirect, url_for, request, render_template, current_app, flash) from flask.ext.login import (LoginManager, logout_user, login_user, current_user) from models import User, get_user_by_username and context from other files: # Path: models.py # class User(Base): # validation_errors = None # __tablename__ = 'users' # __table_args__ = {'schema': 'mineturer'} # id = Column('userid', Integer, primary_key=True) # username = Column('username', String(20), unique=True, index=True) # bcrypt_pwd = Column('bcrypt_pwd', String) # fullname = Column('fullname', String(50)) # enabled = Column('enabled', Boolean) # email = Column('email', String(50), unique=True, index=True) # trips = relationship( # 'Trip', # backref='mineturer.user', # order_by='desc(Trip.start)' # ) # # def __init__(self, username=None, password=None, password2=None, # email=None, fullname=None): # self.validation_errors = {} # self.username = username # self.fullname = fullname # self.set_password(password, password2) # self.email = email # # def set_password(self, password, password2): # if not self.validation_errors: # self.validation_errors = {} # # if not password and not self.id: # self.validation_errors['password'] = 'Fyll inn passord' # if not password2 and not self.id: # self.validation_errors['password2'] = 'Sett passord igjen' # if password != password2: # self.validation_errors['password2'] = 'Passordene er ulike' # if self.validation_errors: # return # # if password: # sha1_hashed = hashlib.sha1(password).hexdigest() # self.bcrypt_pwd = bcrypt.hashpw(sha1_hashed, bcrypt.gensalt()) # # def is_authenticated(self): # return True # # def is_active(self): # return self.enabled # # def is_anonymous(self): # return False # # def get_id(self): # return unicode(self.id) # # def password_ok(self, password): # # sha1_hashed = hashlib.sha1(password).hexdigest() # # bcrypt_hashed = bcrypt.hashpw( # sha1_hashed, # self.bcrypt_pwd.encode('utf-8') # ) # return bcrypt_hashed == self.bcrypt_pwd # # def validate(self): # # if not self.validation_errors: # self.validation_errors = {} # # if not self.id and not self.username: # self.validation_errors['username'] = 'Fyll inn brukernavn' # # if not self.id and not self.fullname: # self.validation_errors['fullname'] = 'Fyll inn navn' # # if not self.id and not self.email: # self.validation_errors['email'] = 'Fyll inn epost' # # if not self.id and get_user_by_username(self.username): # self.validation_errors['username'] = 'Brukernavnet er opptatt' # # if self.validation_errors: # return False # return True # # def __repr__(self): # return '<User %r>' % (self.username) # # def get_user_by_username(username): # return User.query.filter_by( # username=username, # ).first() , which may contain function names, class names, or code. Output only the next line.
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 @property def stored_points(self): if not self.stored_points_list: self.stored_points_list = self.points.all() return self.stored_points_list @property def geom(self): points = [to_shape(point.geom) for point in self.stored_points] return LineString(points) @property def stats(self): if not self.stats_dict: points = self.stored_points start_time = points[0].time end_time = points[-1].time <|code_end|> , determine the next line of code. You have imports: import hashlib import bcrypt from datetime import datetime from sqlalchemy import (Column, Integer, String, Text, Boolean, DateTime, Numeric, ForeignKey) from sqlalchemy.orm import relationship from geoalchemy2.types import Geometry from geoalchemy2.shape import to_shape, from_shape from shapely.geometry import LineString from database import Base from computations import get_stats, compute_speed and context (class names, function names, or code) available: # Path: database.py # def init_db(connection_string="sqlite://", echo=False): # # Path: computations.py # def get_stats(points): # total_distance_2d = 0.0 # total_distance_3d = 0.0 # flat_distance = 0.0 # asc_distance = 0.0 # desc_distance = 0.0 # # total_descent = 0.0 # total_ascent = 0.0 # # active_time = 0.0 # flat_time = 0.0 # asc_time = 0.0 # desc_time = 0.0 # # for current_point, next_point in izip(points, islice(points, 1, None)): # distance_2d = vincenty_distance( # to_shape(current_point.geom), # to_shape(next_point.geom) # ) # if next_point.ele and current_point.ele: # distance_vertical = next_point.ele - current_point.ele # else: # distance_vertical = 0.0 # distance_3d = math.sqrt( # math.pow(distance_2d, 2) + math.pow(distance_vertical, 2) # ) # # delta_time = next_point.time - current_point.time # time = delta_time.total_seconds() # if time > 0.0: # m = distance_3d / time # else: # m = 0.0 # # total_distance_2d += distance_2d # total_distance_3d += distance_3d # # if m > 0.1: # active_time += time # # if distance_vertical == 0.0: # flat_distance += distance_3d # if m > 0.1: # flat_time += time # elif distance_vertical > 0.0: # asc_distance += distance_3d # total_ascent += float(distance_vertical) # if m > 0.1: # asc_time += time # elif distance_vertical < 0.0: # desc_distance += distance_3d # total_descent += float(distance_vertical) # if m > 0.1: # desc_time += time # # heights = [point.ele for point in points if point.ele] # if heights: # max_height = max(heights) # min_height = min(heights) # else: # max_height = 0.0 # min_height = 0.0 # # return { # 'distance_2d': total_distance_2d, # 'distance_3d': total_distance_3d, # 'distance_flat': flat_distance, # 'distance_asc': asc_distance, # 'distance_desc': desc_distance, # 'total_descent': total_descent, # 'total_ascent': total_ascent, # 'max_height': max_height, # 'min_height': min_height, # 'active_time': timedelta(seconds=active_time), # 'flat_time': timedelta(seconds=flat_time), # 'asc_time': timedelta(seconds=asc_time), # 'desc_time': timedelta(seconds=desc_time), # } # # def compute_speed(distance, delta): # if delta.total_seconds() == 0.0: # return 0.0 # return distance / delta.total_seconds() . Output only the next line.
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: self.stored_points_list = self.points.all() return self.stored_points_list @property def geom(self): points = [to_shape(point.geom) for point in self.stored_points] return LineString(points) @property def stats(self): if not self.stats_dict: points = self.stored_points start_time = points[0].time end_time = points[-1].time stats = get_stats(points) total_time = end_time - start_time <|code_end|> , continue by predicting the next line. Consider current file imports: import hashlib import bcrypt from datetime import datetime from sqlalchemy import (Column, Integer, String, Text, Boolean, DateTime, Numeric, ForeignKey) from sqlalchemy.orm import relationship from geoalchemy2.types import Geometry from geoalchemy2.shape import to_shape, from_shape from shapely.geometry import LineString from database import Base from computations import get_stats, compute_speed and context: # Path: database.py # def init_db(connection_string="sqlite://", echo=False): # # Path: computations.py # def get_stats(points): # total_distance_2d = 0.0 # total_distance_3d = 0.0 # flat_distance = 0.0 # asc_distance = 0.0 # desc_distance = 0.0 # # total_descent = 0.0 # total_ascent = 0.0 # # active_time = 0.0 # flat_time = 0.0 # asc_time = 0.0 # desc_time = 0.0 # # for current_point, next_point in izip(points, islice(points, 1, None)): # distance_2d = vincenty_distance( # to_shape(current_point.geom), # to_shape(next_point.geom) # ) # if next_point.ele and current_point.ele: # distance_vertical = next_point.ele - current_point.ele # else: # distance_vertical = 0.0 # distance_3d = math.sqrt( # math.pow(distance_2d, 2) + math.pow(distance_vertical, 2) # ) # # delta_time = next_point.time - current_point.time # time = delta_time.total_seconds() # if time > 0.0: # m = distance_3d / time # else: # m = 0.0 # # total_distance_2d += distance_2d # total_distance_3d += distance_3d # # if m > 0.1: # active_time += time # # if distance_vertical == 0.0: # flat_distance += distance_3d # if m > 0.1: # flat_time += time # elif distance_vertical > 0.0: # asc_distance += distance_3d # total_ascent += float(distance_vertical) # if m > 0.1: # asc_time += time # elif distance_vertical < 0.0: # desc_distance += distance_3d # total_descent += float(distance_vertical) # if m > 0.1: # desc_time += time # # heights = [point.ele for point in points if point.ele] # if heights: # max_height = max(heights) # min_height = min(heights) # else: # max_height = 0.0 # min_height = 0.0 # # return { # 'distance_2d': total_distance_2d, # 'distance_3d': total_distance_3d, # 'distance_flat': flat_distance, # 'distance_asc': asc_distance, # 'distance_desc': desc_distance, # 'total_descent': total_descent, # 'total_ascent': total_ascent, # 'max_height': max_height, # 'min_height': min_height, # 'active_time': timedelta(seconds=active_time), # 'flat_time': timedelta(seconds=flat_time), # 'asc_time': timedelta(seconds=asc_time), # 'desc_time': timedelta(seconds=desc_time), # } # # def compute_speed(distance, delta): # if delta.total_seconds() == 0.0: # return 0.0 # return distance / delta.total_seconds() which might include code, classes, or functions. Output only the next line.
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.geometry import Point from models import Point as MTPoint from xml_code.gpx11 import parseString as parse11 from xml_code.gpx10 import parseString as parse10 import xml.etree.ElementTree as ET and context (classes, functions, or code) from other files: # Path: models.py # class Point(Base): # __tablename__ = 'points' # __table_args__ = {'schema': 'mineturer'} # pid = Column('pid', Integer, primary_key=True) # geom = Column(Geometry(geometry_type='POINT', srid=4326)) # time = Column('time', DateTime) # ele = Column('ele', Numeric) # hr = Column('hr', Numeric) # tripid = Column(Integer, ForeignKey('mineturer.trips.tripid')) # trip = relationship(Trip, primaryjoin=tripid == Trip.id) # # def __init__(self, trip=None, geom=None, time=None, ele=None, hr=None): # self.trip = trip # self.geom = from_shape(geom, srid=4326) # self.time = time # self.ele = ele # self.hr = hr # # def __repr__(self): # return '<Point %r>' % (self.pid) # # Path: xml_code/gpx11.py # def parseString(inString, silence=False): # from StringIO import StringIO # doc = parsexml_(StringIO(inString)) # rootNode = doc.getroot() # rootTag, rootClass = get_root_tag(rootNode) # if rootClass is None: # rootTag = 'gpxType' # rootClass = gpxType # rootObj = rootClass.factory() # rootObj.build(rootNode) # # Enable Python to collect the space used by the DOM. # doc = None # if not silence: # sys.stdout.write('<?xml version="1.0" ?>\n') # rootObj.export( # sys.stdout, 0, name_=rootTag, # namespacedef_='') # return rootObj # # Path: xml_code/gpx10.py # def parseString(inString, silence=False): # from StringIO import StringIO # doc = parsexml_(StringIO(inString)) # rootNode = doc.getroot() # rootTag, rootClass = get_root_tag(rootNode) # if rootClass is None: # rootTag = 'gpx' # rootClass = gpx # rootObj = rootClass.factory() # rootObj.build(rootNode) # # Enable Python to collect the space used by the DOM. # doc = None # if not silence: # sys.stdout.write('<?xml version="1.0" ?>\n') # rootObj.export( # sys.stdout, 0, name_=rootTag, # namespacedef_='xmlns:gpx="http://www.topografix.com/GPX/1/0"') # return rootObj . Output only the next line.
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( geom=Point(track_point.get_lon(), track_point.get_lat()), time=track_point.get_time(), ele=track_point.get_ele() )) return points def parse_gpx_10(data): <|code_end|> , determine the next line of code. You have imports: from shapely.geometry import Point from models import Point as MTPoint from xml_code.gpx11 import parseString as parse11 from xml_code.gpx10 import parseString as parse10 import xml.etree.ElementTree as ET and context (class names, function names, or code) available: # Path: models.py # class Point(Base): # __tablename__ = 'points' # __table_args__ = {'schema': 'mineturer'} # pid = Column('pid', Integer, primary_key=True) # geom = Column(Geometry(geometry_type='POINT', srid=4326)) # time = Column('time', DateTime) # ele = Column('ele', Numeric) # hr = Column('hr', Numeric) # tripid = Column(Integer, ForeignKey('mineturer.trips.tripid')) # trip = relationship(Trip, primaryjoin=tripid == Trip.id) # # def __init__(self, trip=None, geom=None, time=None, ele=None, hr=None): # self.trip = trip # self.geom = from_shape(geom, srid=4326) # self.time = time # self.ele = ele # self.hr = hr # # def __repr__(self): # return '<Point %r>' % (self.pid) # # Path: xml_code/gpx11.py # def parseString(inString, silence=False): # from StringIO import StringIO # doc = parsexml_(StringIO(inString)) # rootNode = doc.getroot() # rootTag, rootClass = get_root_tag(rootNode) # if rootClass is None: # rootTag = 'gpxType' # rootClass = gpxType # rootObj = rootClass.factory() # rootObj.build(rootNode) # # Enable Python to collect the space used by the DOM. # doc = None # if not silence: # sys.stdout.write('<?xml version="1.0" ?>\n') # rootObj.export( # sys.stdout, 0, name_=rootTag, # namespacedef_='') # return rootObj # # Path: xml_code/gpx10.py # def parseString(inString, silence=False): # from StringIO import StringIO # doc = parsexml_(StringIO(inString)) # rootNode = doc.getroot() # rootTag, rootClass = get_root_tag(rootNode) # if rootClass is None: # rootTag = 'gpx' # rootClass = gpx # rootObj = rootClass.factory() # rootObj.build(rootNode) # # Enable Python to collect the space used by the DOM. # doc = None # if not silence: # sys.stdout.write('<?xml version="1.0" ?>\n') # rootObj.export( # sys.stdout, 0, name_=rootTag, # namespacedef_='xmlns:gpx="http://www.topografix.com/GPX/1/0"') # return rootObj . Output only the next line.
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 context including class names, function names, or small code snippets from other files: # Path: models.py # class Trip(Base): # __tablename__ = 'trips' # __table_args__ = {'schema': 'mineturer'} # id = Column('tripid', Integer, primary_key=True) # title = Column('title', String) # description = Column('description', Text) # start = Column('start', DateTime) # stop = Column('stop', DateTime) # type = Column('triptype', String) # userid = Column(Integer, ForeignKey('mineturer.users.userid')) # user = relationship(User, primaryjoin=userid == User.id) # points = relationship( # 'Point', # backref='mineturer.trips', # order_by='asc(Point.time)', # lazy='dynamic' # ) # # stored_points_list = None # stats_dict = None # # def __init__(self, user=None, title=None, description=None, type=None, # start=None, stop=None): # self.user = user # self.title = title # self.description = description # self.type = type # if start: # self.start = start # else: # self.start = datetime.now() # if stop: # self.stop = stop # else: # self.stop = datetime.now() # # def serialize(self): # return { # 'id': self.id, # 'type': self.type, # '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 # # @property # def stored_points(self): # if not self.stored_points_list: # self.stored_points_list = self.points.all() # return self.stored_points_list # # @property # def geom(self): # points = [to_shape(point.geom) for point in self.stored_points] # return LineString(points) # # @property # def stats(self): # # if not self.stats_dict: # points = self.stored_points # # start_time = points[0].time # end_time = points[-1].time # # stats = get_stats(points) # # total_time = end_time - start_time # # avg_speed = compute_speed(stats['distance_3d'], total_time) # avg_moving_speed = compute_speed( # stats['distance_3d'], # stats['active_time'] # ) # # asc_speed = compute_speed(stats['distance_asc'], stats['asc_time']) # desc_speed = compute_speed( # stats['distance_desc'], # stats['desc_time'] # ) # flat_speed = compute_speed( # stats['distance_flat'], # stats['flat_time'] # ) # # self.stats_dict = { # 'start': start_time.isoformat(), # 'stop': end_time.isoformat(), # 'total_time': total_time, # 'active_time': stats['active_time'], # 'distance_2d': stats['distance_2d'], # 'distance_3d': stats['distance_3d'], # 'distance_flat': stats['distance_flat'], # 'distance_asc': stats['distance_asc'], # 'distance_desc': stats['distance_desc'], # 'asc_speed': asc_speed, # 'desc_speed': desc_speed, # 'flat_speed': flat_speed, # 'avg_speed': avg_speed, # 'avg_moving_speed': avg_moving_speed, # 'total_descent': stats['total_descent'], # 'total_ascent': stats['total_ascent'], # 'max_height': stats['max_height'], # 'min_height': stats['min_height'], # 'flat_time': stats['flat_time'], # 'asc_time': stats['asc_time'], # 'desc_time': stats['desc_time'], # 'elev_diff': stats['max_height'] - stats['min_height'], # } # return self.stats_dict # # def __repr__(self): # return '<Trip %r>' % (self.title) # # class Point(Base): # __tablename__ = 'points' # __table_args__ = {'schema': 'mineturer'} # pid = Column('pid', Integer, primary_key=True) # geom = Column(Geometry(geometry_type='POINT', srid=4326)) # time = Column('time', DateTime) # ele = Column('ele', Numeric) # hr = Column('hr', Numeric) # tripid = Column(Integer, ForeignKey('mineturer.trips.tripid')) # trip = relationship(Trip, primaryjoin=tripid == Trip.id) # # def __init__(self, trip=None, geom=None, time=None, ele=None, hr=None): # self.trip = trip # self.geom = from_shape(geom, srid=4326) # self.time = time # self.ele = ele # self.hr = hr # # def __repr__(self): # return '<Point %r>' % (self.pid) . Output only the next line.
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 set_name(self): return 'Youtube search component' def get_actions(self, *args: list): """ :type args: list """ if args[0] == 'click_search': self.search() elif args[0] == 'set_query': self.set_query(args[1]) else: raise NotImplemented <|code_end|> , predict the next line using imports from the current file: from abc import ABCMeta, abstractmethod from typing import Union from selenium.webdriver import Chrome, Firefox from src.factory.pages.menu import Menu from src.factory.pages.search import Search and context including class names, function names, and sometimes code from other files: # Path: src/factory/pages/menu.py # class Menu(object): # """ # A couple of menu actions are implemented in Menu class # """ # MENU_BUTTON = '#appbar-guide-button > span > span' # TREND_BUTTON = '//*[@id="trending-guide-item"]/a/span/span[2]/span' # HISTORY_BUTTON = '//*[@id="history-guide-item"]/a/span/span[2]' # BROWSE = '//*[@id="guide_builder-guide-item"]/a/span/span[2]/span' # # def __init__(self, driver: Union[Chrome, Firefox]): # """ # # :param driver: browser driver # :type driver: object # """ # self.__driver = driver # # def menu_button(self): # """ # Click on menu # """ # click_retry(self.__driver, self.MENU_BUTTON, 'css_selector') # # def filter_by_trend(self): # """ # Sort results by trend # """ # click_retry(self.__driver, self.TREND_BUTTON, 'xpath') # # def filter_by_history(self): # """ # Sort results by history # """ # click_retry(self.__driver, self.HISTORY_BUTTON, 'xpath') # # def browse(self): # """ # Browse channels # """ # click_retry(self.__driver, self.BROWSE, 'xpath') # # Path: src/factory/pages/search.py # class Search(object): # """ # Search page methods implementation # """ # SEARCH_CONTAINER = '//*[@id="masthead-search-term"]' # SEARCH_BUTTON = '//*[@id="search-btn"]' # # def __init__(self, driver: Union[Chrome, Firefox]): # """ # # :param driver: browser driver # :type driver: object # """ # self.__driver = driver # # def search(self): # """ # Click on search button # """ # self.__driver.find_element_by_xpath(Search.SEARCH_BUTTON).click() # # def set_query(self, query): # """ # Set query # :return: # :rtype: # """ # self.__driver.find_element_by_xpath(Search.SEARCH_CONTAINER).send_keys(query) . Output only the next line.
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 """ @abstractmethod def set_name(self): pass @abstractmethod def get_actions(self, *args): pass <|code_end|> , determine the next line of code. You have imports: from abc import ABCMeta, abstractmethod from typing import Union from selenium.webdriver import Chrome, Firefox from src.factory.pages.menu import Menu from src.factory.pages.search import Search and context (class names, function names, or code) available: # Path: src/factory/pages/menu.py # class Menu(object): # """ # A couple of menu actions are implemented in Menu class # """ # MENU_BUTTON = '#appbar-guide-button > span > span' # TREND_BUTTON = '//*[@id="trending-guide-item"]/a/span/span[2]/span' # HISTORY_BUTTON = '//*[@id="history-guide-item"]/a/span/span[2]' # BROWSE = '//*[@id="guide_builder-guide-item"]/a/span/span[2]/span' # # def __init__(self, driver: Union[Chrome, Firefox]): # """ # # :param driver: browser driver # :type driver: object # """ # self.__driver = driver # # def menu_button(self): # """ # Click on menu # """ # click_retry(self.__driver, self.MENU_BUTTON, 'css_selector') # # def filter_by_trend(self): # """ # Sort results by trend # """ # click_retry(self.__driver, self.TREND_BUTTON, 'xpath') # # def filter_by_history(self): # """ # Sort results by history # """ # click_retry(self.__driver, self.HISTORY_BUTTON, 'xpath') # # def browse(self): # """ # Browse channels # """ # click_retry(self.__driver, self.BROWSE, 'xpath') # # Path: src/factory/pages/search.py # class Search(object): # """ # Search page methods implementation # """ # SEARCH_CONTAINER = '//*[@id="masthead-search-term"]' # SEARCH_BUTTON = '//*[@id="search-btn"]' # # def __init__(self, driver: Union[Chrome, Firefox]): # """ # # :param driver: browser driver # :type driver: object # """ # self.__driver = driver # # def search(self): # """ # Click on search button # """ # self.__driver.find_element_by_xpath(Search.SEARCH_BUTTON).click() # # def set_query(self, query): # """ # Set query # :return: # :rtype: # """ # self.__driver.find_element_by_xpath(Search.SEARCH_CONTAINER).send_keys(query) . Output only the next line.
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 src.singleton.singleton_metaclass import Driver and context (functions, classes, or occasionally code) from other files: # Path: src/singleton/singleton_metaclass.py # class Driver(metaclass=MetaClassSingleton): # """ # Driver class decorated by the meta class: MetaClassSingleton. # Behaviour changed in singleton # """ # connection = None # # def connect(self): # """ # Set the connection with the web driver # :return: web driver # """ # if self.connection is None: # self.connection = webdriver.Chrome() # # return self.connection . Output only the next line.
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 = name def __str__(self): return 'B' + str(self.__name) class TestSingletonFactory(TestCase): def test_build(self): <|code_end|> , continue by predicting the next line. Consider current file imports: from unittest import TestCase from src.singleton.singleton_factory import SingletonFactory and context: # Path: src/singleton/singleton_factory.py # class SingletonFactory(object): # """ # A factory of the same instances of injected classes. # """ # # # a mapping between the name of a class and the instance. # __mappings = {} # # @staticmethod # def build(class_, **constructor_args): # """ # Builds an instance of the given class pointer together with the provided constructor arguments. # Returns the SAME instance for a given class. # # :param class_: A pointer to the definition of the class. # :param constructor_args: The arguments for the class instance. # :return: An instance of the provided class. # """ # # # if the class instance is mapped, then retrieve it. # if str(class_) in SingletonFactory.__mappings: # instance_ = SingletonFactory.__mappings[str(class_)] # # # else create the instance and map it to the class name. # else: # instance_ = class_(**constructor_args) # SingletonFactory.__mappings[str(class_)] = instance_ # # return instance_ which might include code, classes, or functions. Output only the next line.
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 BasePage and context from other files: # Path: src/page_object_pattern/base_page.py # class BasePage(object): # """ # Base class to initialize the base page that will be called from all pages # """ # # def __init__(self, driver): # self._driver = driver , which may include functions, classes, or code. Output only the next line.
class SearchPage(BasePage):