Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the following code snippet before the placeholder: <|code_start|> return self.conditions #def __contains__(self, state): # return all(state[var] == value for var, value in self.cond()) class UniqueOperator(object): next_index = 0 def __init__(self, action): self.action = action self.index = UniqueOperator.next_index UniqueOperator.next_index += 1 def __repr__(self): return str(self.action) + '#' + str(self.index) #def effects(action): # if isinstance(action, Operator): # return action.effects # if isinstance(action, State): # return action.values # TODO - should include default false values # if isinstance(action, Goal): # return {} # raise ValueError(action) def achieves(operator, item): (var, val) = item if isinstance(operator, Operator): return var in operator.effects and operator.effects[var] == val if isinstance(operator, UniqueOperator): return var in operator.action.effects and operator.action.effects[var] == val if isinstance(operator, State): return operator[var] == val <|code_end|> , predict the next line using imports from the current file: import random from .operators import Operator from .states import State, Goal, PartialState from heapq import heappop, heappush from collections import deque from .hsp import h_add, h_max and context including class names, function names, and sometimes code from other files: # Path: sas/operators.py # class Operator(PartialState): # def __init__(self, args): # for k, v in args.items(): # setattr(self, k, v) # self.args = args # TODO - use FrozenDict instead # self._frozen_args = frozenset(args.items()) # self._hash = None # self.conditions = None # self.effects = None # self.test = lambda state: True # def eff(self): # return self.effects.items() # def apply(self, state): # return State(merge_dicts(state.values, self.effects)) # def __call__(self, state): # if state not in self: # return None # return self.apply(state) # def __iter__(self): # yield self # def __len__(self): # return 1 # def __eq__(self, other): # return (type(self) == type(other)) and (self._frozen_args == other._frozen_args) # def __ne__(self, other): # return not self == other # def __hash__(self): # if self._hash is None: # self._hash = hash((self.__class__, self._frozen_args)) # return self._hash # def __str__(self): # return self.__class__.__name__ + str_object(self.args) # __repr__ = __str__ # # Path: sas/states.py # class State(object): # def __init__(self, values): # self.values = {var: value for var, value in values.items() if value is not False} # def __getitem__(self, var): # if var not in self.values: return False # return self.values[var] # def __eq__(self, other): # return (type(self) == type(other)) and (self.values == other.values) # def __ne__(self, other): # return not self == other # def __hash__(self): # return hash((self.__class__, frozenset(self.values.items()))) # def __str__(self): # return self.__class__.__name__ + str_object(self.values) # __repr__ = __str__ # # class Goal(PartialState): # TODO: unify PartialState and Goal # def __init__(self, values, test=lambda state: True): # self.conditions = values # self.test = test # def __eq__(self, other): # return (type(self) == type(other)) and (self.conditions == other.conditions) # def __ne__(self, other): # return not self == other # def __hash__(self): # return hash((self.__class__, frozenset(self.cond()))) # def __str__(self): # return self.__class__.__name__ + str_object(self.conditions) # __repr__ = __str__ # # class PartialState(object): # def cond(self): # return self.conditions.items() # def __contains__(self, state): # return all(state[var] == value for var, value in self.cond()) #and self.test(state) # # Path: sas/hsp.py # def h_add(state, goal, operators): # _, operator_costs = compute_costs(state, goal, operators, op=sum) # return operator_costs[goal].cost if goal in operator_costs else None # # def h_max(state, goal, operators): # _, operator_costs = compute_costs(state, goal, operators, op=max) # return operator_costs[goal].cost if goal in operator_costs else None . Output only the next line.
if isinstance(operator, Goal):
Here is a snippet: <|code_start|> def __str__(self): return ("actions: " + str(self.actions)+ "\nconstraints: " + str(self.constraints)+ "\nagenda: " + str(self.agenda)+ "\ncausal_links:" + str(self.causal_links)) def __repr__(self): return str((len(self.actions), len(self.constraints), len(self.agenda), len(self.causal_links))) def extract_plan(self): #print(self) other_acts = set(self.actions) sorted_acts = [] while other_acts: a = random.choice([a for a in other_acts if all((a1, a) not in self.constraints for a1 in other_acts)]) other_acts.remove(a) if isinstance(a, UniqueOperator): sorted_acts.append(a.action) return sorted_acts def flaws_heuristic(self, *args): #return self.goals_heuristic() + # number of threats pass def goals_heuristic(self, *args): return len(self.agenda) def add_heursitic(self, operators): # TODO - cache this #print(GoalConditions(self.agenda)) #return h_add(self.actions[0], GoalConditions([g for g, _ in self.agenda]), operators) <|code_end|> . Write the next line using the current file imports: import random from .operators import Operator from .states import State, Goal, PartialState from heapq import heappop, heappush from collections import deque from .hsp import h_add, h_max and context from other files: # Path: sas/operators.py # class Operator(PartialState): # def __init__(self, args): # for k, v in args.items(): # setattr(self, k, v) # self.args = args # TODO - use FrozenDict instead # self._frozen_args = frozenset(args.items()) # self._hash = None # self.conditions = None # self.effects = None # self.test = lambda state: True # def eff(self): # return self.effects.items() # def apply(self, state): # return State(merge_dicts(state.values, self.effects)) # def __call__(self, state): # if state not in self: # return None # return self.apply(state) # def __iter__(self): # yield self # def __len__(self): # return 1 # def __eq__(self, other): # return (type(self) == type(other)) and (self._frozen_args == other._frozen_args) # def __ne__(self, other): # return not self == other # def __hash__(self): # if self._hash is None: # self._hash = hash((self.__class__, self._frozen_args)) # return self._hash # def __str__(self): # return self.__class__.__name__ + str_object(self.args) # __repr__ = __str__ # # Path: sas/states.py # class State(object): # def __init__(self, values): # self.values = {var: value for var, value in values.items() if value is not False} # def __getitem__(self, var): # if var not in self.values: return False # return self.values[var] # def __eq__(self, other): # return (type(self) == type(other)) and (self.values == other.values) # def __ne__(self, other): # return not self == other # def __hash__(self): # return hash((self.__class__, frozenset(self.values.items()))) # def __str__(self): # return self.__class__.__name__ + str_object(self.values) # __repr__ = __str__ # # class Goal(PartialState): # TODO: unify PartialState and Goal # def __init__(self, values, test=lambda state: True): # self.conditions = values # self.test = test # def __eq__(self, other): # return (type(self) == type(other)) and (self.conditions == other.conditions) # def __ne__(self, other): # return not self == other # def __hash__(self): # return hash((self.__class__, frozenset(self.cond()))) # def __str__(self): # return self.__class__.__name__ + str_object(self.conditions) # __repr__ = __str__ # # class PartialState(object): # def cond(self): # return self.conditions.items() # def __contains__(self, state): # return all(state[var] == value for var, value in self.cond()) #and self.test(state) # # Path: sas/hsp.py # def h_add(state, goal, operators): # _, operator_costs = compute_costs(state, goal, operators, op=sum) # return operator_costs[goal].cost if goal in operator_costs else None # # def h_max(state, goal, operators): # _, operator_costs = compute_costs(state, goal, operators, op=max) # return operator_costs[goal].cost if goal in operator_costs else None , which may include functions, classes, or code. Output only the next line.
return h_max(self.actions[0], GoalConditions([g for g, _ in self.agenda]), operators)
Here is a snippet: <|code_start|> for vertex in self.vertices.values(): vertex.reset() if self.start.includes(vertex.substate): vertex.initial = True #print(start, '\n') for vertex in self.initial_vertices(): vertex.set_reachable() #print(self.queue) #print([c for c in self.connectors.values() if c.active], '\n') self.goal.set_active() #print(self.queue) #print([c for c in self.connectors.values() if c.active], '\n') #self.graph('start.pdf', reachable=False) while time() - start_time <= max_time and iterations <= max_iterations and cycles <= max_cycles: if self.greedy and self.goal.reachable: break subplanner = self.queue.popleft() if subplanner is None: # Dummy node to count the number of cycles cycles += 1 if len(self.queue) == 0: break self.queue.append(None) continue if not subplanner.queued or subplanner.generation_history[self.state_uses[start]] >= max_generations: continue # NOTE - treating queued as whether it should be in the queue subplanner.queued = False #print(subplanner.goal_connector.active, self.is_connector_active(subplanner.goal_connector)) if UPDATE_INACTIVE: self.update_active() <|code_end|> . Write the next line using the current file imports: from .connectivity_graph import * from misc.utils import * from .utils import PRUNE_INACTIVE, CYCLE_INACTIVE, UPDATE_INACTIVE from pygraphviz import AGraph # NOTE - LIS machines do not have pygraphviz and context from other files: # Path: retired/planners/connectivity_graph/utils.py # PRUNE_INACTIVE = False # # CYCLE_INACTIVE = PRUNE_INACTIVE # # UPDATE_INACTIVE = False , which may include functions, classes, or code. Output only the next line.
if CYCLE_INACTIVE: self.is_connector_active(subplanner.goal_connector)
Given the following code snippet before the placeholder: <|code_start|> for edge in self.edges.values(): edge.reset() for vertex in self.vertices.values(): vertex.reset() if self.start.includes(vertex.substate): vertex.initial = True #print(start, '\n') for vertex in self.initial_vertices(): vertex.set_reachable() #print(self.queue) #print([c for c in self.connectors.values() if c.active], '\n') self.goal.set_active() #print(self.queue) #print([c for c in self.connectors.values() if c.active], '\n') #self.graph('start.pdf', reachable=False) while time() - start_time <= max_time and iterations <= max_iterations and cycles <= max_cycles: if self.greedy and self.goal.reachable: break subplanner = self.queue.popleft() if subplanner is None: # Dummy node to count the number of cycles cycles += 1 if len(self.queue) == 0: break self.queue.append(None) continue if not subplanner.queued or subplanner.generation_history[self.state_uses[start]] >= max_generations: continue # NOTE - treating queued as whether it should be in the queue subplanner.queued = False #print(subplanner.goal_connector.active, self.is_connector_active(subplanner.goal_connector)) <|code_end|> , predict the next line using imports from the current file: from .connectivity_graph import * from misc.utils import * from .utils import PRUNE_INACTIVE, CYCLE_INACTIVE, UPDATE_INACTIVE from pygraphviz import AGraph # NOTE - LIS machines do not have pygraphviz and context including class names, function names, and sometimes code from other files: # Path: retired/planners/connectivity_graph/utils.py # PRUNE_INACTIVE = False # # CYCLE_INACTIVE = PRUNE_INACTIVE # # UPDATE_INACTIVE = False . Output only the next line.
if UPDATE_INACTIVE: self.update_active()
Continue the code snippet: <|code_start|> def macro_greedy_cost_fn(v): # TODO: only want to perform this if the macro is helpful if v.parent_edge is None: return v.h_cost return v.parent_edge.source.h_cost - len(v.parent_edge.operator) def macro_deferred_best_first_search(start, goal, generator, priority, stack=False, debug=None, **kwargs): space = StateSpace(generator, start, max_extensions=1, **kwargs) sv = space.root if sv.contained(goal): return space.solution(sv) <|code_end|> . Use current file imports: from misc.functions import elapsed_time, first from misc.numerical import INF from misc.priority_queue import FILOPriorityQueue, FIFOPriorityQueue from planner.progression.best_first import order_successors from planner.state_space import StateSpace and context (classes, functions, or code) from other files: # Path: misc/functions.py # def elapsed_time(start_time): # return time.time() - start_time # # def first(function, iterable): # for item in iterable: # if function(item): # return item # return None # # Path: misc/numerical.py # INF = float('inf') # # Path: misc/priority_queue.py # class FILOPriorityQueue(PriorityQueue): # sign = -1 # # class FIFOPriorityQueue(PriorityQueue): # sign = 1 # # Path: planner/progression/best_first.py # def order_successors(successors, stack=False): # return reversed(successors) if stack else successors # # Path: planner/state_space.py # class StateSpace(object): # def __init__(self, generator_fn, start, max_extensions=INF, max_generations=INF, max_cost=INF, max_length=INF, # max_time=INF, max_iterations=INF, verbose=True, dump_rate=1.): # 0 | 1 | INF # # TODO: move queue here? # self.start_time = time.time() # self.iterations = 0 # self.num_expanded = 0 # self.num_generations = 0 # self.vertices = {} # self.edges = [] # NOTE - allowing parallel-edges # #self.solutions = [] # if isinstance(generator_fn, tuple): # TODO - fix this by making the operators a direct argument # self.generator_fn, self.axioms = generator_fn # else: # self.generator_fn, self.axioms = generator_fn, [] # # TODO: could check whether these are violated generically # self.max_extensions = max_extensions # self.max_generations = max_generations # self.max_cost = max_cost # self.max_length = max_length # self.max_time = max_time # self.max_iterations = max_iterations # self.verbose = verbose # self.dump_rate = dump_rate # self.last_dump = time.time() # self.root = self[start] # self.root.cost = 0 # self.root.length = 0 # self.root.extensions += 1 # self.best_h = None # None | INF # def has_state(self, state): # return state in self.vertices # __contains__ = has_state # def get_state(self, state): # if state not in self: # self.vertices[state] = Vertex(state, self) # return self.vertices[state] # __getitem__ = get_state # def __iter__(self): # return iter(self.vertices.values()) # def __len__(self): # return len(self.vertices) # def new_iteration(self, vertex): # self.iterations += 1 # if elapsed_time(self.last_dump) >= self.dump_rate: # self.dump() # # TODO: record dead ends here # #return vertex.is_dead_end() # TODO: might not have called h_cost # def is_active(self): # return (elapsed_time(self.start_time) < self.max_time) or (self.iterations < self.max_iterations) # def extend(self, vertex, operator): # if (vertex.cost + operator.cost <= self.max_cost) \ # and (vertex.length + len(operator) <= self.max_length) \ # and vertex.contained(operator): # #if vertex.state in operator: # if self.axioms: # assert not isinstance(operator, MacroOperator) # sink_state = operator.apply(vertex.state) # TODO - this won't work for MacroOperators yet? # else: # sink_state = operator(vertex.state)[-1] if isinstance(operator, MacroOperator) else operator(vertex.state) # if (sink_state is not None) and (self[sink_state].extensions < self.max_extensions): # sink_vertex = self[sink_state] # self.edges.append(Edge(vertex, sink_vertex, operator, self)) # sink_vertex.extensions += 1 # return sink_vertex # return None # def retrace(self, vertex): # if vertex is not None: # if vertex == self.root: # return [] # sequence = self.retrace(vertex.parent_edge.source) # if sequence is not None: # return sequence + list(vertex.parent_edge.operator) # return None # def plan(self, vertex): # sequence = self.retrace(vertex) # if sequence is None: # return None # return Plan(self.root.state, sequence) # def solution(self, vertex): # #self.dump() # return Solution(self.plan(vertex), self) # def failure(self): # self.dump() # return Solution(None, self) # def time_elapsed(self): # return elapsed_time(self.start_time) # def __repr__(self): # # TODO: deadends, backtracking, expanded/generated until last jump, etc. # return 'Iterations: {iterations} | State Space: {state_space} | Expanded: {expanded} | ' \ # 'Generations: {generations} | Heuristic: {heuristic} | Time: {time:.3f}'.format( # iterations=self.iterations, state_space=len(self), expanded=self.num_expanded, # generations=self.num_generations, heuristic=self.best_h, time=self.time_elapsed()) # def dump(self): # if not self.verbose: # return # self.last_dump = time.time() # print(self) # # TODO: record iterations since last heuristic . Output only the next line.
queue = (FILOPriorityQueue if stack else FIFOPriorityQueue)([(None, sv)])
Here is a snippet: <|code_start|> def macro_greedy_cost_fn(v): # TODO: only want to perform this if the macro is helpful if v.parent_edge is None: return v.h_cost return v.parent_edge.source.h_cost - len(v.parent_edge.operator) def macro_deferred_best_first_search(start, goal, generator, priority, stack=False, debug=None, **kwargs): space = StateSpace(generator, start, max_extensions=1, **kwargs) sv = space.root if sv.contained(goal): return space.solution(sv) <|code_end|> . Write the next line using the current file imports: from misc.functions import elapsed_time, first from misc.numerical import INF from misc.priority_queue import FILOPriorityQueue, FIFOPriorityQueue from planner.progression.best_first import order_successors from planner.state_space import StateSpace and context from other files: # Path: misc/functions.py # def elapsed_time(start_time): # return time.time() - start_time # # def first(function, iterable): # for item in iterable: # if function(item): # return item # return None # # Path: misc/numerical.py # INF = float('inf') # # Path: misc/priority_queue.py # class FILOPriorityQueue(PriorityQueue): # sign = -1 # # class FIFOPriorityQueue(PriorityQueue): # sign = 1 # # Path: planner/progression/best_first.py # def order_successors(successors, stack=False): # return reversed(successors) if stack else successors # # Path: planner/state_space.py # class StateSpace(object): # def __init__(self, generator_fn, start, max_extensions=INF, max_generations=INF, max_cost=INF, max_length=INF, # max_time=INF, max_iterations=INF, verbose=True, dump_rate=1.): # 0 | 1 | INF # # TODO: move queue here? # self.start_time = time.time() # self.iterations = 0 # self.num_expanded = 0 # self.num_generations = 0 # self.vertices = {} # self.edges = [] # NOTE - allowing parallel-edges # #self.solutions = [] # if isinstance(generator_fn, tuple): # TODO - fix this by making the operators a direct argument # self.generator_fn, self.axioms = generator_fn # else: # self.generator_fn, self.axioms = generator_fn, [] # # TODO: could check whether these are violated generically # self.max_extensions = max_extensions # self.max_generations = max_generations # self.max_cost = max_cost # self.max_length = max_length # self.max_time = max_time # self.max_iterations = max_iterations # self.verbose = verbose # self.dump_rate = dump_rate # self.last_dump = time.time() # self.root = self[start] # self.root.cost = 0 # self.root.length = 0 # self.root.extensions += 1 # self.best_h = None # None | INF # def has_state(self, state): # return state in self.vertices # __contains__ = has_state # def get_state(self, state): # if state not in self: # self.vertices[state] = Vertex(state, self) # return self.vertices[state] # __getitem__ = get_state # def __iter__(self): # return iter(self.vertices.values()) # def __len__(self): # return len(self.vertices) # def new_iteration(self, vertex): # self.iterations += 1 # if elapsed_time(self.last_dump) >= self.dump_rate: # self.dump() # # TODO: record dead ends here # #return vertex.is_dead_end() # TODO: might not have called h_cost # def is_active(self): # return (elapsed_time(self.start_time) < self.max_time) or (self.iterations < self.max_iterations) # def extend(self, vertex, operator): # if (vertex.cost + operator.cost <= self.max_cost) \ # and (vertex.length + len(operator) <= self.max_length) \ # and vertex.contained(operator): # #if vertex.state in operator: # if self.axioms: # assert not isinstance(operator, MacroOperator) # sink_state = operator.apply(vertex.state) # TODO - this won't work for MacroOperators yet? # else: # sink_state = operator(vertex.state)[-1] if isinstance(operator, MacroOperator) else operator(vertex.state) # if (sink_state is not None) and (self[sink_state].extensions < self.max_extensions): # sink_vertex = self[sink_state] # self.edges.append(Edge(vertex, sink_vertex, operator, self)) # sink_vertex.extensions += 1 # return sink_vertex # return None # def retrace(self, vertex): # if vertex is not None: # if vertex == self.root: # return [] # sequence = self.retrace(vertex.parent_edge.source) # if sequence is not None: # return sequence + list(vertex.parent_edge.operator) # return None # def plan(self, vertex): # sequence = self.retrace(vertex) # if sequence is None: # return None # return Plan(self.root.state, sequence) # def solution(self, vertex): # #self.dump() # return Solution(self.plan(vertex), self) # def failure(self): # self.dump() # return Solution(None, self) # def time_elapsed(self): # return elapsed_time(self.start_time) # def __repr__(self): # # TODO: deadends, backtracking, expanded/generated until last jump, etc. # return 'Iterations: {iterations} | State Space: {state_space} | Expanded: {expanded} | ' \ # 'Generations: {generations} | Heuristic: {heuristic} | Time: {time:.3f}'.format( # iterations=self.iterations, state_space=len(self), expanded=self.num_expanded, # generations=self.num_generations, heuristic=self.best_h, time=self.time_elapsed()) # def dump(self): # if not self.verbose: # return # self.last_dump = time.time() # print(self) # # TODO: record iterations since last heuristic , which may include functions, classes, or code. Output only the next line.
queue = (FILOPriorityQueue if stack else FIFOPriorityQueue)([(None, sv)])
Predict the next line for this snippet: <|code_start|> def macro_greedy_cost_fn(v): # TODO: only want to perform this if the macro is helpful if v.parent_edge is None: return v.h_cost return v.parent_edge.source.h_cost - len(v.parent_edge.operator) def macro_deferred_best_first_search(start, goal, generator, priority, stack=False, debug=None, **kwargs): <|code_end|> with the help of current file imports: from misc.functions import elapsed_time, first from misc.numerical import INF from misc.priority_queue import FILOPriorityQueue, FIFOPriorityQueue from planner.progression.best_first import order_successors from planner.state_space import StateSpace and context from other files: # Path: misc/functions.py # def elapsed_time(start_time): # return time.time() - start_time # # def first(function, iterable): # for item in iterable: # if function(item): # return item # return None # # Path: misc/numerical.py # INF = float('inf') # # Path: misc/priority_queue.py # class FILOPriorityQueue(PriorityQueue): # sign = -1 # # class FIFOPriorityQueue(PriorityQueue): # sign = 1 # # Path: planner/progression/best_first.py # def order_successors(successors, stack=False): # return reversed(successors) if stack else successors # # Path: planner/state_space.py # class StateSpace(object): # def __init__(self, generator_fn, start, max_extensions=INF, max_generations=INF, max_cost=INF, max_length=INF, # max_time=INF, max_iterations=INF, verbose=True, dump_rate=1.): # 0 | 1 | INF # # TODO: move queue here? # self.start_time = time.time() # self.iterations = 0 # self.num_expanded = 0 # self.num_generations = 0 # self.vertices = {} # self.edges = [] # NOTE - allowing parallel-edges # #self.solutions = [] # if isinstance(generator_fn, tuple): # TODO - fix this by making the operators a direct argument # self.generator_fn, self.axioms = generator_fn # else: # self.generator_fn, self.axioms = generator_fn, [] # # TODO: could check whether these are violated generically # self.max_extensions = max_extensions # self.max_generations = max_generations # self.max_cost = max_cost # self.max_length = max_length # self.max_time = max_time # self.max_iterations = max_iterations # self.verbose = verbose # self.dump_rate = dump_rate # self.last_dump = time.time() # self.root = self[start] # self.root.cost = 0 # self.root.length = 0 # self.root.extensions += 1 # self.best_h = None # None | INF # def has_state(self, state): # return state in self.vertices # __contains__ = has_state # def get_state(self, state): # if state not in self: # self.vertices[state] = Vertex(state, self) # return self.vertices[state] # __getitem__ = get_state # def __iter__(self): # return iter(self.vertices.values()) # def __len__(self): # return len(self.vertices) # def new_iteration(self, vertex): # self.iterations += 1 # if elapsed_time(self.last_dump) >= self.dump_rate: # self.dump() # # TODO: record dead ends here # #return vertex.is_dead_end() # TODO: might not have called h_cost # def is_active(self): # return (elapsed_time(self.start_time) < self.max_time) or (self.iterations < self.max_iterations) # def extend(self, vertex, operator): # if (vertex.cost + operator.cost <= self.max_cost) \ # and (vertex.length + len(operator) <= self.max_length) \ # and vertex.contained(operator): # #if vertex.state in operator: # if self.axioms: # assert not isinstance(operator, MacroOperator) # sink_state = operator.apply(vertex.state) # TODO - this won't work for MacroOperators yet? # else: # sink_state = operator(vertex.state)[-1] if isinstance(operator, MacroOperator) else operator(vertex.state) # if (sink_state is not None) and (self[sink_state].extensions < self.max_extensions): # sink_vertex = self[sink_state] # self.edges.append(Edge(vertex, sink_vertex, operator, self)) # sink_vertex.extensions += 1 # return sink_vertex # return None # def retrace(self, vertex): # if vertex is not None: # if vertex == self.root: # return [] # sequence = self.retrace(vertex.parent_edge.source) # if sequence is not None: # return sequence + list(vertex.parent_edge.operator) # return None # def plan(self, vertex): # sequence = self.retrace(vertex) # if sequence is None: # return None # return Plan(self.root.state, sequence) # def solution(self, vertex): # #self.dump() # return Solution(self.plan(vertex), self) # def failure(self): # self.dump() # return Solution(None, self) # def time_elapsed(self): # return elapsed_time(self.start_time) # def __repr__(self): # # TODO: deadends, backtracking, expanded/generated until last jump, etc. # return 'Iterations: {iterations} | State Space: {state_space} | Expanded: {expanded} | ' \ # 'Generations: {generations} | Heuristic: {heuristic} | Time: {time:.3f}'.format( # iterations=self.iterations, state_space=len(self), expanded=self.num_expanded, # generations=self.num_generations, heuristic=self.best_h, time=self.time_elapsed()) # def dump(self): # if not self.verbose: # return # self.last_dump = time.time() # print(self) # # TODO: record iterations since last heuristic , which may contain function names, class names, or code. Output only the next line.
space = StateSpace(generator, start, max_extensions=1, **kwargs)
Based on the snippet: <|code_start|>#!/usr/bin/env python from __future__ import print_function #from planner.main import simple_debug, pause_debug DIRECTORY = './simulations/strips/planning/' def solve_strips(problem, print_profile=False, **kwargs): initial, goal, operators = problem() operators = randomize(operators) #dt = datetime.datetime.now() #directory = DIRECTORY + '{}/{}/{}/'.format(problem.__name__, # dt.strftime('%Y-%m-%d'), dt.strftime('%H-%M-%S')) print('Solving strips problem ' + problem.__name__ + '\n' + SEPARATOR) def execute(): start_time = time() try: output = default_plan(initial, goal, operators, debug=None, **kwargs) # None | simple_debug except KeyboardInterrupt: output = None, elapsed_time(start_time) #make_dir(directory) #print('Created directory:', directory) return output <|code_end|> , predict the immediate next line with the help of imports: import argparse import random import strips.domains as domains from time import time from misc.profiling import run_profile, str_profile from misc.functions import randomize, elapsed_time from misc.utils import SEPARATOR from strips.utils import default_plan, SEARCHES, EVALUATORS, HEURISTICS, SUCCESSORS and context (classes, functions, sometimes code) from other files: # Path: misc/profiling.py # def run_profile(function): # pr = cProfile.Profile() # cProfile.run('simulation()', sort = 'cumtime') # pr.enable() # results = function() # pr.disable() # return results, pr # # def str_profile(pr, limit=25): # try: # from StringIO import StringIO # except ImportError: # from io import StringIO # output = StringIO() # ps = pstats.Stats(pr, stream=output) # # print(ps.__dict__.keys()) # directory = os.getcwd() # for (f, l, fn), value in ps.stats.items(): # if directory in f: # ps.stats[(f[f.index(directory) + len(directory):], l, fn)] = value # del ps.stats[(f, l, fn)] # ps.fcn_list = list(ps.stats.keys()) # ps.sort_stats('tottime') # .strip_dirs() # # ps.print_stats(limit) # ps.print_stats(.1) # ps.reverse_order() # so = '\n' + '\n'.join(output.getvalue().split('\n')[::-1]).strip('\n') # # print('\n' + output.getvalue().strip('\n') + '\n') # output.close() # return so # # Path: misc/functions.py # def randomize(sequence): # shuffle(sequence) # return sequence # # def elapsed_time(start_time): # return time.time() - start_time # # Path: misc/utils.py # SEPARATOR = '\n'+85*'-'+'\n' # # Path: strips/utils.py # def default_plan(initial, goal, operators, axioms=[], **kwargs): # #return default_search(initial, goal, single_generator(goal, operators, axioms, default_successors)) # return solve_strips(initial, goal, operators, axioms=axioms, **kwargs) # # SEARCHES = { # # TODO: make the key be the function name # 'a_star': a_star_search, # 'eager': best_first_search, # 'lazy': deferred_best_first_search, # 'hill_climbing': hill_climbing_search, # 'random_walk': random_walk, # 'mcts': mcts, # } # # EVALUATORS = { # 'bfs': bfs, # 'uniform': uniform, # 'astar': astar, # 'wastar2': wastar2, # 'wastar3': wastar3, # 'greedy': greedy, # } # # HEURISTICS = { # 'blind': h_blind, # 'goal': h_goal, # 'max': h_max, # 'add': h_add, # 'ff': h_ff_add, # } # # SUCCESSORS = { # 'all': ha_all, # ha_all | ha_applicable # 'random': ha_random, # #'ff': first_goals, # first_operators # TODO: make a wrapper # } . Output only the next line.
(plan, state_space), profile_output = run_profile(execute)
Given the code snippet: <|code_start|>def solve_strips(problem, print_profile=False, **kwargs): initial, goal, operators = problem() operators = randomize(operators) #dt = datetime.datetime.now() #directory = DIRECTORY + '{}/{}/{}/'.format(problem.__name__, # dt.strftime('%Y-%m-%d'), dt.strftime('%H-%M-%S')) print('Solving strips problem ' + problem.__name__ + '\n' + SEPARATOR) def execute(): start_time = time() try: output = default_plan(initial, goal, operators, debug=None, **kwargs) # None | simple_debug except KeyboardInterrupt: output = None, elapsed_time(start_time) #make_dir(directory) #print('Created directory:', directory) return output (plan, state_space), profile_output = run_profile(execute) #print('Wrote', directory+'profile') print(SEPARATOR) data = (str(plan) if (plan is not None) else 'Unable to find a plan') + '\n\n' + str(state_space) print(data) #write(directory + 'planner_statistics', data) #print('Wrote', directory+'planner_statistics') if print_profile: print(SEPARATOR) <|code_end|> , generate the next line using the imports in this file: import argparse import random import strips.domains as domains from time import time from misc.profiling import run_profile, str_profile from misc.functions import randomize, elapsed_time from misc.utils import SEPARATOR from strips.utils import default_plan, SEARCHES, EVALUATORS, HEURISTICS, SUCCESSORS and context (functions, classes, or occasionally code) from other files: # Path: misc/profiling.py # def run_profile(function): # pr = cProfile.Profile() # cProfile.run('simulation()', sort = 'cumtime') # pr.enable() # results = function() # pr.disable() # return results, pr # # def str_profile(pr, limit=25): # try: # from StringIO import StringIO # except ImportError: # from io import StringIO # output = StringIO() # ps = pstats.Stats(pr, stream=output) # # print(ps.__dict__.keys()) # directory = os.getcwd() # for (f, l, fn), value in ps.stats.items(): # if directory in f: # ps.stats[(f[f.index(directory) + len(directory):], l, fn)] = value # del ps.stats[(f, l, fn)] # ps.fcn_list = list(ps.stats.keys()) # ps.sort_stats('tottime') # .strip_dirs() # # ps.print_stats(limit) # ps.print_stats(.1) # ps.reverse_order() # so = '\n' + '\n'.join(output.getvalue().split('\n')[::-1]).strip('\n') # # print('\n' + output.getvalue().strip('\n') + '\n') # output.close() # return so # # Path: misc/functions.py # def randomize(sequence): # shuffle(sequence) # return sequence # # def elapsed_time(start_time): # return time.time() - start_time # # Path: misc/utils.py # SEPARATOR = '\n'+85*'-'+'\n' # # Path: strips/utils.py # def default_plan(initial, goal, operators, axioms=[], **kwargs): # #return default_search(initial, goal, single_generator(goal, operators, axioms, default_successors)) # return solve_strips(initial, goal, operators, axioms=axioms, **kwargs) # # SEARCHES = { # # TODO: make the key be the function name # 'a_star': a_star_search, # 'eager': best_first_search, # 'lazy': deferred_best_first_search, # 'hill_climbing': hill_climbing_search, # 'random_walk': random_walk, # 'mcts': mcts, # } # # EVALUATORS = { # 'bfs': bfs, # 'uniform': uniform, # 'astar': astar, # 'wastar2': wastar2, # 'wastar3': wastar3, # 'greedy': greedy, # } # # HEURISTICS = { # 'blind': h_blind, # 'goal': h_goal, # 'max': h_max, # 'add': h_add, # 'ff': h_ff_add, # } # # SUCCESSORS = { # 'all': ha_all, # ha_all | ha_applicable # 'random': ha_random, # #'ff': first_goals, # first_operators # TODO: make a wrapper # } . Output only the next line.
print(str_profile(profile_output))
Next line prediction: <|code_start|>#!/usr/bin/env python from __future__ import print_function #from planner.main import simple_debug, pause_debug DIRECTORY = './simulations/strips/planning/' def solve_strips(problem, print_profile=False, **kwargs): initial, goal, operators = problem() <|code_end|> . Use current file imports: (import argparse import random import strips.domains as domains from time import time from misc.profiling import run_profile, str_profile from misc.functions import randomize, elapsed_time from misc.utils import SEPARATOR from strips.utils import default_plan, SEARCHES, EVALUATORS, HEURISTICS, SUCCESSORS) and context including class names, function names, or small code snippets from other files: # Path: misc/profiling.py # def run_profile(function): # pr = cProfile.Profile() # cProfile.run('simulation()', sort = 'cumtime') # pr.enable() # results = function() # pr.disable() # return results, pr # # def str_profile(pr, limit=25): # try: # from StringIO import StringIO # except ImportError: # from io import StringIO # output = StringIO() # ps = pstats.Stats(pr, stream=output) # # print(ps.__dict__.keys()) # directory = os.getcwd() # for (f, l, fn), value in ps.stats.items(): # if directory in f: # ps.stats[(f[f.index(directory) + len(directory):], l, fn)] = value # del ps.stats[(f, l, fn)] # ps.fcn_list = list(ps.stats.keys()) # ps.sort_stats('tottime') # .strip_dirs() # # ps.print_stats(limit) # ps.print_stats(.1) # ps.reverse_order() # so = '\n' + '\n'.join(output.getvalue().split('\n')[::-1]).strip('\n') # # print('\n' + output.getvalue().strip('\n') + '\n') # output.close() # return so # # Path: misc/functions.py # def randomize(sequence): # shuffle(sequence) # return sequence # # def elapsed_time(start_time): # return time.time() - start_time # # Path: misc/utils.py # SEPARATOR = '\n'+85*'-'+'\n' # # Path: strips/utils.py # def default_plan(initial, goal, operators, axioms=[], **kwargs): # #return default_search(initial, goal, single_generator(goal, operators, axioms, default_successors)) # return solve_strips(initial, goal, operators, axioms=axioms, **kwargs) # # SEARCHES = { # # TODO: make the key be the function name # 'a_star': a_star_search, # 'eager': best_first_search, # 'lazy': deferred_best_first_search, # 'hill_climbing': hill_climbing_search, # 'random_walk': random_walk, # 'mcts': mcts, # } # # EVALUATORS = { # 'bfs': bfs, # 'uniform': uniform, # 'astar': astar, # 'wastar2': wastar2, # 'wastar3': wastar3, # 'greedy': greedy, # } # # HEURISTICS = { # 'blind': h_blind, # 'goal': h_goal, # 'max': h_max, # 'add': h_add, # 'ff': h_ff_add, # } # # SUCCESSORS = { # 'all': ha_all, # ha_all | ha_applicable # 'random': ha_random, # #'ff': first_goals, # first_operators # TODO: make a wrapper # } . Output only the next line.
operators = randomize(operators)
Based on the snippet: <|code_start|>#!/usr/bin/env python from __future__ import print_function #from planner.main import simple_debug, pause_debug DIRECTORY = './simulations/strips/planning/' def solve_strips(problem, print_profile=False, **kwargs): initial, goal, operators = problem() operators = randomize(operators) #dt = datetime.datetime.now() #directory = DIRECTORY + '{}/{}/{}/'.format(problem.__name__, # dt.strftime('%Y-%m-%d'), dt.strftime('%H-%M-%S')) print('Solving strips problem ' + problem.__name__ + '\n' + SEPARATOR) def execute(): start_time = time() try: output = default_plan(initial, goal, operators, debug=None, **kwargs) # None | simple_debug except KeyboardInterrupt: <|code_end|> , predict the immediate next line with the help of imports: import argparse import random import strips.domains as domains from time import time from misc.profiling import run_profile, str_profile from misc.functions import randomize, elapsed_time from misc.utils import SEPARATOR from strips.utils import default_plan, SEARCHES, EVALUATORS, HEURISTICS, SUCCESSORS and context (classes, functions, sometimes code) from other files: # Path: misc/profiling.py # def run_profile(function): # pr = cProfile.Profile() # cProfile.run('simulation()', sort = 'cumtime') # pr.enable() # results = function() # pr.disable() # return results, pr # # def str_profile(pr, limit=25): # try: # from StringIO import StringIO # except ImportError: # from io import StringIO # output = StringIO() # ps = pstats.Stats(pr, stream=output) # # print(ps.__dict__.keys()) # directory = os.getcwd() # for (f, l, fn), value in ps.stats.items(): # if directory in f: # ps.stats[(f[f.index(directory) + len(directory):], l, fn)] = value # del ps.stats[(f, l, fn)] # ps.fcn_list = list(ps.stats.keys()) # ps.sort_stats('tottime') # .strip_dirs() # # ps.print_stats(limit) # ps.print_stats(.1) # ps.reverse_order() # so = '\n' + '\n'.join(output.getvalue().split('\n')[::-1]).strip('\n') # # print('\n' + output.getvalue().strip('\n') + '\n') # output.close() # return so # # Path: misc/functions.py # def randomize(sequence): # shuffle(sequence) # return sequence # # def elapsed_time(start_time): # return time.time() - start_time # # Path: misc/utils.py # SEPARATOR = '\n'+85*'-'+'\n' # # Path: strips/utils.py # def default_plan(initial, goal, operators, axioms=[], **kwargs): # #return default_search(initial, goal, single_generator(goal, operators, axioms, default_successors)) # return solve_strips(initial, goal, operators, axioms=axioms, **kwargs) # # SEARCHES = { # # TODO: make the key be the function name # 'a_star': a_star_search, # 'eager': best_first_search, # 'lazy': deferred_best_first_search, # 'hill_climbing': hill_climbing_search, # 'random_walk': random_walk, # 'mcts': mcts, # } # # EVALUATORS = { # 'bfs': bfs, # 'uniform': uniform, # 'astar': astar, # 'wastar2': wastar2, # 'wastar3': wastar3, # 'greedy': greedy, # } # # HEURISTICS = { # 'blind': h_blind, # 'goal': h_goal, # 'max': h_max, # 'add': h_add, # 'ff': h_ff_add, # } # # SUCCESSORS = { # 'all': ha_all, # ha_all | ha_applicable # 'random': ha_random, # #'ff': first_goals, # first_operators # TODO: make a wrapper # } . Output only the next line.
output = None, elapsed_time(start_time)
Continue the code snippet: <|code_start|>#!/usr/bin/env python from __future__ import print_function #from planner.main import simple_debug, pause_debug DIRECTORY = './simulations/strips/planning/' def solve_strips(problem, print_profile=False, **kwargs): initial, goal, operators = problem() operators = randomize(operators) #dt = datetime.datetime.now() #directory = DIRECTORY + '{}/{}/{}/'.format(problem.__name__, # dt.strftime('%Y-%m-%d'), dt.strftime('%H-%M-%S')) <|code_end|> . Use current file imports: import argparse import random import strips.domains as domains from time import time from misc.profiling import run_profile, str_profile from misc.functions import randomize, elapsed_time from misc.utils import SEPARATOR from strips.utils import default_plan, SEARCHES, EVALUATORS, HEURISTICS, SUCCESSORS and context (classes, functions, or code) from other files: # Path: misc/profiling.py # def run_profile(function): # pr = cProfile.Profile() # cProfile.run('simulation()', sort = 'cumtime') # pr.enable() # results = function() # pr.disable() # return results, pr # # def str_profile(pr, limit=25): # try: # from StringIO import StringIO # except ImportError: # from io import StringIO # output = StringIO() # ps = pstats.Stats(pr, stream=output) # # print(ps.__dict__.keys()) # directory = os.getcwd() # for (f, l, fn), value in ps.stats.items(): # if directory in f: # ps.stats[(f[f.index(directory) + len(directory):], l, fn)] = value # del ps.stats[(f, l, fn)] # ps.fcn_list = list(ps.stats.keys()) # ps.sort_stats('tottime') # .strip_dirs() # # ps.print_stats(limit) # ps.print_stats(.1) # ps.reverse_order() # so = '\n' + '\n'.join(output.getvalue().split('\n')[::-1]).strip('\n') # # print('\n' + output.getvalue().strip('\n') + '\n') # output.close() # return so # # Path: misc/functions.py # def randomize(sequence): # shuffle(sequence) # return sequence # # def elapsed_time(start_time): # return time.time() - start_time # # Path: misc/utils.py # SEPARATOR = '\n'+85*'-'+'\n' # # Path: strips/utils.py # def default_plan(initial, goal, operators, axioms=[], **kwargs): # #return default_search(initial, goal, single_generator(goal, operators, axioms, default_successors)) # return solve_strips(initial, goal, operators, axioms=axioms, **kwargs) # # SEARCHES = { # # TODO: make the key be the function name # 'a_star': a_star_search, # 'eager': best_first_search, # 'lazy': deferred_best_first_search, # 'hill_climbing': hill_climbing_search, # 'random_walk': random_walk, # 'mcts': mcts, # } # # EVALUATORS = { # 'bfs': bfs, # 'uniform': uniform, # 'astar': astar, # 'wastar2': wastar2, # 'wastar3': wastar3, # 'greedy': greedy, # } # # HEURISTICS = { # 'blind': h_blind, # 'goal': h_goal, # 'max': h_max, # 'add': h_add, # 'ff': h_ff_add, # } # # SUCCESSORS = { # 'all': ha_all, # ha_all | ha_applicable # 'random': ha_random, # #'ff': first_goals, # first_operators # TODO: make a wrapper # } . Output only the next line.
print('Solving strips problem ' + problem.__name__ + '\n' + SEPARATOR)
Here is a snippet: <|code_start|>#!/usr/bin/env python from __future__ import print_function #from planner.main import simple_debug, pause_debug DIRECTORY = './simulations/strips/planning/' def solve_strips(problem, print_profile=False, **kwargs): initial, goal, operators = problem() operators = randomize(operators) #dt = datetime.datetime.now() #directory = DIRECTORY + '{}/{}/{}/'.format(problem.__name__, # dt.strftime('%Y-%m-%d'), dt.strftime('%H-%M-%S')) print('Solving strips problem ' + problem.__name__ + '\n' + SEPARATOR) def execute(): start_time = time() try: <|code_end|> . Write the next line using the current file imports: import argparse import random import strips.domains as domains from time import time from misc.profiling import run_profile, str_profile from misc.functions import randomize, elapsed_time from misc.utils import SEPARATOR from strips.utils import default_plan, SEARCHES, EVALUATORS, HEURISTICS, SUCCESSORS and context from other files: # Path: misc/profiling.py # def run_profile(function): # pr = cProfile.Profile() # cProfile.run('simulation()', sort = 'cumtime') # pr.enable() # results = function() # pr.disable() # return results, pr # # def str_profile(pr, limit=25): # try: # from StringIO import StringIO # except ImportError: # from io import StringIO # output = StringIO() # ps = pstats.Stats(pr, stream=output) # # print(ps.__dict__.keys()) # directory = os.getcwd() # for (f, l, fn), value in ps.stats.items(): # if directory in f: # ps.stats[(f[f.index(directory) + len(directory):], l, fn)] = value # del ps.stats[(f, l, fn)] # ps.fcn_list = list(ps.stats.keys()) # ps.sort_stats('tottime') # .strip_dirs() # # ps.print_stats(limit) # ps.print_stats(.1) # ps.reverse_order() # so = '\n' + '\n'.join(output.getvalue().split('\n')[::-1]).strip('\n') # # print('\n' + output.getvalue().strip('\n') + '\n') # output.close() # return so # # Path: misc/functions.py # def randomize(sequence): # shuffle(sequence) # return sequence # # def elapsed_time(start_time): # return time.time() - start_time # # Path: misc/utils.py # SEPARATOR = '\n'+85*'-'+'\n' # # Path: strips/utils.py # def default_plan(initial, goal, operators, axioms=[], **kwargs): # #return default_search(initial, goal, single_generator(goal, operators, axioms, default_successors)) # return solve_strips(initial, goal, operators, axioms=axioms, **kwargs) # # SEARCHES = { # # TODO: make the key be the function name # 'a_star': a_star_search, # 'eager': best_first_search, # 'lazy': deferred_best_first_search, # 'hill_climbing': hill_climbing_search, # 'random_walk': random_walk, # 'mcts': mcts, # } # # EVALUATORS = { # 'bfs': bfs, # 'uniform': uniform, # 'astar': astar, # 'wastar2': wastar2, # 'wastar3': wastar3, # 'greedy': greedy, # } # # HEURISTICS = { # 'blind': h_blind, # 'goal': h_goal, # 'max': h_max, # 'add': h_add, # 'ff': h_ff_add, # } # # SUCCESSORS = { # 'all': ha_all, # ha_all | ha_applicable # 'random': ha_random, # #'ff': first_goals, # first_operators # TODO: make a wrapper # } , which may include functions, classes, or code. Output only the next line.
output = default_plan(initial, goal, operators, debug=None, **kwargs) # None | simple_debug
Here is a snippet: <|code_start|> try: output = default_plan(initial, goal, operators, debug=None, **kwargs) # None | simple_debug except KeyboardInterrupt: output = None, elapsed_time(start_time) #make_dir(directory) #print('Created directory:', directory) return output (plan, state_space), profile_output = run_profile(execute) #print('Wrote', directory+'profile') print(SEPARATOR) data = (str(plan) if (plan is not None) else 'Unable to find a plan') + '\n\n' + str(state_space) print(data) #write(directory + 'planner_statistics', data) #print('Wrote', directory+'planner_statistics') if print_profile: print(SEPARATOR) print(str_profile(profile_output)) print(SEPARATOR) ########################################################################### def main(): parser = argparse.ArgumentParser() parser.add_argument('-p', '--problem', default='restack_blocks') parser.add_argument('-q', '--profile', action='store_true') parser.add_argument('-s', '--search', type=str, <|code_end|> . Write the next line using the current file imports: import argparse import random import strips.domains as domains from time import time from misc.profiling import run_profile, str_profile from misc.functions import randomize, elapsed_time from misc.utils import SEPARATOR from strips.utils import default_plan, SEARCHES, EVALUATORS, HEURISTICS, SUCCESSORS and context from other files: # Path: misc/profiling.py # def run_profile(function): # pr = cProfile.Profile() # cProfile.run('simulation()', sort = 'cumtime') # pr.enable() # results = function() # pr.disable() # return results, pr # # def str_profile(pr, limit=25): # try: # from StringIO import StringIO # except ImportError: # from io import StringIO # output = StringIO() # ps = pstats.Stats(pr, stream=output) # # print(ps.__dict__.keys()) # directory = os.getcwd() # for (f, l, fn), value in ps.stats.items(): # if directory in f: # ps.stats[(f[f.index(directory) + len(directory):], l, fn)] = value # del ps.stats[(f, l, fn)] # ps.fcn_list = list(ps.stats.keys()) # ps.sort_stats('tottime') # .strip_dirs() # # ps.print_stats(limit) # ps.print_stats(.1) # ps.reverse_order() # so = '\n' + '\n'.join(output.getvalue().split('\n')[::-1]).strip('\n') # # print('\n' + output.getvalue().strip('\n') + '\n') # output.close() # return so # # Path: misc/functions.py # def randomize(sequence): # shuffle(sequence) # return sequence # # def elapsed_time(start_time): # return time.time() - start_time # # Path: misc/utils.py # SEPARATOR = '\n'+85*'-'+'\n' # # Path: strips/utils.py # def default_plan(initial, goal, operators, axioms=[], **kwargs): # #return default_search(initial, goal, single_generator(goal, operators, axioms, default_successors)) # return solve_strips(initial, goal, operators, axioms=axioms, **kwargs) # # SEARCHES = { # # TODO: make the key be the function name # 'a_star': a_star_search, # 'eager': best_first_search, # 'lazy': deferred_best_first_search, # 'hill_climbing': hill_climbing_search, # 'random_walk': random_walk, # 'mcts': mcts, # } # # EVALUATORS = { # 'bfs': bfs, # 'uniform': uniform, # 'astar': astar, # 'wastar2': wastar2, # 'wastar3': wastar3, # 'greedy': greedy, # } # # HEURISTICS = { # 'blind': h_blind, # 'goal': h_goal, # 'max': h_max, # 'add': h_add, # 'ff': h_ff_add, # } # # SUCCESSORS = { # 'all': ha_all, # ha_all | ha_applicable # 'random': ha_random, # #'ff': first_goals, # first_operators # TODO: make a wrapper # } , which may include functions, classes, or code. Output only the next line.
default='eager', choices=sorted(SEARCHES), help='')
Continue the code snippet: <|code_start|> except KeyboardInterrupt: output = None, elapsed_time(start_time) #make_dir(directory) #print('Created directory:', directory) return output (plan, state_space), profile_output = run_profile(execute) #print('Wrote', directory+'profile') print(SEPARATOR) data = (str(plan) if (plan is not None) else 'Unable to find a plan') + '\n\n' + str(state_space) print(data) #write(directory + 'planner_statistics', data) #print('Wrote', directory+'planner_statistics') if print_profile: print(SEPARATOR) print(str_profile(profile_output)) print(SEPARATOR) ########################################################################### def main(): parser = argparse.ArgumentParser() parser.add_argument('-p', '--problem', default='restack_blocks') parser.add_argument('-q', '--profile', action='store_true') parser.add_argument('-s', '--search', type=str, default='eager', choices=sorted(SEARCHES), help='') parser.add_argument('-e', '--evaluator', type=str, <|code_end|> . Use current file imports: import argparse import random import strips.domains as domains from time import time from misc.profiling import run_profile, str_profile from misc.functions import randomize, elapsed_time from misc.utils import SEPARATOR from strips.utils import default_plan, SEARCHES, EVALUATORS, HEURISTICS, SUCCESSORS and context (classes, functions, or code) from other files: # Path: misc/profiling.py # def run_profile(function): # pr = cProfile.Profile() # cProfile.run('simulation()', sort = 'cumtime') # pr.enable() # results = function() # pr.disable() # return results, pr # # def str_profile(pr, limit=25): # try: # from StringIO import StringIO # except ImportError: # from io import StringIO # output = StringIO() # ps = pstats.Stats(pr, stream=output) # # print(ps.__dict__.keys()) # directory = os.getcwd() # for (f, l, fn), value in ps.stats.items(): # if directory in f: # ps.stats[(f[f.index(directory) + len(directory):], l, fn)] = value # del ps.stats[(f, l, fn)] # ps.fcn_list = list(ps.stats.keys()) # ps.sort_stats('tottime') # .strip_dirs() # # ps.print_stats(limit) # ps.print_stats(.1) # ps.reverse_order() # so = '\n' + '\n'.join(output.getvalue().split('\n')[::-1]).strip('\n') # # print('\n' + output.getvalue().strip('\n') + '\n') # output.close() # return so # # Path: misc/functions.py # def randomize(sequence): # shuffle(sequence) # return sequence # # def elapsed_time(start_time): # return time.time() - start_time # # Path: misc/utils.py # SEPARATOR = '\n'+85*'-'+'\n' # # Path: strips/utils.py # def default_plan(initial, goal, operators, axioms=[], **kwargs): # #return default_search(initial, goal, single_generator(goal, operators, axioms, default_successors)) # return solve_strips(initial, goal, operators, axioms=axioms, **kwargs) # # SEARCHES = { # # TODO: make the key be the function name # 'a_star': a_star_search, # 'eager': best_first_search, # 'lazy': deferred_best_first_search, # 'hill_climbing': hill_climbing_search, # 'random_walk': random_walk, # 'mcts': mcts, # } # # EVALUATORS = { # 'bfs': bfs, # 'uniform': uniform, # 'astar': astar, # 'wastar2': wastar2, # 'wastar3': wastar3, # 'greedy': greedy, # } # # HEURISTICS = { # 'blind': h_blind, # 'goal': h_goal, # 'max': h_max, # 'add': h_add, # 'ff': h_ff_add, # } # # SUCCESSORS = { # 'all': ha_all, # ha_all | ha_applicable # 'random': ha_random, # #'ff': first_goals, # first_operators # TODO: make a wrapper # } . Output only the next line.
default='greedy', choices=sorted(EVALUATORS), help='')
Given snippet: <|code_start|> #make_dir(directory) #print('Created directory:', directory) return output (plan, state_space), profile_output = run_profile(execute) #print('Wrote', directory+'profile') print(SEPARATOR) data = (str(plan) if (plan is not None) else 'Unable to find a plan') + '\n\n' + str(state_space) print(data) #write(directory + 'planner_statistics', data) #print('Wrote', directory+'planner_statistics') if print_profile: print(SEPARATOR) print(str_profile(profile_output)) print(SEPARATOR) ########################################################################### def main(): parser = argparse.ArgumentParser() parser.add_argument('-p', '--problem', default='restack_blocks') parser.add_argument('-q', '--profile', action='store_true') parser.add_argument('-s', '--search', type=str, default='eager', choices=sorted(SEARCHES), help='') parser.add_argument('-e', '--evaluator', type=str, default='greedy', choices=sorted(EVALUATORS), help='') parser.add_argument('-heu', '--heuristic', type=str, <|code_end|> , continue by predicting the next line. Consider current file imports: import argparse import random import strips.domains as domains from time import time from misc.profiling import run_profile, str_profile from misc.functions import randomize, elapsed_time from misc.utils import SEPARATOR from strips.utils import default_plan, SEARCHES, EVALUATORS, HEURISTICS, SUCCESSORS and context: # Path: misc/profiling.py # def run_profile(function): # pr = cProfile.Profile() # cProfile.run('simulation()', sort = 'cumtime') # pr.enable() # results = function() # pr.disable() # return results, pr # # def str_profile(pr, limit=25): # try: # from StringIO import StringIO # except ImportError: # from io import StringIO # output = StringIO() # ps = pstats.Stats(pr, stream=output) # # print(ps.__dict__.keys()) # directory = os.getcwd() # for (f, l, fn), value in ps.stats.items(): # if directory in f: # ps.stats[(f[f.index(directory) + len(directory):], l, fn)] = value # del ps.stats[(f, l, fn)] # ps.fcn_list = list(ps.stats.keys()) # ps.sort_stats('tottime') # .strip_dirs() # # ps.print_stats(limit) # ps.print_stats(.1) # ps.reverse_order() # so = '\n' + '\n'.join(output.getvalue().split('\n')[::-1]).strip('\n') # # print('\n' + output.getvalue().strip('\n') + '\n') # output.close() # return so # # Path: misc/functions.py # def randomize(sequence): # shuffle(sequence) # return sequence # # def elapsed_time(start_time): # return time.time() - start_time # # Path: misc/utils.py # SEPARATOR = '\n'+85*'-'+'\n' # # Path: strips/utils.py # def default_plan(initial, goal, operators, axioms=[], **kwargs): # #return default_search(initial, goal, single_generator(goal, operators, axioms, default_successors)) # return solve_strips(initial, goal, operators, axioms=axioms, **kwargs) # # SEARCHES = { # # TODO: make the key be the function name # 'a_star': a_star_search, # 'eager': best_first_search, # 'lazy': deferred_best_first_search, # 'hill_climbing': hill_climbing_search, # 'random_walk': random_walk, # 'mcts': mcts, # } # # EVALUATORS = { # 'bfs': bfs, # 'uniform': uniform, # 'astar': astar, # 'wastar2': wastar2, # 'wastar3': wastar3, # 'greedy': greedy, # } # # HEURISTICS = { # 'blind': h_blind, # 'goal': h_goal, # 'max': h_max, # 'add': h_add, # 'ff': h_ff_add, # } # # SUCCESSORS = { # 'all': ha_all, # ha_all | ha_applicable # 'random': ha_random, # #'ff': first_goals, # first_operators # TODO: make a wrapper # } which might include code, classes, or functions. Output only the next line.
default='ff', choices=sorted(HEURISTICS), help='')
Next line prediction: <|code_start|> return output (plan, state_space), profile_output = run_profile(execute) #print('Wrote', directory+'profile') print(SEPARATOR) data = (str(plan) if (plan is not None) else 'Unable to find a plan') + '\n\n' + str(state_space) print(data) #write(directory + 'planner_statistics', data) #print('Wrote', directory+'planner_statistics') if print_profile: print(SEPARATOR) print(str_profile(profile_output)) print(SEPARATOR) ########################################################################### def main(): parser = argparse.ArgumentParser() parser.add_argument('-p', '--problem', default='restack_blocks') parser.add_argument('-q', '--profile', action='store_true') parser.add_argument('-s', '--search', type=str, default='eager', choices=sorted(SEARCHES), help='') parser.add_argument('-e', '--evaluator', type=str, default='greedy', choices=sorted(EVALUATORS), help='') parser.add_argument('-heu', '--heuristic', type=str, default='ff', choices=sorted(HEURISTICS), help='') parser.add_argument('-suc', '--successors', type=str, <|code_end|> . Use current file imports: (import argparse import random import strips.domains as domains from time import time from misc.profiling import run_profile, str_profile from misc.functions import randomize, elapsed_time from misc.utils import SEPARATOR from strips.utils import default_plan, SEARCHES, EVALUATORS, HEURISTICS, SUCCESSORS) and context including class names, function names, or small code snippets from other files: # Path: misc/profiling.py # def run_profile(function): # pr = cProfile.Profile() # cProfile.run('simulation()', sort = 'cumtime') # pr.enable() # results = function() # pr.disable() # return results, pr # # def str_profile(pr, limit=25): # try: # from StringIO import StringIO # except ImportError: # from io import StringIO # output = StringIO() # ps = pstats.Stats(pr, stream=output) # # print(ps.__dict__.keys()) # directory = os.getcwd() # for (f, l, fn), value in ps.stats.items(): # if directory in f: # ps.stats[(f[f.index(directory) + len(directory):], l, fn)] = value # del ps.stats[(f, l, fn)] # ps.fcn_list = list(ps.stats.keys()) # ps.sort_stats('tottime') # .strip_dirs() # # ps.print_stats(limit) # ps.print_stats(.1) # ps.reverse_order() # so = '\n' + '\n'.join(output.getvalue().split('\n')[::-1]).strip('\n') # # print('\n' + output.getvalue().strip('\n') + '\n') # output.close() # return so # # Path: misc/functions.py # def randomize(sequence): # shuffle(sequence) # return sequence # # def elapsed_time(start_time): # return time.time() - start_time # # Path: misc/utils.py # SEPARATOR = '\n'+85*'-'+'\n' # # Path: strips/utils.py # def default_plan(initial, goal, operators, axioms=[], **kwargs): # #return default_search(initial, goal, single_generator(goal, operators, axioms, default_successors)) # return solve_strips(initial, goal, operators, axioms=axioms, **kwargs) # # SEARCHES = { # # TODO: make the key be the function name # 'a_star': a_star_search, # 'eager': best_first_search, # 'lazy': deferred_best_first_search, # 'hill_climbing': hill_climbing_search, # 'random_walk': random_walk, # 'mcts': mcts, # } # # EVALUATORS = { # 'bfs': bfs, # 'uniform': uniform, # 'astar': astar, # 'wastar2': wastar2, # 'wastar3': wastar3, # 'greedy': greedy, # } # # HEURISTICS = { # 'blind': h_blind, # 'goal': h_goal, # 'max': h_max, # 'add': h_add, # 'ff': h_ff_add, # } # # SUCCESSORS = { # 'all': ha_all, # ha_all | ha_applicable # 'random': ha_random, # #'ff': first_goals, # first_operators # TODO: make a wrapper # } . Output only the next line.
default='all', choices=sorted(SUCCESSORS), help='')
Using the snippet: <|code_start|> if DELAYED_ACTIVATION and not connector.reachable: return def set_inactive(self): if not self.active: return self.active = False for connector in self.connectors: connector.update_inactive() for source_vertex, _ in self.mappings: if source_vertex is not None: source_vertex.update_inactive() def update_inactive(self): if not self.active or self == self.rg.goal: return # TODO - decide if better condition self.active = False # Temporarily set to inactive for _, sink_vertex in self.mappings: sink_vertex.update_inactive() if sink_vertex.active: self.active = True return # Cannot find active parent node self.set_inactive() def __str__(self): return 'E(' + str(self.value) + ')' __repr__ = __str__ def node_str(self): node_str = self.value.__class__.__name__ <|code_end|> , determine the next line of code. You have imports: from .utils import * from planner.operators import Operator from misc.utils import str_object and context (class names, function names, or code) available: # Path: planner/operators.py # class Operator(object): # def __init__(self, args): # self.args = args # for k, v in args.items(): # setattr(self, k, v) # self.conditions = [] # self.effects = {} # def __contains__(self, state): # return all(state in precondition for precondition in self.conditions) # def apply(self, state): # return State(dict(list(state) + [(var, effect(state)) for var, effect in self.effects.items()])) # def __call__(self, state): # if state not in self: return None # return self.apply(state) # def __iter__(self): # yield self # def __len__(self): # return 1 # def fixed_conditions(self): # fc = {} # for condition in self.conditions: # if isinstance(condition, SubstateCondition): # for var, value in condition.substate: # if var in fc and fc[var] != value: # raise RuntimeError('Condition has conflicting conditions') # fc[var] = value # return fc # def fixed_effects(self): # return {var: effect.value for var, effect in self.effects.items() # if isinstance(effect, ValueEffect)} # def fixed_image(self): # return merge_dicts(self.fixed_conditions(), self.fixed_effects()) # #def image(self): # # pass # #def fixed_preimage(self): # # pass # def __eq__(self, other): # if type(self) != type(other): return False # return self.args == other.args # def __ne__(self, other): # return not self == other # def __hash__(self): # return hash((self.__class__, frozenset(self.args.items()))) # def __str__(self): # return self.__class__.__name__ + str_args(self.args) # __repr__ = __str__ # # Path: misc/utils.py # SEPARATOR = '\n'+85*'-'+'\n' # def arg_info(frame, ignore=['self']): # def function_name(stack): # NOTE - stack = inspect.stack() # def get_path(frame): # def get_directory(abs_path): # def global_fn(name): # def refresh(module_name): . Output only the next line.
if isinstance(self.value, Operator):
Using the snippet: <|code_start|> def set_inactive(self): if not self.active: return self.active = False for connector in self.connectors: connector.update_inactive() for source_vertex, _ in self.mappings: if source_vertex is not None: source_vertex.update_inactive() def update_inactive(self): if not self.active or self == self.rg.goal: return # TODO - decide if better condition self.active = False # Temporarily set to inactive for _, sink_vertex in self.mappings: sink_vertex.update_inactive() if sink_vertex.active: self.active = True return # Cannot find active parent node self.set_inactive() def __str__(self): return 'E(' + str(self.value) + ')' __repr__ = __str__ def node_str(self): node_str = self.value.__class__.__name__ if isinstance(self.value, Operator): for name, arg in self.value.args.items(): <|code_end|> , determine the next line of code. You have imports: from .utils import * from planner.operators import Operator from misc.utils import str_object and context (class names, function names, or code) available: # Path: planner/operators.py # class Operator(object): # def __init__(self, args): # self.args = args # for k, v in args.items(): # setattr(self, k, v) # self.conditions = [] # self.effects = {} # def __contains__(self, state): # return all(state in precondition for precondition in self.conditions) # def apply(self, state): # return State(dict(list(state) + [(var, effect(state)) for var, effect in self.effects.items()])) # def __call__(self, state): # if state not in self: return None # return self.apply(state) # def __iter__(self): # yield self # def __len__(self): # return 1 # def fixed_conditions(self): # fc = {} # for condition in self.conditions: # if isinstance(condition, SubstateCondition): # for var, value in condition.substate: # if var in fc and fc[var] != value: # raise RuntimeError('Condition has conflicting conditions') # fc[var] = value # return fc # def fixed_effects(self): # return {var: effect.value for var, effect in self.effects.items() # if isinstance(effect, ValueEffect)} # def fixed_image(self): # return merge_dicts(self.fixed_conditions(), self.fixed_effects()) # #def image(self): # # pass # #def fixed_preimage(self): # # pass # def __eq__(self, other): # if type(self) != type(other): return False # return self.args == other.args # def __ne__(self, other): # return not self == other # def __hash__(self): # return hash((self.__class__, frozenset(self.args.items()))) # def __str__(self): # return self.__class__.__name__ + str_args(self.args) # __repr__ = __str__ # # Path: misc/utils.py # SEPARATOR = '\n'+85*'-'+'\n' # def arg_info(frame, ignore=['self']): # def function_name(stack): # NOTE - stack = inspect.stack() # def get_path(frame): # def get_directory(abs_path): # def global_fn(name): # def refresh(module_name): . Output only the next line.
node_str += '\n' + str_object(name) + '=' + str_object(arg)
Based on the snippet: <|code_start|> s += 'end_rule\n' return s ########################################################################### #FD_PATH = os.path.join(FD_ROOT, 'builds/release32/bin/') FD_PATH = os.environ.get('FD_PATH', '') # TODO: warning if this path is not set SAS_PATH = 'output.sas' OUTPUT_PATH = 'sas_plan' #SEARCH_OPTIONS = '--heuristic "hlm,hff=lm_ff_syn(lm_rhw(reasonable_orders=true,lm_cost_type=plusone),cost_type=plusone)" ' \ # '--search "lazy_wastar([hff,hlm],preferred=[hff,hlm],w=1,max_time=%s,bound=%s)"' SEARCH_OPTIONS = '--heuristic "h=ff(transform=adapt_costs(cost_type=PLUSONE))" ' \ '--search "astar(h,max_time=%s,bound=%s)"' SEARCH_COMMAND = FD_PATH + 'bin/downward %s < %s'%(SEARCH_OPTIONS, SAS_PATH) #+ ' --search-time-limit %s'%10 # TODO - limit def write_sas(problem): s = write_version() + \ write_action_costs() + \ write_variables(problem) + \ write_mutexes(problem) + \ write_initial(problem) + \ write_goal(problem) + \ write_actions(problem) + \ write_axioms(problem) <|code_end|> , predict the immediate next line with the help of imports: from misc.io import write, read from os.path import expanduser from time import time import os and context (classes, functions, sometimes code) from other files: # Path: misc/io.py # def write(filename, string): # with open(filename, 'w') as f: # f.write(string) # # def read(filename): # with open(filename, 'r') as f: # return f.read() . Output only the next line.
write(SAS_PATH, s)
Here is a snippet: <|code_start|>FD_PATH = os.environ.get('FD_PATH', '') # TODO: warning if this path is not set SAS_PATH = 'output.sas' OUTPUT_PATH = 'sas_plan' #SEARCH_OPTIONS = '--heuristic "hlm,hff=lm_ff_syn(lm_rhw(reasonable_orders=true,lm_cost_type=plusone),cost_type=plusone)" ' \ # '--search "lazy_wastar([hff,hlm],preferred=[hff,hlm],w=1,max_time=%s,bound=%s)"' SEARCH_OPTIONS = '--heuristic "h=ff(transform=adapt_costs(cost_type=PLUSONE))" ' \ '--search "astar(h,max_time=%s,bound=%s)"' SEARCH_COMMAND = FD_PATH + 'bin/downward %s < %s'%(SEARCH_OPTIONS, SAS_PATH) #+ ' --search-time-limit %s'%10 # TODO - limit def write_sas(problem): s = write_version() + \ write_action_costs() + \ write_variables(problem) + \ write_mutexes(problem) + \ write_initial(problem) + \ write_goal(problem) + \ write_actions(problem) + \ write_axioms(problem) write(SAS_PATH, s) def fast_downward(debug=False, max_time=30, max_cost='infinity'): if os.path.exists(OUTPUT_PATH): os.remove(OUTPUT_PATH) command = SEARCH_COMMAND%(max_time, max_cost) t0 = time() p = os.popen(command) <|code_end|> . Write the next line using the current file imports: from misc.io import write, read from os.path import expanduser from time import time import os and context from other files: # Path: misc/io.py # def write(filename, string): # with open(filename, 'w') as f: # f.write(string) # # def read(filename): # with open(filename, 'r') as f: # return f.read() , which may include functions, classes, or code. Output only the next line.
output = p.read()
Given the following code snippet before the placeholder: <|code_start|> return values[scores.index(max(scores))] def argmin(function, sequence): values = list(sequence) scores = [function(x) for x in values] return values[scores.index(min(scores))] def pop_max(function, array): scores = [function(x) for x in array] return array.pop(scores.index(max(scores))) def pop_min(function, array): scores = [function(x) for x in array] return array.pop(scores.index(min(scores))) def safe_remove(sequence, item): try: sequence.remove(item) return True except ValueError: return False def safe_function(function, sequence, default): if len(sequence) == 0: return default return function(sequence) def safe_choice(sequence, default=None): return safe_function(choice, sequence, default) <|code_end|> , predict the next line using imports from the current file: from random import shuffle, choice from itertools import cycle, islice, permutations, chain, product, count from collections import Iterable from functools import reduce from .numerical import INF import operator import time and context including class names, function names, and sometimes code from other files: # Path: misc/numerical.py # INF = float('inf') . Output only the next line.
def safe_max(sequence, default=-INF):
Using the snippet: <|code_start|> Node = namedtuple('Node', ['cost', 'level']) # Record parent operator for values to even more efficiently linearize # TODO - helpful actions def compute_costs(state, goal, operators, op=max, unit=False, greedy=True): variable_nodes = defaultdict(dict) operator_nodes = {} conditions = defaultdict(lambda: defaultdict(set)) unsatisfied = {} queue = [] def applicable_operator(operator): if len(operator.conditions) != 0: operator_nodes[operator] = Node(op(variable_nodes[v][val].cost for v, val in operator.cond()), max(variable_nodes[v][val].level for v, val in operator.cond())) else: operator_nodes[operator] = Node(0, 0) if operator != goal: variable_node = Node(operator_nodes[operator].cost + (operator.cost if not unit else 1), operator_nodes[operator].level + 1) for var2, value2 in operator.eff(): if value2 not in variable_nodes[var2] or variable_node < variable_nodes[var2][value2]: variable_nodes[var2][value2] = variable_node <|code_end|> , determine the next line of code. You have imports: from misc.utils import * from misc.priority_queue import HeapElement and context (class names, function names, or code) available: # Path: misc/priority_queue.py # class HeapElement(object): # def __init__(self, key, value): # self.key = key # self.value = value # def __lt__(self, other): # return self.key < other.key # def __iter__(self): # return iter([self.key, self.value]) # def __repr__(self): # return '{}({}, {})'.format(self.__class__.__name__, self.key, self.value) . Output only the next line.
heappush(queue, HeapElement(variable_node, (var2, value2)))
Given snippet: <|code_start|> self.queued = False self.locked = False #self() # To immediately call the generator def __call__(self): if self.locked: return self.locked = True try: next(self.generator) self.generations += 1 except StopIteration: self.exhausted = True self.locked = False def __str__(self): return str(self.__class__.__name__) + '(' + str(self.goal_connector) + ')' __repr__ = __str__ ########################################################################### class DiscreteSubplanner(Subplanner): def __init__(self, operators): self.operators = operators def generator(self, start_vertex, goal_connector, rg): #yield # NOTE - include if don't want initial generation vertex = rg.vertex(goal_connector.condition.substate) vertex.connect(goal_connector) variable, value = list(vertex.substate)[0] for operator in self.operators: if variable in operator.effects: effect = operator.effects[variable] <|code_end|> , continue by predicting the next line. Consider current file imports: from .operators import is_discrete_effect from misc.generators import GeneratorWrapper and context: # Path: retired/discrete/operators.py # def is_discrete_effect(effect): # return isinstance(effect, ValueEffect) # # Path: misc/generators.py # class GeneratorWrapper(Iterator): # def __init__(self, generator): # self.generator = generator # def next(self): # return self.generator.next() # def __call__(self): # return self.next() which might include code, classes, or functions. Output only the next line.
if is_discrete_effect(effect) and effect.value == value:
Given the following code snippet before the placeholder: <|code_start|> # https://docs.python.org/2/library/functions.html#staticmethod class Subplanner(object): def applicable(self, start_vertex, goal_connector, rg): raise NotImplementedError('Subplanner must implement applicable(self, start_vertex, goal_connector, rg)') def generator(self, start_vertex, goal_connector, rg): raise NotImplementedError('Subplanner must implement generator(self, start_vertex, goal_connector, rg)') def __contains__(self, start_vertex, goal_connector, rg): return self.applicable(start_vertex, goal_connector, rg) def __call__(self, start_vertex, goal_connector, rg): return SubplannerGenerator(start_vertex, goal_connector, rg, self.generator) <|code_end|> , predict the next line using imports from the current file: from .operators import is_discrete_effect from misc.generators import GeneratorWrapper and context including class names, function names, and sometimes code from other files: # Path: retired/discrete/operators.py # def is_discrete_effect(effect): # return isinstance(effect, ValueEffect) # # Path: misc/generators.py # class GeneratorWrapper(Iterator): # def __init__(self, generator): # self.generator = generator # def next(self): # return self.generator.next() # def __call__(self): # return self.next() . Output only the next line.
class SubplannerGenerator(GeneratorWrapper):
Given snippet: <|code_start|> new_achieved.add(condition) new_causal_links += [(None, condition)] else: new_agenda.append(condition) consts = self.constraints for condition in operator.cond(): consts = add_constraint((condition, subgoal), consts) yield PartialPlan(self.initial, new_achieved, new_actions, consts, new_agenda, new_causal_links) # TODO - way of weighting the partial order planning progress def get_initial_plan(initial, goal): achieved = {atom for atom in initial.values.items()} agenda = [] for condition in goal.cond(): if condition not in achieved: if initial[condition[0]] == condition[1]: achieved.add(condition) else: agenda.append(condition) return PartialPlan(initial, achieved, set(), set(), agenda, [(None, atom) for atom in achieved]) <|code_end|> , continue by predicting the next line. Consider current file imports: import random from misc.priority_queue import Queue, FIFOPriorityQueue and context: # Path: misc/priority_queue.py # class Queue(object): # FIFO # def __init__(self, array=[]): # self.queue = deque(array) # def peek(self): # return self.queue[0] # def push(self, _, element): # self.queue.append(element) # def pop(self): # return self.queue.popleft() # def empty(self): # return len(self) == 0 # def __len__(self): # return len(self.queue) # def __repr__(self): # return '{}{}'.format(self.__class__.__name__, list(self.queue)) # # class FIFOPriorityQueue(PriorityQueue): # sign = 1 which might include code, classes, or functions. Output only the next line.
def relaxed_pop(initial, goal, operators, QueueClass=FIFOPriorityQueue):
Given the following code snippet before the placeholder: <|code_start|> self.batch_create_rows: gapic_v1.method.wrap_method( self.batch_create_rows, default_timeout=60.0, client_info=client_info, ), self.update_row: gapic_v1.method.wrap_method( self.update_row, default_timeout=60.0, client_info=client_info, ), self.batch_update_rows: gapic_v1.method.wrap_method( self.batch_update_rows, default_timeout=60.0, client_info=client_info, ), self.delete_row: gapic_v1.method.wrap_method( self.delete_row, default_timeout=60.0, client_info=client_info, ), self.batch_delete_rows: gapic_v1.method.wrap_method( self.batch_delete_rows, default_timeout=60.0, client_info=client_info, ), } def close(self): """Closes resources associated with the transport. .. warning:: Only call this method if the transport is NOT shared with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property def get_table( self, ) -> Callable[ <|code_end|> , predict the next line using imports from the current file: import abc import pkg_resources import google.auth # type: ignore import google.api_core from typing import Awaitable, Callable, Dict, Optional, Sequence, Union from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.area120.tables_v1alpha1.types import tables from google.protobuf import empty_pb2 # type: ignore and context including class names, function names, and sometimes code from other files: # Path: google/area120/tables_v1alpha1/types/tables.py # class View(proto.Enum): # class GetTableRequest(proto.Message): # class ListTablesRequest(proto.Message): # class ListTablesResponse(proto.Message): # class GetWorkspaceRequest(proto.Message): # class ListWorkspacesRequest(proto.Message): # class ListWorkspacesResponse(proto.Message): # class GetRowRequest(proto.Message): # class ListRowsRequest(proto.Message): # class ListRowsResponse(proto.Message): # class CreateRowRequest(proto.Message): # class BatchCreateRowsRequest(proto.Message): # class BatchCreateRowsResponse(proto.Message): # class UpdateRowRequest(proto.Message): # class BatchUpdateRowsRequest(proto.Message): # class BatchUpdateRowsResponse(proto.Message): # class DeleteRowRequest(proto.Message): # class BatchDeleteRowsRequest(proto.Message): # class Table(proto.Message): # class ColumnDescription(proto.Message): # class LabeledItem(proto.Message): # class RelationshipDetails(proto.Message): # class LookupDetails(proto.Message): # class Row(proto.Message): # class Workspace(proto.Message): # VIEW_UNSPECIFIED = 0 # COLUMN_ID_VIEW = 1 # def raw_page(self): # def raw_page(self): # def raw_page(self): . Output only the next line.
[tables.GetTableRequest], Union[tables.Table, Awaitable[tables.Table]]
Predict the next line after this snippet: <|code_start|># # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # class ListTablesPager: """A pager for iterating through ``list_tables`` requests. This class thinly wraps an initial :class:`google.area120.tables_v1alpha1.types.ListTablesResponse` object, and provides an ``__iter__`` method to iterate through its ``tables`` field. If there are more pages, the ``__iter__`` method will make additional ``ListTables`` requests and continue to iterate through the ``tables`` field on the corresponding responses. All the usual :class:`google.area120.tables_v1alpha1.types.ListTablesResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ def __init__( self, <|code_end|> using the current file's imports: from typing import ( Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, ) from google.area120.tables_v1alpha1.types import tables and any relevant context from other files: # Path: google/area120/tables_v1alpha1/types/tables.py # class View(proto.Enum): # class GetTableRequest(proto.Message): # class ListTablesRequest(proto.Message): # class ListTablesResponse(proto.Message): # class GetWorkspaceRequest(proto.Message): # class ListWorkspacesRequest(proto.Message): # class ListWorkspacesResponse(proto.Message): # class GetRowRequest(proto.Message): # class ListRowsRequest(proto.Message): # class ListRowsResponse(proto.Message): # class CreateRowRequest(proto.Message): # class BatchCreateRowsRequest(proto.Message): # class BatchCreateRowsResponse(proto.Message): # class UpdateRowRequest(proto.Message): # class BatchUpdateRowsRequest(proto.Message): # class BatchUpdateRowsResponse(proto.Message): # class DeleteRowRequest(proto.Message): # class BatchDeleteRowsRequest(proto.Message): # class Table(proto.Message): # class ColumnDescription(proto.Message): # class LabeledItem(proto.Message): # class RelationshipDetails(proto.Message): # class LookupDetails(proto.Message): # class Row(proto.Message): # class Workspace(proto.Message): # VIEW_UNSPECIFIED = 0 # COLUMN_ID_VIEW = 1 # def raw_page(self): # def raw_page(self): # def raw_page(self): . Output only the next line.
method: Callable[..., tables.ListTablesResponse],
Predict the next line for this snippet: <|code_start|> @celery.task(soft_time_limit=60) def update_or_create_key(uid): with TemporaryDirectory() as homedir: try: <|code_end|> with the help of current file imports: import celery import subprocess from bidb.utils.tempfile import TemporaryDirectory from bidb.utils.subprocess import check_output2 from .models import Key and context from other files: # Path: bidb/utils/tempfile.py # @contextlib.contextmanager # def TemporaryDirectory(): # name = tempfile.mkdtemp() # # try: # yield name # finally: # shutil.rmtree(name, ignore_errors=True) # # Path: bidb/utils/subprocess.py # def check_output2(args, stdin=None): # p = subprocess.Popen( # args, # stdout=subprocess.PIPE, # stdin=subprocess.PIPE, # stderr=subprocess.STDOUT, # ) # # out, _ = p.communicate(input=stdin) # # retcode = p.wait() # # if retcode: # raise subprocess.CalledProcessError(retcode, ' '.join(args), out) # # return out # # Path: bidb/keys/models.py # class Key(models.Model): # uid = models.CharField(max_length=255, unique=True) # # name = models.TextField() # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('-created',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d uid=%r name=%r" % ( # self.pk, # self.uid, # self.name, # ) # # def save(self, *args, **kwargs): # created = not self.pk # # super(Key, self).save(*args, **kwargs) # # if created: # from .tasks import update_or_create_key # # transaction.on_commit(lambda: update_or_create_key.delay(self.uid)) , which may contain function names, class names, or code. Output only the next line.
check_output2((
Predict the next line after this snippet: <|code_start|>@celery.task(soft_time_limit=60) def update_or_create_key(uid): with TemporaryDirectory() as homedir: try: check_output2(( 'gpg', '--homedir', homedir, '--keyserver', 'pgpkeys.mit.edu', '--recv-keys', uid, )) except subprocess.CalledProcessError as exc: print "E: {}: {}".format(exc, exc.output) return None, False data = check_output2(( 'gpg', '--homedir', homedir, '--with-colons', '--fixed-list-mode', '--fingerprint', uid, )) for line in data.splitlines(): if line.startswith('uid:'): name = line.split(':')[9] break else: raise ValueError("Could not parse name from key: {}".format(data)) <|code_end|> using the current file's imports: import celery import subprocess from bidb.utils.tempfile import TemporaryDirectory from bidb.utils.subprocess import check_output2 from .models import Key and any relevant context from other files: # Path: bidb/utils/tempfile.py # @contextlib.contextmanager # def TemporaryDirectory(): # name = tempfile.mkdtemp() # # try: # yield name # finally: # shutil.rmtree(name, ignore_errors=True) # # Path: bidb/utils/subprocess.py # def check_output2(args, stdin=None): # p = subprocess.Popen( # args, # stdout=subprocess.PIPE, # stdin=subprocess.PIPE, # stderr=subprocess.STDOUT, # ) # # out, _ = p.communicate(input=stdin) # # retcode = p.wait() # # if retcode: # raise subprocess.CalledProcessError(retcode, ' '.join(args), out) # # return out # # Path: bidb/keys/models.py # class Key(models.Model): # uid = models.CharField(max_length=255, unique=True) # # name = models.TextField() # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('-created',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d uid=%r name=%r" % ( # self.pk, # self.uid, # self.name, # ) # # def save(self, *args, **kwargs): # created = not self.pk # # super(Key, self).save(*args, **kwargs) # # if created: # from .tasks import update_or_create_key # # transaction.on_commit(lambda: update_or_create_key.delay(self.uid)) . Output only the next line.
return Key.objects.update_or_create(uid=uid, defaults={
Based on the snippet: <|code_start|>def source(request, name): source = get_object_or_404(Source, name=name) binaries = Binary.objects.filter( generated_binaries__buildinfo__source=source, ).distinct() versions = source.buildinfos.values_list('version', flat=True) \ .order_by('version').distinct() return render(request, 'packages/source.html', { 'source': source, 'binaries': binaries, 'versions': versions, }) def source_version(request, name, version): source = get_object_or_404(Source, name=name) if not source.buildinfos.filter(version=version).exists(): raise Http404() qs = source.buildinfos.filter( version=version, ).order_by( 'architecture__name', ).prefetch_related( 'submissions__key', ) <|code_end|> , predict the immediate next line with the help of imports: from django.conf import settings from django.http import Http404, JsonResponse from django.shortcuts import render, get_object_or_404 from bidb.utils.itertools import groupby from bidb.utils.paginator import AutoPaginator from bidb.buildinfo.buildinfo_submissions.models import Submission from .models import Binary, Source and context (classes, functions, sometimes code) from other files: # Path: bidb/utils/itertools.py # def groupby(iterable, keyfunc, sortfunc=lambda x: x): # return [ # (x, list(sorted(y, key=sortfunc))) # for x, y in itertools.groupby(iterable, keyfunc) # ] # # Path: bidb/utils/paginator.py # class AutoPaginator(Paginator): # def __init__(self, request, *args, **kwargs): # self.request = request # self.default = kwargs.pop('default', 1) # super(AutoPaginator, self).__init__(*args, **kwargs) # # def current_page(self): # try: # page = int(self.request.GET['page']) # # if page <= 0: # raise ValueError() # except (ValueError, KeyError): # page = self.default # # try: # return self.page(page) # except EmptyPage: # return Page([], page, self) # # def validate_number(self, number): # """ # Our version ignores EmptyPage. # """ # try: # return max(1, int(number)) # except (TypeError, ValueError): # return 1 # # Path: bidb/buildinfo/buildinfo_submissions/models.py # class Submission(models.Model): # buildinfo = models.ForeignKey( # 'buildinfo.Buildinfo', # related_name='submissions', # ) # # slug = models.CharField( # unique=True, # default=functools.partial( # get_random_string, 8, '3479abcdefghijkmnopqrstuvwxyz', # ), # max_length=8, # ) # # key = models.ForeignKey('keys.Key', related_name='submissions') # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('created',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d buildinfo=%r" % ( # self.pk, # self.buildinfo, # ) # # @models.permalink # def get_absolute_url(self): # return 'buildinfo:submissions:view', ( # self.buildinfo.sha1, # self.buildinfo.get_filename(), # self.slug, # ) # # def get_storage_name(self): # return 'buildinfo_submissions.Submission/{}/{}/{}'.format( # self.slug[:2], # self.slug[2:4], # self.slug, # ) # # Path: bidb/packages/models.py # class Binary(models.Model): # name = models.CharField(max_length=200, unique=True) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) # # @models.permalink # def get_absolute_url(self): # return 'packages:binary', (self.name,) # # class Source(models.Model): # name = models.CharField(max_length=200, unique=True) # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) # # @models.permalink # def get_absolute_url(self): # return 'packages:source', (self.name,) . Output only the next line.
buildinfos_by_arch = groupby(
Using the snippet: <|code_start|> reproducible = False reproducible_by_arch[x] = reproducible return render(request, 'packages/source_version.html', { 'source': source, 'version': version, 'buildinfos_by_arch': buildinfos_by_arch, 'reproducible_by_arch': reproducible_by_arch, }) def binary(request, name): binary = get_object_or_404(Binary, name=name) versions = binary.generated_binaries.values_list( 'buildinfo__version', flat=True, ).order_by('buildinfo__version').distinct() return render(request, 'packages/binary.html', { 'binary': binary, 'versions': versions, }) def api_source_version_architecture(request, name, version, architecture): source = get_object_or_404(Source, name=name) if not source.buildinfos.filter(version=version).exists(): raise Http404() <|code_end|> , determine the next line of code. You have imports: from django.conf import settings from django.http import Http404, JsonResponse from django.shortcuts import render, get_object_or_404 from bidb.utils.itertools import groupby from bidb.utils.paginator import AutoPaginator from bidb.buildinfo.buildinfo_submissions.models import Submission from .models import Binary, Source and context (class names, function names, or code) available: # Path: bidb/utils/itertools.py # def groupby(iterable, keyfunc, sortfunc=lambda x: x): # return [ # (x, list(sorted(y, key=sortfunc))) # for x, y in itertools.groupby(iterable, keyfunc) # ] # # Path: bidb/utils/paginator.py # class AutoPaginator(Paginator): # def __init__(self, request, *args, **kwargs): # self.request = request # self.default = kwargs.pop('default', 1) # super(AutoPaginator, self).__init__(*args, **kwargs) # # def current_page(self): # try: # page = int(self.request.GET['page']) # # if page <= 0: # raise ValueError() # except (ValueError, KeyError): # page = self.default # # try: # return self.page(page) # except EmptyPage: # return Page([], page, self) # # def validate_number(self, number): # """ # Our version ignores EmptyPage. # """ # try: # return max(1, int(number)) # except (TypeError, ValueError): # return 1 # # Path: bidb/buildinfo/buildinfo_submissions/models.py # class Submission(models.Model): # buildinfo = models.ForeignKey( # 'buildinfo.Buildinfo', # related_name='submissions', # ) # # slug = models.CharField( # unique=True, # default=functools.partial( # get_random_string, 8, '3479abcdefghijkmnopqrstuvwxyz', # ), # max_length=8, # ) # # key = models.ForeignKey('keys.Key', related_name='submissions') # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('created',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d buildinfo=%r" % ( # self.pk, # self.buildinfo, # ) # # @models.permalink # def get_absolute_url(self): # return 'buildinfo:submissions:view', ( # self.buildinfo.sha1, # self.buildinfo.get_filename(), # self.slug, # ) # # def get_storage_name(self): # return 'buildinfo_submissions.Submission/{}/{}/{}'.format( # self.slug[:2], # self.slug[2:4], # self.slug, # ) # # Path: bidb/packages/models.py # class Binary(models.Model): # name = models.CharField(max_length=200, unique=True) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) # # @models.permalink # def get_absolute_url(self): # return 'packages:binary', (self.name,) # # class Source(models.Model): # name = models.CharField(max_length=200, unique=True) # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) # # @models.permalink # def get_absolute_url(self): # return 'packages:source', (self.name,) . Output only the next line.
qs = Submission.objects.filter(
Continue the code snippet: <|code_start|> def sources(request): page = AutoPaginator(request, Source.objects.all(), 250).current_page() return render(request, 'packages/sources.html', { 'page': page, }) def binaries(request): <|code_end|> . Use current file imports: from django.conf import settings from django.http import Http404, JsonResponse from django.shortcuts import render, get_object_or_404 from bidb.utils.itertools import groupby from bidb.utils.paginator import AutoPaginator from bidb.buildinfo.buildinfo_submissions.models import Submission from .models import Binary, Source and context (classes, functions, or code) from other files: # Path: bidb/utils/itertools.py # def groupby(iterable, keyfunc, sortfunc=lambda x: x): # return [ # (x, list(sorted(y, key=sortfunc))) # for x, y in itertools.groupby(iterable, keyfunc) # ] # # Path: bidb/utils/paginator.py # class AutoPaginator(Paginator): # def __init__(self, request, *args, **kwargs): # self.request = request # self.default = kwargs.pop('default', 1) # super(AutoPaginator, self).__init__(*args, **kwargs) # # def current_page(self): # try: # page = int(self.request.GET['page']) # # if page <= 0: # raise ValueError() # except (ValueError, KeyError): # page = self.default # # try: # return self.page(page) # except EmptyPage: # return Page([], page, self) # # def validate_number(self, number): # """ # Our version ignores EmptyPage. # """ # try: # return max(1, int(number)) # except (TypeError, ValueError): # return 1 # # Path: bidb/buildinfo/buildinfo_submissions/models.py # class Submission(models.Model): # buildinfo = models.ForeignKey( # 'buildinfo.Buildinfo', # related_name='submissions', # ) # # slug = models.CharField( # unique=True, # default=functools.partial( # get_random_string, 8, '3479abcdefghijkmnopqrstuvwxyz', # ), # max_length=8, # ) # # key = models.ForeignKey('keys.Key', related_name='submissions') # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('created',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d buildinfo=%r" % ( # self.pk, # self.buildinfo, # ) # # @models.permalink # def get_absolute_url(self): # return 'buildinfo:submissions:view', ( # self.buildinfo.sha1, # self.buildinfo.get_filename(), # self.slug, # ) # # def get_storage_name(self): # return 'buildinfo_submissions.Submission/{}/{}/{}'.format( # self.slug[:2], # self.slug[2:4], # self.slug, # ) # # Path: bidb/packages/models.py # class Binary(models.Model): # name = models.CharField(max_length=200, unique=True) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) # # @models.permalink # def get_absolute_url(self): # return 'packages:binary', (self.name,) # # class Source(models.Model): # name = models.CharField(max_length=200, unique=True) # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) # # @models.permalink # def get_absolute_url(self): # return 'packages:source', (self.name,) . Output only the next line.
page = AutoPaginator(request, Binary.objects.all(), 250).current_page()
Predict the next line after this snippet: <|code_start|> @csrf_exempt @require_http_methods(['PUT']) def submit(request): try: <|code_end|> using the current file's imports: from django.conf import settings from django.http import HttpResponse, HttpResponseBadRequest from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_http_methods from .utils import parse_submission, InvalidSubmission and any relevant context from other files: # Path: bidb/api/utils.py # @transaction.atomic # def parse_submission(request): # raw_text = request.read() # # try: # data = deb822.Deb822(raw_text) # except TypeError: # raise InvalidSubmission("Could not parse RFC-822 format data.") # # raw_text_gpg_stripped = data.dump() # # ## Parse GPG info ######################################################### # # uid = None # data.raw_text = raw_text # gpg_info = data.get_gpg_info() # # for x in ('VALIDSIG', 'NO_PUBKEY'): # try: # uid = gpg_info[x][0] # break # except (KeyError, IndexError): # pass # # if uid is None: # raise InvalidSubmission("Could not determine GPG uid") # # ## Check whether .buildinfo already exists ################################ # # def create_submission(buildinfo): # submission = buildinfo.submissions.create( # key=Key.objects.get_or_create(uid=uid)[0], # ) # # default_storage.save( # submission.get_storage_name(), # ContentFile(raw_text), # ) # # return submission # # ## Parse new .buildinfo ################################################### # # def get_or_create(model, field): # try: # return model.objects.get_or_create(name=data[field])[0] # except KeyError: # raise InvalidSubmission("Missing required field: {}".format(field)) # # if data.get('Format') not in SUPPORTED_FORMATS: # raise InvalidSubmission( # "Only {} 'Format:' versions are supported".format( # ', '.join(sorted(SUPPORTED_FORMATS)), # ) # ) # # sha1 = hashlib.sha1(raw_text_gpg_stripped.encode('utf-8')).hexdigest() # # try: # with transaction.atomic(): # buildinfo = Buildinfo.objects.create( # sha1=sha1, # # source=get_or_create(Source, 'Source'), # architecture=get_or_create(Architecture, 'Architecture'), # version=data['version'], # # build_path=data.get('Build-Path', ''), # build_date=parse(data.get('Build-Date', '')), # build_origin=get_or_create(Origin, 'Build-Origin'), # build_architecture=get_or_create(Architecture, 'Build-Architecture'), # # environment=data.get('Environment', ''), # ) # except IntegrityError: # # Already exists; just attach a new Submission instance # return create_submission(Buildinfo.objects.get(sha1=sha1)), False # # default_storage.save( # buildinfo.get_storage_name(), # ContentFile(raw_text_gpg_stripped), # ) # # ## Parse binaries ######################################################### # # try: # binary_names = set(data['Binary'].split(' ')) # except KeyError: # raise InvalidSubmission("Missing 'Binary' field") # # if not binary_names: # raise InvalidSubmission("Invalid 'Binary' field") # # binaries = {} # for x in binary_names: # # Save instances for lookup later # binaries[x] = buildinfo.binaries.create( # binary=Binary.objects.get_or_create(name=x)[0], # ) # # ## Parse checksums ######################################################## # # hashes = ('Md5', 'Sha1', 'Sha256') # # checksums = {} # for x in hashes: # for y in data['Checksums-%s' % x].strip().splitlines(): # checksum, size, filename = y.strip().split() # # # Check size # try: # size = int(size) # if size < 0: # raise ValueError() # except ValueError: # raise InvalidSubmission( # "Invalid size for {}: {}".format(filename, size), # ) # # checksums.setdefault(filename, { # 'size': size, # 'binary': None, # })['checksum_{}'.format(x.lower())] = checksum # # existing = checksums[filename]['size'] # if size != existing: # raise InvalidSubmission("Mismatched file size in " # "Checksums-{}: {} != {}".format(x, existing, size)) # # ## Create Checksum instances ############################################## # # for k, v in sorted(checksums.items()): # # Match with Binary instances if possible # m = re_binary.match(k) # if m is not None: # v['binary'] = binaries.get(m.group('name')) # # buildinfo.checksums.create(filename=k, **v) # # ## Validate Installed-Build-Depends ####################################### # # for x in data['Installed-Build-Depends'].strip().splitlines(): # m = re_installed_build_depends.match(x.strip()) # # if m is None: # raise InvalidSubmission( # "Invalid entry in Installed-Build-Depends: {}".format(x), # ) # # return create_submission(buildinfo), True # # class InvalidSubmission(Exception): # pass . Output only the next line.
submission, created = parse_submission(request)
Predict the next line for this snippet: <|code_start|> @csrf_exempt @require_http_methods(['PUT']) def submit(request): try: submission, created = parse_submission(request) <|code_end|> with the help of current file imports: from django.conf import settings from django.http import HttpResponse, HttpResponseBadRequest from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_http_methods from .utils import parse_submission, InvalidSubmission and context from other files: # Path: bidb/api/utils.py # @transaction.atomic # def parse_submission(request): # raw_text = request.read() # # try: # data = deb822.Deb822(raw_text) # except TypeError: # raise InvalidSubmission("Could not parse RFC-822 format data.") # # raw_text_gpg_stripped = data.dump() # # ## Parse GPG info ######################################################### # # uid = None # data.raw_text = raw_text # gpg_info = data.get_gpg_info() # # for x in ('VALIDSIG', 'NO_PUBKEY'): # try: # uid = gpg_info[x][0] # break # except (KeyError, IndexError): # pass # # if uid is None: # raise InvalidSubmission("Could not determine GPG uid") # # ## Check whether .buildinfo already exists ################################ # # def create_submission(buildinfo): # submission = buildinfo.submissions.create( # key=Key.objects.get_or_create(uid=uid)[0], # ) # # default_storage.save( # submission.get_storage_name(), # ContentFile(raw_text), # ) # # return submission # # ## Parse new .buildinfo ################################################### # # def get_or_create(model, field): # try: # return model.objects.get_or_create(name=data[field])[0] # except KeyError: # raise InvalidSubmission("Missing required field: {}".format(field)) # # if data.get('Format') not in SUPPORTED_FORMATS: # raise InvalidSubmission( # "Only {} 'Format:' versions are supported".format( # ', '.join(sorted(SUPPORTED_FORMATS)), # ) # ) # # sha1 = hashlib.sha1(raw_text_gpg_stripped.encode('utf-8')).hexdigest() # # try: # with transaction.atomic(): # buildinfo = Buildinfo.objects.create( # sha1=sha1, # # source=get_or_create(Source, 'Source'), # architecture=get_or_create(Architecture, 'Architecture'), # version=data['version'], # # build_path=data.get('Build-Path', ''), # build_date=parse(data.get('Build-Date', '')), # build_origin=get_or_create(Origin, 'Build-Origin'), # build_architecture=get_or_create(Architecture, 'Build-Architecture'), # # environment=data.get('Environment', ''), # ) # except IntegrityError: # # Already exists; just attach a new Submission instance # return create_submission(Buildinfo.objects.get(sha1=sha1)), False # # default_storage.save( # buildinfo.get_storage_name(), # ContentFile(raw_text_gpg_stripped), # ) # # ## Parse binaries ######################################################### # # try: # binary_names = set(data['Binary'].split(' ')) # except KeyError: # raise InvalidSubmission("Missing 'Binary' field") # # if not binary_names: # raise InvalidSubmission("Invalid 'Binary' field") # # binaries = {} # for x in binary_names: # # Save instances for lookup later # binaries[x] = buildinfo.binaries.create( # binary=Binary.objects.get_or_create(name=x)[0], # ) # # ## Parse checksums ######################################################## # # hashes = ('Md5', 'Sha1', 'Sha256') # # checksums = {} # for x in hashes: # for y in data['Checksums-%s' % x].strip().splitlines(): # checksum, size, filename = y.strip().split() # # # Check size # try: # size = int(size) # if size < 0: # raise ValueError() # except ValueError: # raise InvalidSubmission( # "Invalid size for {}: {}".format(filename, size), # ) # # checksums.setdefault(filename, { # 'size': size, # 'binary': None, # })['checksum_{}'.format(x.lower())] = checksum # # existing = checksums[filename]['size'] # if size != existing: # raise InvalidSubmission("Mismatched file size in " # "Checksums-{}: {} != {}".format(x, existing, size)) # # ## Create Checksum instances ############################################## # # for k, v in sorted(checksums.items()): # # Match with Binary instances if possible # m = re_binary.match(k) # if m is not None: # v['binary'] = binaries.get(m.group('name')) # # buildinfo.checksums.create(filename=k, **v) # # ## Validate Installed-Build-Depends ####################################### # # for x in data['Installed-Build-Depends'].strip().splitlines(): # m = re_installed_build_depends.match(x.strip()) # # if m is None: # raise InvalidSubmission( # "Invalid entry in Installed-Build-Depends: {}".format(x), # ) # # return create_submission(buildinfo), True # # class InvalidSubmission(Exception): # pass , which may contain function names, class names, or code. Output only the next line.
except InvalidSubmission as exc:
Using the snippet: <|code_start|>def parse_submission(request): raw_text = request.read() try: data = deb822.Deb822(raw_text) except TypeError: raise InvalidSubmission("Could not parse RFC-822 format data.") raw_text_gpg_stripped = data.dump() ## Parse GPG info ######################################################### uid = None data.raw_text = raw_text gpg_info = data.get_gpg_info() for x in ('VALIDSIG', 'NO_PUBKEY'): try: uid = gpg_info[x][0] break except (KeyError, IndexError): pass if uid is None: raise InvalidSubmission("Could not determine GPG uid") ## Check whether .buildinfo already exists ################################ def create_submission(buildinfo): submission = buildinfo.submissions.create( <|code_end|> , determine the next line of code. You have imports: import re import hashlib from debian import deb822 from dateutil.parser import parse from django.db import transaction, IntegrityError from django.core.files.base import ContentFile from django.core.files.storage import default_storage from bidb.keys.models import Key from bidb.packages.models import Source, Architecture, Binary from bidb.buildinfo.models import Buildinfo, Origin and context (class names, function names, or code) available: # Path: bidb/keys/models.py # class Key(models.Model): # uid = models.CharField(max_length=255, unique=True) # # name = models.TextField() # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('-created',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d uid=%r name=%r" % ( # self.pk, # self.uid, # self.name, # ) # # def save(self, *args, **kwargs): # created = not self.pk # # super(Key, self).save(*args, **kwargs) # # if created: # from .tasks import update_or_create_key # # transaction.on_commit(lambda: update_or_create_key.delay(self.uid)) # # Path: bidb/packages/models.py # class Source(models.Model): # name = models.CharField(max_length=200, unique=True) # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) # # @models.permalink # def get_absolute_url(self): # return 'packages:source', (self.name,) # # class Architecture(models.Model): # name = models.CharField(max_length=200, unique=True) # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) # # class Binary(models.Model): # name = models.CharField(max_length=200, unique=True) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) # # @models.permalink # def get_absolute_url(self): # return 'packages:binary', (self.name,) # # Path: bidb/buildinfo/models.py # class Buildinfo(models.Model): # sha1 = models.CharField(max_length=40, unique=True) # # source = models.ForeignKey( # 'packages.Source', # related_name='buildinfos', # ) # # architecture = models.ForeignKey( # 'packages.Architecture', # related_name='buildinfos', # ) # version = models.CharField(max_length=200) # # build_path = models.CharField(max_length=512) # build_date = models.DateTimeField(null=True) # build_origin = models.ForeignKey('Origin', null=True) # build_architecture = models.ForeignKey( # 'packages.Architecture', # related_name='buildinfos_build', # ) # # environment = models.TextField() # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('-created',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d source=%r version=%r" % ( # self.pk, # self.source, # self.version, # ) # # @models.permalink # def get_absolute_url(self): # return 'buildinfo:view', (self.sha1, self.get_filename()) # # @models.permalink # def get_absolute_raw_url(self): # return 'buildinfo:raw-text', (self.sha1, self.get_filename()) # # def get_filename(self): # return '{}_{}_{}'.format( # self.source.name, # self.version, # self.architecture.name.split(' ')[0], # ) # # def get_storage_name(self): # return 'buildinfo.Buildinfo/{}/{}/{}'.format( # self.sha1[:2], # self.sha1[2:4], # self.sha1, # ) # # class Origin(models.Model): # name = models.CharField(max_length=255) # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) . Output only the next line.
key=Key.objects.get_or_create(uid=uid)[0],
Given the following code snippet before the placeholder: <|code_start|> default_storage.save( submission.get_storage_name(), ContentFile(raw_text), ) return submission ## Parse new .buildinfo ################################################### def get_or_create(model, field): try: return model.objects.get_or_create(name=data[field])[0] except KeyError: raise InvalidSubmission("Missing required field: {}".format(field)) if data.get('Format') not in SUPPORTED_FORMATS: raise InvalidSubmission( "Only {} 'Format:' versions are supported".format( ', '.join(sorted(SUPPORTED_FORMATS)), ) ) sha1 = hashlib.sha1(raw_text_gpg_stripped.encode('utf-8')).hexdigest() try: with transaction.atomic(): buildinfo = Buildinfo.objects.create( sha1=sha1, <|code_end|> , predict the next line using imports from the current file: import re import hashlib from debian import deb822 from dateutil.parser import parse from django.db import transaction, IntegrityError from django.core.files.base import ContentFile from django.core.files.storage import default_storage from bidb.keys.models import Key from bidb.packages.models import Source, Architecture, Binary from bidb.buildinfo.models import Buildinfo, Origin and context including class names, function names, and sometimes code from other files: # Path: bidb/keys/models.py # class Key(models.Model): # uid = models.CharField(max_length=255, unique=True) # # name = models.TextField() # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('-created',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d uid=%r name=%r" % ( # self.pk, # self.uid, # self.name, # ) # # def save(self, *args, **kwargs): # created = not self.pk # # super(Key, self).save(*args, **kwargs) # # if created: # from .tasks import update_or_create_key # # transaction.on_commit(lambda: update_or_create_key.delay(self.uid)) # # Path: bidb/packages/models.py # class Source(models.Model): # name = models.CharField(max_length=200, unique=True) # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) # # @models.permalink # def get_absolute_url(self): # return 'packages:source', (self.name,) # # class Architecture(models.Model): # name = models.CharField(max_length=200, unique=True) # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) # # class Binary(models.Model): # name = models.CharField(max_length=200, unique=True) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) # # @models.permalink # def get_absolute_url(self): # return 'packages:binary', (self.name,) # # Path: bidb/buildinfo/models.py # class Buildinfo(models.Model): # sha1 = models.CharField(max_length=40, unique=True) # # source = models.ForeignKey( # 'packages.Source', # related_name='buildinfos', # ) # # architecture = models.ForeignKey( # 'packages.Architecture', # related_name='buildinfos', # ) # version = models.CharField(max_length=200) # # build_path = models.CharField(max_length=512) # build_date = models.DateTimeField(null=True) # build_origin = models.ForeignKey('Origin', null=True) # build_architecture = models.ForeignKey( # 'packages.Architecture', # related_name='buildinfos_build', # ) # # environment = models.TextField() # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('-created',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d source=%r version=%r" % ( # self.pk, # self.source, # self.version, # ) # # @models.permalink # def get_absolute_url(self): # return 'buildinfo:view', (self.sha1, self.get_filename()) # # @models.permalink # def get_absolute_raw_url(self): # return 'buildinfo:raw-text', (self.sha1, self.get_filename()) # # def get_filename(self): # return '{}_{}_{}'.format( # self.source.name, # self.version, # self.architecture.name.split(' ')[0], # ) # # def get_storage_name(self): # return 'buildinfo.Buildinfo/{}/{}/{}'.format( # self.sha1[:2], # self.sha1[2:4], # self.sha1, # ) # # class Origin(models.Model): # name = models.CharField(max_length=255) # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) . Output only the next line.
source=get_or_create(Source, 'Source'),
Predict the next line after this snippet: <|code_start|> default_storage.save( submission.get_storage_name(), ContentFile(raw_text), ) return submission ## Parse new .buildinfo ################################################### def get_or_create(model, field): try: return model.objects.get_or_create(name=data[field])[0] except KeyError: raise InvalidSubmission("Missing required field: {}".format(field)) if data.get('Format') not in SUPPORTED_FORMATS: raise InvalidSubmission( "Only {} 'Format:' versions are supported".format( ', '.join(sorted(SUPPORTED_FORMATS)), ) ) sha1 = hashlib.sha1(raw_text_gpg_stripped.encode('utf-8')).hexdigest() try: with transaction.atomic(): buildinfo = Buildinfo.objects.create( sha1=sha1, source=get_or_create(Source, 'Source'), <|code_end|> using the current file's imports: import re import hashlib from debian import deb822 from dateutil.parser import parse from django.db import transaction, IntegrityError from django.core.files.base import ContentFile from django.core.files.storage import default_storage from bidb.keys.models import Key from bidb.packages.models import Source, Architecture, Binary from bidb.buildinfo.models import Buildinfo, Origin and any relevant context from other files: # Path: bidb/keys/models.py # class Key(models.Model): # uid = models.CharField(max_length=255, unique=True) # # name = models.TextField() # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('-created',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d uid=%r name=%r" % ( # self.pk, # self.uid, # self.name, # ) # # def save(self, *args, **kwargs): # created = not self.pk # # super(Key, self).save(*args, **kwargs) # # if created: # from .tasks import update_or_create_key # # transaction.on_commit(lambda: update_or_create_key.delay(self.uid)) # # Path: bidb/packages/models.py # class Source(models.Model): # name = models.CharField(max_length=200, unique=True) # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) # # @models.permalink # def get_absolute_url(self): # return 'packages:source', (self.name,) # # class Architecture(models.Model): # name = models.CharField(max_length=200, unique=True) # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) # # class Binary(models.Model): # name = models.CharField(max_length=200, unique=True) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) # # @models.permalink # def get_absolute_url(self): # return 'packages:binary', (self.name,) # # Path: bidb/buildinfo/models.py # class Buildinfo(models.Model): # sha1 = models.CharField(max_length=40, unique=True) # # source = models.ForeignKey( # 'packages.Source', # related_name='buildinfos', # ) # # architecture = models.ForeignKey( # 'packages.Architecture', # related_name='buildinfos', # ) # version = models.CharField(max_length=200) # # build_path = models.CharField(max_length=512) # build_date = models.DateTimeField(null=True) # build_origin = models.ForeignKey('Origin', null=True) # build_architecture = models.ForeignKey( # 'packages.Architecture', # related_name='buildinfos_build', # ) # # environment = models.TextField() # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('-created',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d source=%r version=%r" % ( # self.pk, # self.source, # self.version, # ) # # @models.permalink # def get_absolute_url(self): # return 'buildinfo:view', (self.sha1, self.get_filename()) # # @models.permalink # def get_absolute_raw_url(self): # return 'buildinfo:raw-text', (self.sha1, self.get_filename()) # # def get_filename(self): # return '{}_{}_{}'.format( # self.source.name, # self.version, # self.architecture.name.split(' ')[0], # ) # # def get_storage_name(self): # return 'buildinfo.Buildinfo/{}/{}/{}'.format( # self.sha1[:2], # self.sha1[2:4], # self.sha1, # ) # # class Origin(models.Model): # name = models.CharField(max_length=255) # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) . Output only the next line.
architecture=get_or_create(Architecture, 'Architecture'),
Predict the next line for this snippet: <|code_start|> build_path=data.get('Build-Path', ''), build_date=parse(data.get('Build-Date', '')), build_origin=get_or_create(Origin, 'Build-Origin'), build_architecture=get_or_create(Architecture, 'Build-Architecture'), environment=data.get('Environment', ''), ) except IntegrityError: # Already exists; just attach a new Submission instance return create_submission(Buildinfo.objects.get(sha1=sha1)), False default_storage.save( buildinfo.get_storage_name(), ContentFile(raw_text_gpg_stripped), ) ## Parse binaries ######################################################### try: binary_names = set(data['Binary'].split(' ')) except KeyError: raise InvalidSubmission("Missing 'Binary' field") if not binary_names: raise InvalidSubmission("Invalid 'Binary' field") binaries = {} for x in binary_names: # Save instances for lookup later binaries[x] = buildinfo.binaries.create( <|code_end|> with the help of current file imports: import re import hashlib from debian import deb822 from dateutil.parser import parse from django.db import transaction, IntegrityError from django.core.files.base import ContentFile from django.core.files.storage import default_storage from bidb.keys.models import Key from bidb.packages.models import Source, Architecture, Binary from bidb.buildinfo.models import Buildinfo, Origin and context from other files: # Path: bidb/keys/models.py # class Key(models.Model): # uid = models.CharField(max_length=255, unique=True) # # name = models.TextField() # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('-created',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d uid=%r name=%r" % ( # self.pk, # self.uid, # self.name, # ) # # def save(self, *args, **kwargs): # created = not self.pk # # super(Key, self).save(*args, **kwargs) # # if created: # from .tasks import update_or_create_key # # transaction.on_commit(lambda: update_or_create_key.delay(self.uid)) # # Path: bidb/packages/models.py # class Source(models.Model): # name = models.CharField(max_length=200, unique=True) # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) # # @models.permalink # def get_absolute_url(self): # return 'packages:source', (self.name,) # # class Architecture(models.Model): # name = models.CharField(max_length=200, unique=True) # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) # # class Binary(models.Model): # name = models.CharField(max_length=200, unique=True) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) # # @models.permalink # def get_absolute_url(self): # return 'packages:binary', (self.name,) # # Path: bidb/buildinfo/models.py # class Buildinfo(models.Model): # sha1 = models.CharField(max_length=40, unique=True) # # source = models.ForeignKey( # 'packages.Source', # related_name='buildinfos', # ) # # architecture = models.ForeignKey( # 'packages.Architecture', # related_name='buildinfos', # ) # version = models.CharField(max_length=200) # # build_path = models.CharField(max_length=512) # build_date = models.DateTimeField(null=True) # build_origin = models.ForeignKey('Origin', null=True) # build_architecture = models.ForeignKey( # 'packages.Architecture', # related_name='buildinfos_build', # ) # # environment = models.TextField() # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('-created',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d source=%r version=%r" % ( # self.pk, # self.source, # self.version, # ) # # @models.permalink # def get_absolute_url(self): # return 'buildinfo:view', (self.sha1, self.get_filename()) # # @models.permalink # def get_absolute_raw_url(self): # return 'buildinfo:raw-text', (self.sha1, self.get_filename()) # # def get_filename(self): # return '{}_{}_{}'.format( # self.source.name, # self.version, # self.architecture.name.split(' ')[0], # ) # # def get_storage_name(self): # return 'buildinfo.Buildinfo/{}/{}/{}'.format( # self.sha1[:2], # self.sha1[2:4], # self.sha1, # ) # # class Origin(models.Model): # name = models.CharField(max_length=255) # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) , which may contain function names, class names, or code. Output only the next line.
binary=Binary.objects.get_or_create(name=x)[0],
Based on the snippet: <|code_start|> submission = buildinfo.submissions.create( key=Key.objects.get_or_create(uid=uid)[0], ) default_storage.save( submission.get_storage_name(), ContentFile(raw_text), ) return submission ## Parse new .buildinfo ################################################### def get_or_create(model, field): try: return model.objects.get_or_create(name=data[field])[0] except KeyError: raise InvalidSubmission("Missing required field: {}".format(field)) if data.get('Format') not in SUPPORTED_FORMATS: raise InvalidSubmission( "Only {} 'Format:' versions are supported".format( ', '.join(sorted(SUPPORTED_FORMATS)), ) ) sha1 = hashlib.sha1(raw_text_gpg_stripped.encode('utf-8')).hexdigest() try: with transaction.atomic(): <|code_end|> , predict the immediate next line with the help of imports: import re import hashlib from debian import deb822 from dateutil.parser import parse from django.db import transaction, IntegrityError from django.core.files.base import ContentFile from django.core.files.storage import default_storage from bidb.keys.models import Key from bidb.packages.models import Source, Architecture, Binary from bidb.buildinfo.models import Buildinfo, Origin and context (classes, functions, sometimes code) from other files: # Path: bidb/keys/models.py # class Key(models.Model): # uid = models.CharField(max_length=255, unique=True) # # name = models.TextField() # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('-created',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d uid=%r name=%r" % ( # self.pk, # self.uid, # self.name, # ) # # def save(self, *args, **kwargs): # created = not self.pk # # super(Key, self).save(*args, **kwargs) # # if created: # from .tasks import update_or_create_key # # transaction.on_commit(lambda: update_or_create_key.delay(self.uid)) # # Path: bidb/packages/models.py # class Source(models.Model): # name = models.CharField(max_length=200, unique=True) # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) # # @models.permalink # def get_absolute_url(self): # return 'packages:source', (self.name,) # # class Architecture(models.Model): # name = models.CharField(max_length=200, unique=True) # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) # # class Binary(models.Model): # name = models.CharField(max_length=200, unique=True) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) # # @models.permalink # def get_absolute_url(self): # return 'packages:binary', (self.name,) # # Path: bidb/buildinfo/models.py # class Buildinfo(models.Model): # sha1 = models.CharField(max_length=40, unique=True) # # source = models.ForeignKey( # 'packages.Source', # related_name='buildinfos', # ) # # architecture = models.ForeignKey( # 'packages.Architecture', # related_name='buildinfos', # ) # version = models.CharField(max_length=200) # # build_path = models.CharField(max_length=512) # build_date = models.DateTimeField(null=True) # build_origin = models.ForeignKey('Origin', null=True) # build_architecture = models.ForeignKey( # 'packages.Architecture', # related_name='buildinfos_build', # ) # # environment = models.TextField() # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('-created',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d source=%r version=%r" % ( # self.pk, # self.source, # self.version, # ) # # @models.permalink # def get_absolute_url(self): # return 'buildinfo:view', (self.sha1, self.get_filename()) # # @models.permalink # def get_absolute_raw_url(self): # return 'buildinfo:raw-text', (self.sha1, self.get_filename()) # # def get_filename(self): # return '{}_{}_{}'.format( # self.source.name, # self.version, # self.architecture.name.split(' ')[0], # ) # # def get_storage_name(self): # return 'buildinfo.Buildinfo/{}/{}/{}'.format( # self.sha1[:2], # self.sha1[2:4], # self.sha1, # ) # # class Origin(models.Model): # name = models.CharField(max_length=255) # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) . Output only the next line.
buildinfo = Buildinfo.objects.create(
Given the following code snippet before the placeholder: <|code_start|> return submission ## Parse new .buildinfo ################################################### def get_or_create(model, field): try: return model.objects.get_or_create(name=data[field])[0] except KeyError: raise InvalidSubmission("Missing required field: {}".format(field)) if data.get('Format') not in SUPPORTED_FORMATS: raise InvalidSubmission( "Only {} 'Format:' versions are supported".format( ', '.join(sorted(SUPPORTED_FORMATS)), ) ) sha1 = hashlib.sha1(raw_text_gpg_stripped.encode('utf-8')).hexdigest() try: with transaction.atomic(): buildinfo = Buildinfo.objects.create( sha1=sha1, source=get_or_create(Source, 'Source'), architecture=get_or_create(Architecture, 'Architecture'), version=data['version'], build_path=data.get('Build-Path', ''), build_date=parse(data.get('Build-Date', '')), <|code_end|> , predict the next line using imports from the current file: import re import hashlib from debian import deb822 from dateutil.parser import parse from django.db import transaction, IntegrityError from django.core.files.base import ContentFile from django.core.files.storage import default_storage from bidb.keys.models import Key from bidb.packages.models import Source, Architecture, Binary from bidb.buildinfo.models import Buildinfo, Origin and context including class names, function names, and sometimes code from other files: # Path: bidb/keys/models.py # class Key(models.Model): # uid = models.CharField(max_length=255, unique=True) # # name = models.TextField() # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('-created',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d uid=%r name=%r" % ( # self.pk, # self.uid, # self.name, # ) # # def save(self, *args, **kwargs): # created = not self.pk # # super(Key, self).save(*args, **kwargs) # # if created: # from .tasks import update_or_create_key # # transaction.on_commit(lambda: update_or_create_key.delay(self.uid)) # # Path: bidb/packages/models.py # class Source(models.Model): # name = models.CharField(max_length=200, unique=True) # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) # # @models.permalink # def get_absolute_url(self): # return 'packages:source', (self.name,) # # class Architecture(models.Model): # name = models.CharField(max_length=200, unique=True) # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) # # class Binary(models.Model): # name = models.CharField(max_length=200, unique=True) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) # # @models.permalink # def get_absolute_url(self): # return 'packages:binary', (self.name,) # # Path: bidb/buildinfo/models.py # class Buildinfo(models.Model): # sha1 = models.CharField(max_length=40, unique=True) # # source = models.ForeignKey( # 'packages.Source', # related_name='buildinfos', # ) # # architecture = models.ForeignKey( # 'packages.Architecture', # related_name='buildinfos', # ) # version = models.CharField(max_length=200) # # build_path = models.CharField(max_length=512) # build_date = models.DateTimeField(null=True) # build_origin = models.ForeignKey('Origin', null=True) # build_architecture = models.ForeignKey( # 'packages.Architecture', # related_name='buildinfos_build', # ) # # environment = models.TextField() # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('-created',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d source=%r version=%r" % ( # self.pk, # self.source, # self.version, # ) # # @models.permalink # def get_absolute_url(self): # return 'buildinfo:view', (self.sha1, self.get_filename()) # # @models.permalink # def get_absolute_raw_url(self): # return 'buildinfo:raw-text', (self.sha1, self.get_filename()) # # def get_filename(self): # return '{}_{}_{}'.format( # self.source.name, # self.version, # self.architecture.name.split(' ')[0], # ) # # def get_storage_name(self): # return 'buildinfo.Buildinfo/{}/{}/{}'.format( # self.sha1[:2], # self.sha1[2:4], # self.sha1, # ) # # class Origin(models.Model): # name = models.CharField(max_length=255) # # created = models.DateTimeField(default=datetime.datetime.utcnow) # # class Meta: # ordering = ('name',) # get_latest_by = 'created' # # def __unicode__(self): # return u"pk=%d name=%r" % ( # self.pk, # self.name, # ) . Output only the next line.
build_origin=get_or_create(Origin, 'Build-Origin'),
Continue the code snippet: <|code_start|> #from gogogo.views.db import reverse as db_reverse # Shorter cache time for db object _default_cache_time = 300 def list(request): """ List all agency """ lang = MLStringProperty.get_current_lang(request) cache_key = "gogogo_db_agency_list_%d" % lang cache = memcache.get(cache_key) if cache == None: query = Agency.all(keys_only=True) result = [] for key in query: <|code_end|> . Use current file imports: from django.http import HttpResponse from django.http import Http404 from django.template import Context, loader , RequestContext from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django import forms from django.forms import ModelForm from ragendja.auth.decorators import staff_only from ragendja.template import render_to_response from gogogo.models import * from django.core.urlresolvers import reverse from gogogo.models.cache import getCachedEntityOr404 from google.appengine.api import memcache and context (classes, functions, or code) from other files: # Path: gogogo/models/cache.py # def getCachedEntityOr404(model = None,key=None,key_name=None , id = None , id_or_name = None): # """ # Get cached entity object generated by createEntity() # """ # # if id_or_name: # try: # id = int(id_or_name) # except ValueError: # key_name = id_or_name # # cache_key = getCacheEntityKey(model = model ,key=key , key_name = key_name, id = id) # # entity = memcache.get(cache_key) # # if entity == None: # object = getCachedObjectOr404(model, key=key,key_name=key_name, id = id) # entity = createEntity(object) # # if not memcache.add(cache_key, entity, _default_cache_time): # logging.error("Memcache set %s failed." % cache_key) # # return entity . Output only the next line.
entity = getCachedEntityOr404(Agency,key = key)
Given the following code snippet before the placeholder: <|code_start|> #from gogogo.views.db import reverse as db_reverse def search(request): """ Route searching """ error = None agency = None if "agency" in request.GET: agency_id = request.GET['agency'] agency = db.Key.from_path(Agency.kind(),agency_id) if "keyword" not in request.GET: return render_to_response( request, 'gogogo/route/search.html' ,{ 'page_title': _("Route searching"), 'result' : [], 'error' : _("Error! No keyword provided!") }) keyword = request.GET['keyword'] keyword = keyword.lower() <|code_end|> , predict the next line using imports from the current file: from django.http import HttpResponse from django.http import Http404 from django.template import Context, loader , RequestContext from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django import forms from django.forms import ModelForm from ragendja.auth.decorators import staff_only from ragendja.template import render_to_response from gogogo.models import * from ragendja.dbutils import get_object_or_404 from django.core.urlresolvers import reverse from gogogo.models.loaders import ListLoader import cgi import logging and context including class names, function names, and sometimes code from other files: # Path: gogogo/models/loaders.py # class ListLoader: # """ # Load all entity of a model from memcache or bigtable # """ # # cache_key_prefix = "gogogo_list_loader_" # # def __init__(self,model): # self.model = model # self.data = None # # def get_cache_key(self,num): # return "%s_%s_%d" % (ListLoader.cache_key_prefix , self.model.kind() , num) # # def get_info_cache_key(self): # return "%s_info_%s" % (ListLoader.cache_key_prefix , self.model.kind() ) # # def load(self,batch_size=1000): # if self.data != None: #already loaded # return # # n = 0 # batch = self.load_batch(n,batch_size) # # while len(batch) == batch_size: # n+=1 # batch += self.load_batch(n , batch_size , batch[-1].key() ) # # self.data = batch # # memcache.add(self.get_info_cache_key(), len(self.data) , _default_cache_time * 2) # # return self.data # # def load_batch(self,num,limit = 1000,key = None): # cache_key = self.get_cache_key(num) # cache = memcache.get(cache_key) # if cache == None: # if key: # entities = self.model.all().filter('__key__ >',key).fetch(limit) # else: # entities = self.model.all().fetch(limit) # # cache = [entity for entity in entities] # memcache.set(cache_key, cache, _default_cache_time) # # ret = cache # return ret # # def get_data(self): # return self.data # # def remove_cache(self,limit = 1000): # count = memcache.get(self.get_info_cache_key()) # if count == None: # count = 1 # # i = 0 # while count >0: # cache_key = self.get_cache_key(i) # memcache.delete(cache_key) # count -= limit . Output only the next line.
route_list_loader = ListLoader(Route)
Given snippet: <|code_start|> 'fields': ('name', 'url', 'type', 'phone', 'icon', 'priority', 'no_service', 'free_transfer', 'show_map_in_transit_page' ) }), ) form = AgencyBasicForm list_display = ('Agency_ID','Agency_Name','url') search_fields = ('name',) def Agency_Name(self,obj): return u' | '.join(obj.name) def Agency_ID(self,obj): #return obj.aid return obj.key().id_or_name() def save_model(self,request,obj,form,change): if change: return admin.ModelAdmin.save_model(self,request,obj,form,change) else: <|code_end|> , continue by predicting the next line. Consider current file imports: from django.contrib import admin from django import forms from ragendja.forms import * from gogogo.models import * from gogogo.models.utils import copyModel,createEntity from gogogo.models.forms import * from gogogo.views.db.forms import next_key_name from django.conf import settings and context: # Path: gogogo/models/utils.py # def copyModel(object, **kwargs): # """ # Copy a model instance # # @param kwargs Argument passed to the model constructor funtion for new copied model # """ # model_class = db._kind_map[object.kind()] # # entity = {} # # for prop in object.properties().values(): # datastore_value = prop.get_value_for_datastore(object) # entity[prop.name] = datastore_value # # entity.update(kwargs) # # return model_class(**entity) # # def createEntity(object): # """ Create an entity from model instance object which is # suitable for data import and export. # # Operations: # - Convert all ReferenceProperty to the key_name/key # - set 'id' attribute (= id_or_name() # - set 'instance' attribute , the reference to the model instance # # @return A dict object contains the entity of the model instance. The fields are not translated , use trEntity to translate to user's locale # # """ # entity = {} # # for prop in object.properties().values(): # datastore_value = prop.get_value_for_datastore(object) # entity[prop.name] = datastore_value # # if datastore_value == None: # continue # if not datastore_value == []: # if isinstance(prop,db.ReferenceProperty): # entity[prop.name] = datastore_value.id_or_name() # elif isinstance(prop,MLStringProperty): # entity[prop.name] = u'|'.join(datastore_value) # elif isinstance(prop,KeyListProperty): # entity[prop.name] = [ key.id_or_name() for key in datastore_value ] # # #entity['key_name'] = object.key().id_or_name() # # # The client side do not know the different between id and key_name, they just # # "id" as the unique identifier of an entry # if object.is_saved(): # entity['id'] = object.key().id_or_name() # # # Going to deprecate # entity['instance'] = object # return entity # # Path: gogogo/views/db/forms.py # def next_key_name(model_class,key_name): # """ # Get the next available key # """ # if key_name == None: # return key_name # Use numeric key # # entity = model_class.get(db.Key.from_path(model_class.kind() , key_name)) # # if not entity: # return key_name # else: # count = 0 # while True: # count += 1 # new_key_name = key_name + "-" + str(count) # entity = model_class.get(db.Key.from_path(model_class.kind() , new_key_name)) # if not entity: # return new_key_name which might include code, classes, or functions. Output only the next line.
new_obj = copyModel(obj,auto_set_key_name = True )
Given the following code snippet before the placeholder: <|code_start|> #from gogogo.views.db import reverse as db_reverse _default_cache_time = 3600 def browse(request,id): """ Browse the information of a shape """ <|code_end|> , predict the next line using imports from the current file: from django.http import HttpResponse from django.http import Http404 from django.template import Context, loader , RequestContext from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django import forms from django.forms import ModelForm from ragendja.auth.decorators import staff_only from ragendja.template import render_to_response from gogogo.models import * from django.core.urlresolvers import reverse from gogogo.models.cache import getCachedObjectOr404 , getCachedEntityOr404 and context including class names, function names, and sometimes code from other files: # Path: gogogo/models/cache.py # def getCachedObjectOr404(model = None,key=None,key_name=None,id = None , id_or_name = None): # """ # Get a object from cache. If it is not existed in the cache, # it will query from database directly and save it in cache. # # If the object is not existed in the cache and database , it # will raise Http404 exception # """ # # if id_or_name: # try: # id = int(id_or_name) # except ValueError: # key_name = id_or_name # # cache_key = getCacheObjectKey(model = model , key=key , key_name = key_name,id = id) # # #print cache_key # object = memcache.get(cache_key) # # if object == None: # if key: # object = get_object_or_404(model,key) # else: # object = get_object_or_404(model,key_name=key_name, id = id) # if not memcache.add(cache_key, object, _default_cache_time): # logging.error("Memcache set %s failed." % cache_key) # # return object # # def getCachedEntityOr404(model = None,key=None,key_name=None , id = None , id_or_name = None): # """ # Get cached entity object generated by createEntity() # """ # # if id_or_name: # try: # id = int(id_or_name) # except ValueError: # key_name = id_or_name # # cache_key = getCacheEntityKey(model = model ,key=key , key_name = key_name, id = id) # # entity = memcache.get(cache_key) # # if entity == None: # object = getCachedObjectOr404(model, key=key,key_name=key_name, id = id) # entity = createEntity(object) # # if not memcache.add(cache_key, entity, _default_cache_time): # logging.error("Memcache set %s failed." % cache_key) # # return entity . Output only the next line.
entity = getCachedEntityOr404(Shape,id_or_name = id)
Given snippet: <|code_start|> count = 0 for row in query : count+=1 entity = createEntity(row) #entity['id'] = row.key().id_or_name() entity['type'] = Changelog.get_type_name(entity['type']) entity['entry_name'] = unicode(row.reference) result.append(entity) prev_offset = offset - limit if prev_offset < 0 : prev_offset = 0 return render_to_response( request, 'gogogo/db/changelog/list.html', { "result" : result, "offset" : offset + limit, "prev_offset" : prev_offset, "show_next" : count == limit, "show_prev" : offset != 0, "kind" : kind }) def browse(request,id): """ Browse a changelog """ <|code_end|> , continue by predicting the next line. Consider current file imports: from django.http import HttpResponse from django.http import Http404 from django.template import Context, loader , RequestContext from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django import forms from django.forms import ModelForm from django.utils import simplejson from ragendja.auth.decorators import staff_only from ragendja.template import render_to_response from django.core.urlresolvers import reverse from ragendja.dbutils import get_object_or_404 from gogogo.models import * from gogogo.models.cache import getCachedEntityOr404 from gogogo.models.utils import createEntity and context: # Path: gogogo/models/cache.py # def getCachedEntityOr404(model = None,key=None,key_name=None , id = None , id_or_name = None): # """ # Get cached entity object generated by createEntity() # """ # # if id_or_name: # try: # id = int(id_or_name) # except ValueError: # key_name = id_or_name # # cache_key = getCacheEntityKey(model = model ,key=key , key_name = key_name, id = id) # # entity = memcache.get(cache_key) # # if entity == None: # object = getCachedObjectOr404(model, key=key,key_name=key_name, id = id) # entity = createEntity(object) # # if not memcache.add(cache_key, entity, _default_cache_time): # logging.error("Memcache set %s failed." % cache_key) # # return entity # # Path: gogogo/models/utils.py # def createEntity(object): # """ Create an entity from model instance object which is # suitable for data import and export. # # Operations: # - Convert all ReferenceProperty to the key_name/key # - set 'id' attribute (= id_or_name() # - set 'instance' attribute , the reference to the model instance # # @return A dict object contains the entity of the model instance. The fields are not translated , use trEntity to translate to user's locale # # """ # entity = {} # # for prop in object.properties().values(): # datastore_value = prop.get_value_for_datastore(object) # entity[prop.name] = datastore_value # # if datastore_value == None: # continue # if not datastore_value == []: # if isinstance(prop,db.ReferenceProperty): # entity[prop.name] = datastore_value.id_or_name() # elif isinstance(prop,MLStringProperty): # entity[prop.name] = u'|'.join(datastore_value) # elif isinstance(prop,KeyListProperty): # entity[prop.name] = [ key.id_or_name() for key in datastore_value ] # # #entity['key_name'] = object.key().id_or_name() # # # The client side do not know the different between id and key_name, they just # # "id" as the unique identifier of an entry # if object.is_saved(): # entity['id'] = object.key().id_or_name() # # # Going to deprecate # entity['instance'] = object # return entity which might include code, classes, or functions. Output only the next line.
entity = getCachedEntityOr404(Changelog,id_or_name = id)
Next line prediction: <|code_start|> """ List changelog """ kind = None limit = 10 offset = 0 if request.method == "GET": if "limit" in request.GET: limit = int(request.GET['limit']) if "offset" in request.GET: offset = int(request.GET['offset']) if offset < 0 : offset = 0 if "kind" in request.GET: kind = request.GET['kind'] if kind is not None: gql = db.GqlQuery("SELECT * from gogogo_changelog WHERE model_kind = :1 ORDER BY commit_date DESC ",kind) else: gql = db.GqlQuery("SELECT * from gogogo_changelog ORDER BY commit_date DESC ") query = gql.fetch(limit,offset) result = [] count = 0 for row in query : count+=1 <|code_end|> . Use current file imports: (from django.http import HttpResponse from django.http import Http404 from django.template import Context, loader , RequestContext from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django import forms from django.forms import ModelForm from django.utils import simplejson from ragendja.auth.decorators import staff_only from ragendja.template import render_to_response from django.core.urlresolvers import reverse from ragendja.dbutils import get_object_or_404 from gogogo.models import * from gogogo.models.cache import getCachedEntityOr404 from gogogo.models.utils import createEntity) and context including class names, function names, or small code snippets from other files: # Path: gogogo/models/cache.py # def getCachedEntityOr404(model = None,key=None,key_name=None , id = None , id_or_name = None): # """ # Get cached entity object generated by createEntity() # """ # # if id_or_name: # try: # id = int(id_or_name) # except ValueError: # key_name = id_or_name # # cache_key = getCacheEntityKey(model = model ,key=key , key_name = key_name, id = id) # # entity = memcache.get(cache_key) # # if entity == None: # object = getCachedObjectOr404(model, key=key,key_name=key_name, id = id) # entity = createEntity(object) # # if not memcache.add(cache_key, entity, _default_cache_time): # logging.error("Memcache set %s failed." % cache_key) # # return entity # # Path: gogogo/models/utils.py # def createEntity(object): # """ Create an entity from model instance object which is # suitable for data import and export. # # Operations: # - Convert all ReferenceProperty to the key_name/key # - set 'id' attribute (= id_or_name() # - set 'instance' attribute , the reference to the model instance # # @return A dict object contains the entity of the model instance. The fields are not translated , use trEntity to translate to user's locale # # """ # entity = {} # # for prop in object.properties().values(): # datastore_value = prop.get_value_for_datastore(object) # entity[prop.name] = datastore_value # # if datastore_value == None: # continue # if not datastore_value == []: # if isinstance(prop,db.ReferenceProperty): # entity[prop.name] = datastore_value.id_or_name() # elif isinstance(prop,MLStringProperty): # entity[prop.name] = u'|'.join(datastore_value) # elif isinstance(prop,KeyListProperty): # entity[prop.name] = [ key.id_or_name() for key in datastore_value ] # # #entity['key_name'] = object.key().id_or_name() # # # The client side do not know the different between id and key_name, they just # # "id" as the unique identifier of an entry # if object.is_saved(): # entity['id'] = object.key().id_or_name() # # # Going to deprecate # entity['instance'] = object # return entity . Output only the next line.
entity = createEntity(row)
Given the code snippet: <|code_start|> entity = createEntity(row) entity['id'] = row.key().id() result.append(entity) prev_offset = offset - limit if prev_offset < 0 : prev_offset = 0 return render_to_response( request, 'gogogo/db/report/list.html', { "result" : result, "offset" : offset + limit, "prev_offset" : prev_offset, "show_next" : count == limit, "show_prev" : offset != 0, "kind" : kind }) @google_login_required def submit(request,kind,id): """ Submit a new report """ kind = "gogogo_" + kind if not kind in _supported_model: raise Http404 model = _supported_model[kind] <|code_end|> , generate the next line using the imports in this file: from django.http import HttpResponse from django.http import Http404 from django.template import Context, loader , RequestContext from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django.forms import ModelForm from django.forms import Widget from django.forms.widgets import Input from django.http import HttpResponseRedirect from ragendja.auth.decorators import staff_only , login_required , google_login_required from ragendja.template import render_to_response from gogogo.models import * from django.core.urlresolvers import reverse from django.utils.safestring import mark_safe from gogogo.models.cache import getCachedObjectOr404 from gogogo.models.utils import createEntity from gogogo.views.widgets import ReferenceLinkField from django import forms and context (functions, classes, or occasionally code) from other files: # Path: gogogo/models/cache.py # def getCachedObjectOr404(model = None,key=None,key_name=None,id = None , id_or_name = None): # """ # Get a object from cache. If it is not existed in the cache, # it will query from database directly and save it in cache. # # If the object is not existed in the cache and database , it # will raise Http404 exception # """ # # if id_or_name: # try: # id = int(id_or_name) # except ValueError: # key_name = id_or_name # # cache_key = getCacheObjectKey(model = model , key=key , key_name = key_name,id = id) # # #print cache_key # object = memcache.get(cache_key) # # if object == None: # if key: # object = get_object_or_404(model,key) # else: # object = get_object_or_404(model,key_name=key_name, id = id) # if not memcache.add(cache_key, object, _default_cache_time): # logging.error("Memcache set %s failed." % cache_key) # # return object # # Path: gogogo/models/utils.py # def createEntity(object): # """ Create an entity from model instance object which is # suitable for data import and export. # # Operations: # - Convert all ReferenceProperty to the key_name/key # - set 'id' attribute (= id_or_name() # - set 'instance' attribute , the reference to the model instance # # @return A dict object contains the entity of the model instance. The fields are not translated , use trEntity to translate to user's locale # # """ # entity = {} # # for prop in object.properties().values(): # datastore_value = prop.get_value_for_datastore(object) # entity[prop.name] = datastore_value # # if datastore_value == None: # continue # if not datastore_value == []: # if isinstance(prop,db.ReferenceProperty): # entity[prop.name] = datastore_value.id_or_name() # elif isinstance(prop,MLStringProperty): # entity[prop.name] = u'|'.join(datastore_value) # elif isinstance(prop,KeyListProperty): # entity[prop.name] = [ key.id_or_name() for key in datastore_value ] # # #entity['key_name'] = object.key().id_or_name() # # # The client side do not know the different between id and key_name, they just # # "id" as the unique identifier of an entry # if object.is_saved(): # entity['id'] = object.key().id_or_name() # # # Going to deprecate # entity['instance'] = object # return entity # # Path: gogogo/views/widgets.py # class ReferenceLinkField(forms.Field): # """ # A read-only field with a link to the target of reporting object # """ # # def __init__(self, *args, **kwargs): # if 'widget' not in kwargs: # kwargs.update( { 'widget' : ReferenceLinkWidget() }) # # super(ReferenceLinkField, self).__init__(*args, **kwargs) # # # def clean(self,value): # # value = super(ReferenceLinkField, self).clean(value) # if not value: # return None # instance = db.get(value) # if instance is None: # raise db.BadValueError(self.error_messages['invalid_choice']) # return instance . Output only the next line.
object = getCachedObjectOr404(model,key_name = id)
Predict the next line for this snippet: <|code_start|> """ List report """ kind = None limit = 10 offset = 0 if request.method == "GET": if "limit" in request.GET: limit = int(request.GET['limit']) if "offset" in request.GET: offset = int(request.GET['offset']) if offset < 0 : offset = 0 if "kind" in request.GET: kind = request.GET['kind'] if kind is not None: gql = db.GqlQuery("SELECT * from gogogo_report WHERE model_kind = :1 ORDER BY commit_date DESC ",kind) else: gql = db.GqlQuery("SELECT * from gogogo_report ORDER BY commit_date DESC ") query = gql.fetch(limit,offset) result = [] count = 0 for row in query : count+=1 <|code_end|> with the help of current file imports: from django.http import HttpResponse from django.http import Http404 from django.template import Context, loader , RequestContext from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django.forms import ModelForm from django.forms import Widget from django.forms.widgets import Input from django.http import HttpResponseRedirect from ragendja.auth.decorators import staff_only , login_required , google_login_required from ragendja.template import render_to_response from gogogo.models import * from django.core.urlresolvers import reverse from django.utils.safestring import mark_safe from gogogo.models.cache import getCachedObjectOr404 from gogogo.models.utils import createEntity from gogogo.views.widgets import ReferenceLinkField from django import forms and context from other files: # Path: gogogo/models/cache.py # def getCachedObjectOr404(model = None,key=None,key_name=None,id = None , id_or_name = None): # """ # Get a object from cache. If it is not existed in the cache, # it will query from database directly and save it in cache. # # If the object is not existed in the cache and database , it # will raise Http404 exception # """ # # if id_or_name: # try: # id = int(id_or_name) # except ValueError: # key_name = id_or_name # # cache_key = getCacheObjectKey(model = model , key=key , key_name = key_name,id = id) # # #print cache_key # object = memcache.get(cache_key) # # if object == None: # if key: # object = get_object_or_404(model,key) # else: # object = get_object_or_404(model,key_name=key_name, id = id) # if not memcache.add(cache_key, object, _default_cache_time): # logging.error("Memcache set %s failed." % cache_key) # # return object # # Path: gogogo/models/utils.py # def createEntity(object): # """ Create an entity from model instance object which is # suitable for data import and export. # # Operations: # - Convert all ReferenceProperty to the key_name/key # - set 'id' attribute (= id_or_name() # - set 'instance' attribute , the reference to the model instance # # @return A dict object contains the entity of the model instance. The fields are not translated , use trEntity to translate to user's locale # # """ # entity = {} # # for prop in object.properties().values(): # datastore_value = prop.get_value_for_datastore(object) # entity[prop.name] = datastore_value # # if datastore_value == None: # continue # if not datastore_value == []: # if isinstance(prop,db.ReferenceProperty): # entity[prop.name] = datastore_value.id_or_name() # elif isinstance(prop,MLStringProperty): # entity[prop.name] = u'|'.join(datastore_value) # elif isinstance(prop,KeyListProperty): # entity[prop.name] = [ key.id_or_name() for key in datastore_value ] # # #entity['key_name'] = object.key().id_or_name() # # # The client side do not know the different between id and key_name, they just # # "id" as the unique identifier of an entry # if object.is_saved(): # entity['id'] = object.key().id_or_name() # # # Going to deprecate # entity['instance'] = object # return entity # # Path: gogogo/views/widgets.py # class ReferenceLinkField(forms.Field): # """ # A read-only field with a link to the target of reporting object # """ # # def __init__(self, *args, **kwargs): # if 'widget' not in kwargs: # kwargs.update( { 'widget' : ReferenceLinkWidget() }) # # super(ReferenceLinkField, self).__init__(*args, **kwargs) # # # def clean(self,value): # # value = super(ReferenceLinkField, self).clean(value) # if not value: # return None # instance = db.get(value) # if instance is None: # raise db.BadValueError(self.error_messages['invalid_choice']) # return instance , which may contain function names, class names, or code. Output only the next line.
entity = createEntity(row)
Using the snippet: <|code_start|>""" Invalid information report function """ #from gogogo.views.db import reverse as db_reverse class ReportForm(ModelForm): subject = forms.CharField(required=True) detail = forms.CharField(required=True,widget=forms.Textarea) #reference = ReferenceLinkField(required=False,widget = ReferenceLinkWidget()) <|code_end|> , determine the next line of code. You have imports: from django.http import HttpResponse from django.http import Http404 from django.template import Context, loader , RequestContext from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django.forms import ModelForm from django.forms import Widget from django.forms.widgets import Input from django.http import HttpResponseRedirect from ragendja.auth.decorators import staff_only , login_required , google_login_required from ragendja.template import render_to_response from gogogo.models import * from django.core.urlresolvers import reverse from django.utils.safestring import mark_safe from gogogo.models.cache import getCachedObjectOr404 from gogogo.models.utils import createEntity from gogogo.views.widgets import ReferenceLinkField from django import forms and context (class names, function names, or code) available: # Path: gogogo/models/cache.py # def getCachedObjectOr404(model = None,key=None,key_name=None,id = None , id_or_name = None): # """ # Get a object from cache. If it is not existed in the cache, # it will query from database directly and save it in cache. # # If the object is not existed in the cache and database , it # will raise Http404 exception # """ # # if id_or_name: # try: # id = int(id_or_name) # except ValueError: # key_name = id_or_name # # cache_key = getCacheObjectKey(model = model , key=key , key_name = key_name,id = id) # # #print cache_key # object = memcache.get(cache_key) # # if object == None: # if key: # object = get_object_or_404(model,key) # else: # object = get_object_or_404(model,key_name=key_name, id = id) # if not memcache.add(cache_key, object, _default_cache_time): # logging.error("Memcache set %s failed." % cache_key) # # return object # # Path: gogogo/models/utils.py # def createEntity(object): # """ Create an entity from model instance object which is # suitable for data import and export. # # Operations: # - Convert all ReferenceProperty to the key_name/key # - set 'id' attribute (= id_or_name() # - set 'instance' attribute , the reference to the model instance # # @return A dict object contains the entity of the model instance. The fields are not translated , use trEntity to translate to user's locale # # """ # entity = {} # # for prop in object.properties().values(): # datastore_value = prop.get_value_for_datastore(object) # entity[prop.name] = datastore_value # # if datastore_value == None: # continue # if not datastore_value == []: # if isinstance(prop,db.ReferenceProperty): # entity[prop.name] = datastore_value.id_or_name() # elif isinstance(prop,MLStringProperty): # entity[prop.name] = u'|'.join(datastore_value) # elif isinstance(prop,KeyListProperty): # entity[prop.name] = [ key.id_or_name() for key in datastore_value ] # # #entity['key_name'] = object.key().id_or_name() # # # The client side do not know the different between id and key_name, they just # # "id" as the unique identifier of an entry # if object.is_saved(): # entity['id'] = object.key().id_or_name() # # # Going to deprecate # entity['instance'] = object # return entity # # Path: gogogo/views/widgets.py # class ReferenceLinkField(forms.Field): # """ # A read-only field with a link to the target of reporting object # """ # # def __init__(self, *args, **kwargs): # if 'widget' not in kwargs: # kwargs.update( { 'widget' : ReferenceLinkWidget() }) # # super(ReferenceLinkField, self).__init__(*args, **kwargs) # # # def clean(self,value): # # value = super(ReferenceLinkField, self).clean(value) # if not value: # return None # instance = db.get(value) # if instance is None: # raise db.BadValueError(self.error_messages['invalid_choice']) # return instance . Output only the next line.
reference = ReferenceLinkField()
Here is a snippet: <|code_start|> def test_print_version(ctx): ctx.resilient_parsing = True assert print_version(ctx, 'version 1', True) is None ctx.resilient_parsing = False with pytest.raises(Exception): print_version(ctx, 'version 1', True) def test_main(ctx): with pytest.raises(SystemExit): <|code_end|> . Write the next line using the current file imports: from egasub.cli import print_version, main, dry_run import pytest import os and context from other files: # Path: egasub/cli.py # def print_version(ctx, param, value): # if not value or ctx.resilient_parsing: # return # click.echo('egasub %s' % ver) # ctx.exit() # # @click.group() # @click.option('--debug/--no-debug', '-d', default=False) # @click.option('--info/--no-info','-i', default=True) # @click.option('--version', '-v', is_flag=True, callback=print_version, # expose_value=False, is_eager=True) # @click.pass_context # def main(ctx, debug, info): # # initializing ctx.obj # ctx.obj = {} # ctx.obj['IS_TEST'] = False # ctx.obj['CURRENT_DIR'] = os.getcwd() # ctx.obj['IS_TEST_PROJ'] = None # ctx.obj['WORKSPACE_PATH'] = utils.find_workspace_root(cwd=ctx.obj['CURRENT_DIR']) # utils.initialize_log(ctx, debug, info) # # @main.command() # @click.argument('submission_dir', type=click.Path(exists=True), nargs=-1) # @click.pass_context # def dry_run(ctx, submission_dir): # """ # Test submission on submission folder(s). # """ # if '.' in submission_dir or '..' in submission_dir: # ctx.obj['LOGGER'].critical("Submission dir can not be '.' or '..'") # ctx.abort() # # utils.initialize_app(ctx) # # if not submission_dir: # ctx.obj['LOGGER'].critical('You must specify at least one submission directory.') # ctx.abort() # # perform_submission(ctx, submission_dir, dry_run=True) , which may include functions, classes, or code. Output only the next line.
main()
Here is a snippet: <|code_start|> def test_initialize_app(ctx, mock_server): with pytest.raises(KeyError): initialize_app(ctx) #ctx.obj['WORKSPACE_PATH'] = "tests/data/workspace/" #ctx.obj['CURRENT_DIR'] = 'tests/data/workspace/' #ctx.obj['WORKSPACE_PATH']['SETTINGS'] = #with pytest.raises(Exception): # initialize_app(ctx) #ctx.obj['CURRENT_DIR'] = "" def test_initialize_log(ctx): ctx.obj['WORKSPACE_PATH'] = None <|code_end|> . Write the next line using the current file imports: from egasub.utils import initialize_app, initialize_log, get_current_dir_type, get_settings, find_workspace_root import pytest import os and context from other files: # Path: egasub/utils.py # def initialize_app(ctx): # if not ctx.obj['WORKSPACE_PATH']: # ctx.obj['LOGGER'].critical('Not in an EGA submission workspace! Please run "egasub init" to initiate an EGA workspace.') # ctx.abort() # # # read the settings # ctx.obj['SETTINGS'] = get_settings(ctx.obj['WORKSPACE_PATH']) # if not ctx.obj['SETTINGS']: # ctx.obj['LOGGER'].critical('Unable to read config file, or config file invalid!') # ctx.abort() # # # figure out the current dir type, e.g., study, sample or analysis # ctx.obj['CURRENT_DIR_TYPE'] = get_current_dir_type(ctx) # # if not ctx.obj['CURRENT_DIR_TYPE']: # ctx.obj['LOGGER'].critical("You must run this command directly under a 'submission batch' directory named with this pattern: (unaligned|alignment|variation)\.([a-zA-Z0-9_\-]+). You can create 'submission batch' directories under the current workspace: %s" % ctx.obj['WORKSPACE_PATH']) # ctx.abort() # # ctx.obj['EGA_ENUMS'] = EgaEnums() # # def initialize_log(ctx, debug, info): # logger = logging.getLogger('ega_submission') # logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s") # # logger.setLevel(logging.DEBUG) # # if ctx.obj['WORKSPACE_PATH'] == None: # logger = logging.getLogger('ega_submission') # ch = logging.StreamHandler() # if debug: # ch.setLevel(logging.DEBUG) # elif info: # ch.setLevel(logging.INFO) # logger.addHandler(ch) # ctx.obj['LOGGER'] = logger # return # # log_directory = os.path.join(ctx.obj['WORKSPACE_PATH'],".log") # log_file = "%s.log" % re.sub(r'[-:.]', '_', datetime.datetime.utcnow().isoformat()) # ctx.obj['log_file'] = log_file # log_file = os.path.join(log_directory, log_file) # # if not os.path.isdir(log_directory): # os.mkdir(log_directory) # # fh = logging.FileHandler(log_file) # fh.setLevel(logging.DEBUG) # always set fh to debug # fh.setFormatter(logFormatter) # # ch = logging.StreamHandler() # ch.setFormatter(logging.Formatter("[%(levelname)-5.5s] %(message)s")) # if debug: # ch.setLevel(logging.DEBUG) # elif info: # ch.setLevel(logging.INFO) # # logger.addHandler(fh) # logger.addHandler(ch) # # ctx.obj['LOGGER'] = logger # # def get_current_dir_type(ctx): # workplace = ctx.obj['WORKSPACE_PATH'] # current_dir = ctx.obj['CURRENT_DIR'] # # pattern = re.compile('^%s/(unaligned|alignment|variation)\.([a-zA-Z0-9_\-]+)$' % workplace) # m = re.match(pattern, current_dir) # if m and m.group(1): # return m.group(1) # # return None # # def get_settings(wspath): # config_file = os.path.join(wspath, '.egasub', 'config.yaml') # if not os.path.isfile(config_file): # return None # # with open(config_file, 'r') as f: # settings = yaml.safe_load(f) # # return settings # # def find_workspace_root(cwd=os.getcwd()): # searching_for = set(['.egasub']) # last_root = cwd # current_root = cwd # found_path = None # while found_path is None and current_root: # for root, dirs, _ in os.walk(current_root): # if not searching_for - set(dirs): # # found the directories, stop # if os.path.isfile(os.path.join(root, '.egasub', 'config.yaml')): # return root # else: # return None # # only need to search for the current dir # break # # # Otherwise, pop up a level, search again # last_root = current_root # current_root = os.path.dirname(last_root) # # # stop if it's already reached os root dir # if current_root == last_root: break # return None , which may include functions, classes, or code. Output only the next line.
initialize_log(ctx, True, "info")
Continue the code snippet: <|code_start|> def test_initialize_app(ctx, mock_server): with pytest.raises(KeyError): initialize_app(ctx) #ctx.obj['WORKSPACE_PATH'] = "tests/data/workspace/" #ctx.obj['CURRENT_DIR'] = 'tests/data/workspace/' #ctx.obj['WORKSPACE_PATH']['SETTINGS'] = #with pytest.raises(Exception): # initialize_app(ctx) #ctx.obj['CURRENT_DIR'] = "" def test_initialize_log(ctx): ctx.obj['WORKSPACE_PATH'] = None initialize_log(ctx, True, "info") #assert os.path.isdir("%s/.log" %(str(ctx.obj['LOGGER']))) ctx.obj['WORKSPACE_PATH'] = "tests/data/workspace/" initialize_log(ctx, True, "info") assert os.path.isdir("tests/data/workspace/.log") def test_get_current_dir_type(ctx): #ctx.obj['CURRENT_DIR'] = None #ctx.obj['WORKSPACE_PATH'] = None with pytest.raises(KeyError): <|code_end|> . Use current file imports: from egasub.utils import initialize_app, initialize_log, get_current_dir_type, get_settings, find_workspace_root import pytest import os and context (classes, functions, or code) from other files: # Path: egasub/utils.py # def initialize_app(ctx): # if not ctx.obj['WORKSPACE_PATH']: # ctx.obj['LOGGER'].critical('Not in an EGA submission workspace! Please run "egasub init" to initiate an EGA workspace.') # ctx.abort() # # # read the settings # ctx.obj['SETTINGS'] = get_settings(ctx.obj['WORKSPACE_PATH']) # if not ctx.obj['SETTINGS']: # ctx.obj['LOGGER'].critical('Unable to read config file, or config file invalid!') # ctx.abort() # # # figure out the current dir type, e.g., study, sample or analysis # ctx.obj['CURRENT_DIR_TYPE'] = get_current_dir_type(ctx) # # if not ctx.obj['CURRENT_DIR_TYPE']: # ctx.obj['LOGGER'].critical("You must run this command directly under a 'submission batch' directory named with this pattern: (unaligned|alignment|variation)\.([a-zA-Z0-9_\-]+). You can create 'submission batch' directories under the current workspace: %s" % ctx.obj['WORKSPACE_PATH']) # ctx.abort() # # ctx.obj['EGA_ENUMS'] = EgaEnums() # # def initialize_log(ctx, debug, info): # logger = logging.getLogger('ega_submission') # logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s") # # logger.setLevel(logging.DEBUG) # # if ctx.obj['WORKSPACE_PATH'] == None: # logger = logging.getLogger('ega_submission') # ch = logging.StreamHandler() # if debug: # ch.setLevel(logging.DEBUG) # elif info: # ch.setLevel(logging.INFO) # logger.addHandler(ch) # ctx.obj['LOGGER'] = logger # return # # log_directory = os.path.join(ctx.obj['WORKSPACE_PATH'],".log") # log_file = "%s.log" % re.sub(r'[-:.]', '_', datetime.datetime.utcnow().isoformat()) # ctx.obj['log_file'] = log_file # log_file = os.path.join(log_directory, log_file) # # if not os.path.isdir(log_directory): # os.mkdir(log_directory) # # fh = logging.FileHandler(log_file) # fh.setLevel(logging.DEBUG) # always set fh to debug # fh.setFormatter(logFormatter) # # ch = logging.StreamHandler() # ch.setFormatter(logging.Formatter("[%(levelname)-5.5s] %(message)s")) # if debug: # ch.setLevel(logging.DEBUG) # elif info: # ch.setLevel(logging.INFO) # # logger.addHandler(fh) # logger.addHandler(ch) # # ctx.obj['LOGGER'] = logger # # def get_current_dir_type(ctx): # workplace = ctx.obj['WORKSPACE_PATH'] # current_dir = ctx.obj['CURRENT_DIR'] # # pattern = re.compile('^%s/(unaligned|alignment|variation)\.([a-zA-Z0-9_\-]+)$' % workplace) # m = re.match(pattern, current_dir) # if m and m.group(1): # return m.group(1) # # return None # # def get_settings(wspath): # config_file = os.path.join(wspath, '.egasub', 'config.yaml') # if not os.path.isfile(config_file): # return None # # with open(config_file, 'r') as f: # settings = yaml.safe_load(f) # # return settings # # def find_workspace_root(cwd=os.getcwd()): # searching_for = set(['.egasub']) # last_root = cwd # current_root = cwd # found_path = None # while found_path is None and current_root: # for root, dirs, _ in os.walk(current_root): # if not searching_for - set(dirs): # # found the directories, stop # if os.path.isfile(os.path.join(root, '.egasub', 'config.yaml')): # return root # else: # return None # # only need to search for the current dir # break # # # Otherwise, pop up a level, search again # last_root = current_root # current_root = os.path.dirname(last_root) # # # stop if it's already reached os root dir # if current_root == last_root: break # return None . Output only the next line.
get_current_dir_type(ctx)
Using the snippet: <|code_start|> ctx.obj['WORKSPACE_PATH'] = "" with pytest.raises(KeyError): get_current_dir_type(ctx) ctx.obj['CURRENT_DIR'] = "" print get_current_dir_type(ctx) assert get_current_dir_type(ctx) == None workspace = "test" ctx.obj['WORKSPACE_PATH'] = workspace ctx.obj['CURRENT_DIR'] = "%s/alignment.20170115" % workspace assert get_current_dir_type(ctx) == "alignment" ctx.obj['CURRENT_DIR'] = "%s/alignment.test" % workspace assert get_current_dir_type(ctx) == "alignment" ctx.obj['CURRENT_DIR'] = "%s/unaligned.test" % workspace assert get_current_dir_type(ctx) == "unaligned" ctx.obj['CURRENT_DIR'] = "%s/variation.test" % workspace assert get_current_dir_type(ctx) == "variation" ctx.obj['CURRENT_DIR'] = "%s/variations.test" % workspace assert get_current_dir_type(ctx) == None def test_get_settings(): <|code_end|> , determine the next line of code. You have imports: from egasub.utils import initialize_app, initialize_log, get_current_dir_type, get_settings, find_workspace_root import pytest import os and context (class names, function names, or code) available: # Path: egasub/utils.py # def initialize_app(ctx): # if not ctx.obj['WORKSPACE_PATH']: # ctx.obj['LOGGER'].critical('Not in an EGA submission workspace! Please run "egasub init" to initiate an EGA workspace.') # ctx.abort() # # # read the settings # ctx.obj['SETTINGS'] = get_settings(ctx.obj['WORKSPACE_PATH']) # if not ctx.obj['SETTINGS']: # ctx.obj['LOGGER'].critical('Unable to read config file, or config file invalid!') # ctx.abort() # # # figure out the current dir type, e.g., study, sample or analysis # ctx.obj['CURRENT_DIR_TYPE'] = get_current_dir_type(ctx) # # if not ctx.obj['CURRENT_DIR_TYPE']: # ctx.obj['LOGGER'].critical("You must run this command directly under a 'submission batch' directory named with this pattern: (unaligned|alignment|variation)\.([a-zA-Z0-9_\-]+). You can create 'submission batch' directories under the current workspace: %s" % ctx.obj['WORKSPACE_PATH']) # ctx.abort() # # ctx.obj['EGA_ENUMS'] = EgaEnums() # # def initialize_log(ctx, debug, info): # logger = logging.getLogger('ega_submission') # logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s") # # logger.setLevel(logging.DEBUG) # # if ctx.obj['WORKSPACE_PATH'] == None: # logger = logging.getLogger('ega_submission') # ch = logging.StreamHandler() # if debug: # ch.setLevel(logging.DEBUG) # elif info: # ch.setLevel(logging.INFO) # logger.addHandler(ch) # ctx.obj['LOGGER'] = logger # return # # log_directory = os.path.join(ctx.obj['WORKSPACE_PATH'],".log") # log_file = "%s.log" % re.sub(r'[-:.]', '_', datetime.datetime.utcnow().isoformat()) # ctx.obj['log_file'] = log_file # log_file = os.path.join(log_directory, log_file) # # if not os.path.isdir(log_directory): # os.mkdir(log_directory) # # fh = logging.FileHandler(log_file) # fh.setLevel(logging.DEBUG) # always set fh to debug # fh.setFormatter(logFormatter) # # ch = logging.StreamHandler() # ch.setFormatter(logging.Formatter("[%(levelname)-5.5s] %(message)s")) # if debug: # ch.setLevel(logging.DEBUG) # elif info: # ch.setLevel(logging.INFO) # # logger.addHandler(fh) # logger.addHandler(ch) # # ctx.obj['LOGGER'] = logger # # def get_current_dir_type(ctx): # workplace = ctx.obj['WORKSPACE_PATH'] # current_dir = ctx.obj['CURRENT_DIR'] # # pattern = re.compile('^%s/(unaligned|alignment|variation)\.([a-zA-Z0-9_\-]+)$' % workplace) # m = re.match(pattern, current_dir) # if m and m.group(1): # return m.group(1) # # return None # # def get_settings(wspath): # config_file = os.path.join(wspath, '.egasub', 'config.yaml') # if not os.path.isfile(config_file): # return None # # with open(config_file, 'r') as f: # settings = yaml.safe_load(f) # # return settings # # def find_workspace_root(cwd=os.getcwd()): # searching_for = set(['.egasub']) # last_root = cwd # current_root = cwd # found_path = None # while found_path is None and current_root: # for root, dirs, _ in os.walk(current_root): # if not searching_for - set(dirs): # # found the directories, stop # if os.path.isfile(os.path.join(root, '.egasub', 'config.yaml')): # return root # else: # return None # # only need to search for the current dir # break # # # Otherwise, pop up a level, search again # last_root = current_root # current_root = os.path.dirname(last_root) # # # stop if it's already reached os root dir # if current_root == last_root: break # return None . Output only the next line.
assert get_settings("") == None
Here is a snippet: <|code_start|> assert get_current_dir_type(ctx) == "alignment" ctx.obj['CURRENT_DIR'] = "%s/alignment.test" % workspace assert get_current_dir_type(ctx) == "alignment" ctx.obj['CURRENT_DIR'] = "%s/unaligned.test" % workspace assert get_current_dir_type(ctx) == "unaligned" ctx.obj['CURRENT_DIR'] = "%s/variation.test" % workspace assert get_current_dir_type(ctx) == "variation" ctx.obj['CURRENT_DIR'] = "%s/variations.test" % workspace assert get_current_dir_type(ctx) == None def test_get_settings(): assert get_settings("") == None settings = get_settings("tests/data/workspace") assert settings['ega_submitter_account'] == "dummy-account" assert settings['icgc_id_service_token'] == 'fake-token' assert settings['ega_submitter_password'] == 'change-me' assert settings['icgc_project_code'] == 'PACA-CA' assert settings['ega_submitter_account'] != "dummy-test" assert settings['icgc_id_service_token'] != 'fake-test' assert settings['ega_submitter_password'] != 'change-test' assert settings['icgc_project_code'] != 'PACA-TEST' def test_find_workspace_root(): workspace_root = "tests/data/workspace" <|code_end|> . Write the next line using the current file imports: from egasub.utils import initialize_app, initialize_log, get_current_dir_type, get_settings, find_workspace_root import pytest import os and context from other files: # Path: egasub/utils.py # def initialize_app(ctx): # if not ctx.obj['WORKSPACE_PATH']: # ctx.obj['LOGGER'].critical('Not in an EGA submission workspace! Please run "egasub init" to initiate an EGA workspace.') # ctx.abort() # # # read the settings # ctx.obj['SETTINGS'] = get_settings(ctx.obj['WORKSPACE_PATH']) # if not ctx.obj['SETTINGS']: # ctx.obj['LOGGER'].critical('Unable to read config file, or config file invalid!') # ctx.abort() # # # figure out the current dir type, e.g., study, sample or analysis # ctx.obj['CURRENT_DIR_TYPE'] = get_current_dir_type(ctx) # # if not ctx.obj['CURRENT_DIR_TYPE']: # ctx.obj['LOGGER'].critical("You must run this command directly under a 'submission batch' directory named with this pattern: (unaligned|alignment|variation)\.([a-zA-Z0-9_\-]+). You can create 'submission batch' directories under the current workspace: %s" % ctx.obj['WORKSPACE_PATH']) # ctx.abort() # # ctx.obj['EGA_ENUMS'] = EgaEnums() # # def initialize_log(ctx, debug, info): # logger = logging.getLogger('ega_submission') # logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s") # # logger.setLevel(logging.DEBUG) # # if ctx.obj['WORKSPACE_PATH'] == None: # logger = logging.getLogger('ega_submission') # ch = logging.StreamHandler() # if debug: # ch.setLevel(logging.DEBUG) # elif info: # ch.setLevel(logging.INFO) # logger.addHandler(ch) # ctx.obj['LOGGER'] = logger # return # # log_directory = os.path.join(ctx.obj['WORKSPACE_PATH'],".log") # log_file = "%s.log" % re.sub(r'[-:.]', '_', datetime.datetime.utcnow().isoformat()) # ctx.obj['log_file'] = log_file # log_file = os.path.join(log_directory, log_file) # # if not os.path.isdir(log_directory): # os.mkdir(log_directory) # # fh = logging.FileHandler(log_file) # fh.setLevel(logging.DEBUG) # always set fh to debug # fh.setFormatter(logFormatter) # # ch = logging.StreamHandler() # ch.setFormatter(logging.Formatter("[%(levelname)-5.5s] %(message)s")) # if debug: # ch.setLevel(logging.DEBUG) # elif info: # ch.setLevel(logging.INFO) # # logger.addHandler(fh) # logger.addHandler(ch) # # ctx.obj['LOGGER'] = logger # # def get_current_dir_type(ctx): # workplace = ctx.obj['WORKSPACE_PATH'] # current_dir = ctx.obj['CURRENT_DIR'] # # pattern = re.compile('^%s/(unaligned|alignment|variation)\.([a-zA-Z0-9_\-]+)$' % workplace) # m = re.match(pattern, current_dir) # if m and m.group(1): # return m.group(1) # # return None # # def get_settings(wspath): # config_file = os.path.join(wspath, '.egasub', 'config.yaml') # if not os.path.isfile(config_file): # return None # # with open(config_file, 'r') as f: # settings = yaml.safe_load(f) # # return settings # # def find_workspace_root(cwd=os.getcwd()): # searching_for = set(['.egasub']) # last_root = cwd # current_root = cwd # found_path = None # while found_path is None and current_root: # for root, dirs, _ in os.walk(current_root): # if not searching_for - set(dirs): # # found the directories, stop # if os.path.isfile(os.path.join(root, '.egasub', 'config.yaml')): # return root # else: # return None # # only need to search for the current dir # break # # # Otherwise, pop up a level, search again # last_root = current_root # current_root = os.path.dirname(last_root) # # # stop if it's already reached os root dir # if current_root == last_root: break # return None , which may include functions, classes, or code. Output only the next line.
assert find_workspace_root() == None
Here is a snippet: <|code_start|> 'anonymizedName' : self.anonymized_name, 'bioSampleId' : self.bio_sample_id, 'sampleAge' : self.sample_age, 'sampleDetail' : self.sample_detail, 'attributes' : map(lambda attribute: attribute.to_dict(), self.attributes), 'id' : self.id, 'status': self.status, 'egaAccessionId': self.ega_accession_id } def to_xml(self): pass @staticmethod def from_dict(sample_dict): return Sample( sample_dict.get('alias'), sample_dict.get('title'), sample_dict.get('description'), sample_dict.get('caseOrControlId'), sample_dict.get('genderId'), sample_dict.get('organismPart'), sample_dict.get('cellLine'), sample_dict.get('region'), sample_dict.get('phenotype'), sample_dict.get('subjectId'), sample_dict.get('anonymizedName'), sample_dict.get('bioSampleId'), sample_dict.get('sampleAge'), sample_dict.get('sampleDetail'), <|code_end|> . Write the next line using the current file imports: from .attribute import Attribute and context from other files: # Path: egasub/ega/entities/attribute.py # class Attribute(object): # def __init__(self, tag, value="", unit=None): # self.tag = tag # self.value = value # self.unit = unit # # # def to_dict(self): # return { # "tag": self.tag, # "value": self.value, # "unit": self.unit # } # # # def to_xml(self): # xml_string = "<TAG>%s</TAG>\n<VALUE>%s</VALUE>\n" % (self.tag, self.value) # if self.unit is not None: # xml_string += "<UNIT>%s</UNIT>\n" % (self.unit) # return xml_string # # @staticmethod # def from_dict(attr_dict): # return Attribute(attr_dict.get('tag'),attr_dict.get('value'),attr_dict.get('unit')) , which may include functions, classes, or code. Output only the next line.
[] if not sample_dict.get('attributes') else [ Attribute.from_dict(attr_dict) for attr_dict in sample_dict.get('attributes')],
Continue the code snippet: <|code_start|> def test_alignment(ctx): submission_dirs = ['test_1','test_2'] ctx.obj['CURRENT_DIR_TYPE'] = "alignme" ctx.obj['CURRENT_DIR_TYPE'] = "alignment" with pytest.raises(IOError): <|code_end|> . Use current file imports: from egasub.submission.init_submission_dir import init_submission_dir import pytest and context (classes, functions, or code) from other files: # Path: egasub/submission/init_submission_dir.py # def init_submission_dir(ctx, submission_dirs): # submission_type = ctx.obj['CURRENT_DIR_TYPE'] # if submission_type in ("alignment", "variation"): # file_name = "analysis.yaml" # elif submission_type in ("unaligned"): # file_name = "experiment.yaml" # else: # ctx.obj['LOGGER'].critical('You must be in one of the supported submission data type directory: unaligned, alignment or variation') # ctx.abort() # # src_file = os.path.join(os.path.dirname( # os.path.realpath(__file__)), # 'metadata_template', # submission_type,file_name # ) # for d in submission_dirs: # d = d.rstrip('/') # if not re.match(r'^[a-zA-Z0-9_\-]+(\.[a-zA-Z0-9_\-]+){0,1}$', d): # ctx.obj['LOGGER'].warning("Skipping directory '%s'. Submission directory should be named as <sample alias> or <sample alias>.<lane label>, sample alias and lane label may only contain letter, digit, underscore (_) or dash (-)" % d) # continue # # if d.upper().startswith('SA'): # we may want to make this configurable to allow it turned off for non-ICGC submitters # ctx.obj['LOGGER'].warning("Skipping directory '%s'. Submission directory can not start with 'SA' or 'sa', this is reserved for ICGC DCC." % d) # continue # # if d.upper().startswith('EGA'): # ctx.obj['LOGGER'].warning("Skipping directory '%s'. Submission directory can not start with 'EGA' or 'ega', this is reserved for EGA." % d) # continue # # dest_file = os.path.join(d, file_name) # # if os.path.isfile(dest_file): # ctx.obj['LOGGER'].warning("Skipping directory '%s', as it already contains the file: %s" % (d, file_name)) # continue # # copyfile(src_file, dest_file) # ctx.obj['LOGGER'].info("Initialized folder '%s' with a metadata template '%s', please fill it out properly before performing submission." % (d, file_name)) . Output only the next line.
init_submission_dir(ctx,submission_dirs)
Given the following code snippet before the placeholder: <|code_start|> files = [File(32,'file name1','CheckSum1','UnencryptedChecksum1','md5'), File(33,'file name2','CheckSum2','UnencryptedChecksum2','md5')] attributes = [Attribute('The tag 1','The value 1','an unit'),Attribute('The tag 2','The value 2','an unit')] <|code_end|> , predict the next line using imports from the current file: from egasub.ega.entities.analysis import Analysis from egasub.ega.entities.file import File from egasub.ega.entities.chromosome_reference import ChromosomeReference from egasub.ega.entities.sample_reference import SampleReference from egasub.ega.entities.attribute import Attribute and context including class names, function names, and sometimes code from other files: # Path: egasub/ega/entities/analysis.py # class Analysis(object): # def __init__(self, alias, title, description, study_id, sample_references, analysis_center, analysis_date, # analysis_type_id, files, attributes, genome_id, chromosome_references, experiment_type_id,platform,status=None, id_=None,ega_accession_id=None): # self.title = title # self.description = description # self.study_id = study_id # self.sample_references = sample_references # self.analysis_center = analysis_center # self.analysis_date = analysis_date # self.analysis_type_id = analysis_type_id # self.files = files # self.attributes = attributes # self.genome_id = genome_id # self.chromosome_references = chromosome_references # self.experiment_type_id = experiment_type_id # self.platform = platform # self.alias = alias # self.status = status # self.id = id_ # self.ega_accession_id = ega_accession_id # # def to_dict(self): # return { # 'title' : self.title, # 'description' : self.description, # 'studyId' : self.study_id, # 'sampleReferences' : map(lambda ref: ref.to_dict(), self.sample_references), # 'analysisCenter' : self.analysis_center, # 'analysisDate' : self.analysis_date, # 'analysisTypeId' : self.analysis_type_id, # 'files' : map(lambda file: file.to_dict(), self.files), # 'attributes' : map(lambda att: att.to_dict(), self.attributes), # 'genomeId' : self.genome_id, # 'chromosomeReferences' : [ ref.to_dict() for ref in self.chromosome_references], # 'experimentTypeId' : self.experiment_type_id, # 'platform' : self.platform, # 'alias' : self.alias, # 'status': self.status, # 'egaAccessionId': self.ega_accession_id # } # # def to_xml(self): # pass # # @staticmethod # def from_dict(analysis_dict): # return Analysis( # analysis_dict.get('alias'), # analysis_dict.get('title'), # analysis_dict.get('description'), # analysis_dict.get('studyId'), # [], # sampleReferences # analysis_dict.get('analysisCenter'), # analysis_dict.get('analysisDate'), # analysis_dict.get('analysisTypeId'), # [] if not analysis_dict.get('files') else [ File.from_dict(file_dict) for file_dict in analysis_dict.get('files')], # [], # attribute # analysis_dict.get('genomeId'), # [] if not analysis_dict.get('chromosomeReferences') else [ChromosomeReference(tag) for tag in analysis_dict.get('chromosomeReferences')], # analysis_dict.get('experimentTypeId'), # analysis_dict.get('platform') # ) # # Path: egasub/ega/entities/file.py # class File(object): # def __init__(self,file_id,file_name,checksum,unencrypted_checksum,checksum_method): # self.file_id = file_id # self.file_name = file_name # self.checksum = checksum # self.unencrypted_checksum = unencrypted_checksum # self.checksum_method = checksum_method # # def to_dict(self): # return { # 'fileId': self.file_id, # 'fileName': self.file_name, # 'checksum': self.checksum, # 'unencryptedChecksum' : self.unencrypted_checksum, # 'checksumMethod' : self.checksum_method # } # # def to_xml(self): # pass # # @staticmethod # def from_dict(file_dict): # return File( # None, # file_dict.get('fileName'), # file_dict.get('checksum'), # file_dict.get('unencryptedChecksum'), # file_dict.get('checksumMethod') # ) # # Path: egasub/ega/entities/chromosome_reference.py # class ChromosomeReference(object): # def __init__(self,value,label=None): # self.value=value # self.label=label # # def to_dict(self): # return { # 'value' : self.value, # 'label' : self.label # } # # def to_xml(self): # pass # # Path: egasub/ega/entities/sample_reference.py # class SampleReference(object): # def __init__(self,value,label): # self.value = value # self.label = label # # def to_dict(self): # return { # 'value' : self.value, # 'label' : self.label # } # # def to_xml(self): # pass # # Path: egasub/ega/entities/attribute.py # class Attribute(object): # def __init__(self, tag, value="", unit=None): # self.tag = tag # self.value = value # self.unit = unit # # # def to_dict(self): # return { # "tag": self.tag, # "value": self.value, # "unit": self.unit # } # # # def to_xml(self): # xml_string = "<TAG>%s</TAG>\n<VALUE>%s</VALUE>\n" % (self.tag, self.value) # if self.unit is not None: # xml_string += "<UNIT>%s</UNIT>\n" % (self.unit) # return xml_string # # @staticmethod # def from_dict(attr_dict): # return Attribute(attr_dict.get('tag'),attr_dict.get('value'),attr_dict.get('unit')) . Output only the next line.
chromosome_references = [ChromosomeReference('the value1','the label2'),ChromosomeReference('the value2','the label2')]
Predict the next line after this snippet: <|code_start|> files = [File(32,'file name1','CheckSum1','UnencryptedChecksum1','md5'), File(33,'file name2','CheckSum2','UnencryptedChecksum2','md5')] attributes = [Attribute('The tag 1','The value 1','an unit'),Attribute('The tag 2','The value 2','an unit')] chromosome_references = [ChromosomeReference('the value1','the label2'),ChromosomeReference('the value2','the label2')] <|code_end|> using the current file's imports: from egasub.ega.entities.analysis import Analysis from egasub.ega.entities.file import File from egasub.ega.entities.chromosome_reference import ChromosomeReference from egasub.ega.entities.sample_reference import SampleReference from egasub.ega.entities.attribute import Attribute and any relevant context from other files: # Path: egasub/ega/entities/analysis.py # class Analysis(object): # def __init__(self, alias, title, description, study_id, sample_references, analysis_center, analysis_date, # analysis_type_id, files, attributes, genome_id, chromosome_references, experiment_type_id,platform,status=None, id_=None,ega_accession_id=None): # self.title = title # self.description = description # self.study_id = study_id # self.sample_references = sample_references # self.analysis_center = analysis_center # self.analysis_date = analysis_date # self.analysis_type_id = analysis_type_id # self.files = files # self.attributes = attributes # self.genome_id = genome_id # self.chromosome_references = chromosome_references # self.experiment_type_id = experiment_type_id # self.platform = platform # self.alias = alias # self.status = status # self.id = id_ # self.ega_accession_id = ega_accession_id # # def to_dict(self): # return { # 'title' : self.title, # 'description' : self.description, # 'studyId' : self.study_id, # 'sampleReferences' : map(lambda ref: ref.to_dict(), self.sample_references), # 'analysisCenter' : self.analysis_center, # 'analysisDate' : self.analysis_date, # 'analysisTypeId' : self.analysis_type_id, # 'files' : map(lambda file: file.to_dict(), self.files), # 'attributes' : map(lambda att: att.to_dict(), self.attributes), # 'genomeId' : self.genome_id, # 'chromosomeReferences' : [ ref.to_dict() for ref in self.chromosome_references], # 'experimentTypeId' : self.experiment_type_id, # 'platform' : self.platform, # 'alias' : self.alias, # 'status': self.status, # 'egaAccessionId': self.ega_accession_id # } # # def to_xml(self): # pass # # @staticmethod # def from_dict(analysis_dict): # return Analysis( # analysis_dict.get('alias'), # analysis_dict.get('title'), # analysis_dict.get('description'), # analysis_dict.get('studyId'), # [], # sampleReferences # analysis_dict.get('analysisCenter'), # analysis_dict.get('analysisDate'), # analysis_dict.get('analysisTypeId'), # [] if not analysis_dict.get('files') else [ File.from_dict(file_dict) for file_dict in analysis_dict.get('files')], # [], # attribute # analysis_dict.get('genomeId'), # [] if not analysis_dict.get('chromosomeReferences') else [ChromosomeReference(tag) for tag in analysis_dict.get('chromosomeReferences')], # analysis_dict.get('experimentTypeId'), # analysis_dict.get('platform') # ) # # Path: egasub/ega/entities/file.py # class File(object): # def __init__(self,file_id,file_name,checksum,unencrypted_checksum,checksum_method): # self.file_id = file_id # self.file_name = file_name # self.checksum = checksum # self.unencrypted_checksum = unencrypted_checksum # self.checksum_method = checksum_method # # def to_dict(self): # return { # 'fileId': self.file_id, # 'fileName': self.file_name, # 'checksum': self.checksum, # 'unencryptedChecksum' : self.unencrypted_checksum, # 'checksumMethod' : self.checksum_method # } # # def to_xml(self): # pass # # @staticmethod # def from_dict(file_dict): # return File( # None, # file_dict.get('fileName'), # file_dict.get('checksum'), # file_dict.get('unencryptedChecksum'), # file_dict.get('checksumMethod') # ) # # Path: egasub/ega/entities/chromosome_reference.py # class ChromosomeReference(object): # def __init__(self,value,label=None): # self.value=value # self.label=label # # def to_dict(self): # return { # 'value' : self.value, # 'label' : self.label # } # # def to_xml(self): # pass # # Path: egasub/ega/entities/sample_reference.py # class SampleReference(object): # def __init__(self,value,label): # self.value = value # self.label = label # # def to_dict(self): # return { # 'value' : self.value, # 'label' : self.label # } # # def to_xml(self): # pass # # Path: egasub/ega/entities/attribute.py # class Attribute(object): # def __init__(self, tag, value="", unit=None): # self.tag = tag # self.value = value # self.unit = unit # # # def to_dict(self): # return { # "tag": self.tag, # "value": self.value, # "unit": self.unit # } # # # def to_xml(self): # xml_string = "<TAG>%s</TAG>\n<VALUE>%s</VALUE>\n" % (self.tag, self.value) # if self.unit is not None: # xml_string += "<UNIT>%s</UNIT>\n" % (self.unit) # return xml_string # # @staticmethod # def from_dict(attr_dict): # return Attribute(attr_dict.get('tag'),attr_dict.get('value'),attr_dict.get('unit')) . Output only the next line.
sample_references = [SampleReference('a value 1','a label 1'),SampleReference('a value 2','a label 2')]
Given the following code snippet before the placeholder: <|code_start|> def test_init_submission_dir(ctx): ctx.obj['CURRENT_DIR_TYPE'] = None with pytest.raises(TypeError): <|code_end|> , predict the next line using imports from the current file: from egasub.submission import init_submission_dir import pytest and context including class names, function names, and sometimes code from other files: # Path: egasub/submission/init_submission_dir.py # def init_submission_dir(ctx, submission_dirs): # submission_type = ctx.obj['CURRENT_DIR_TYPE'] # if submission_type in ("alignment", "variation"): # file_name = "analysis.yaml" # elif submission_type in ("unaligned"): # file_name = "experiment.yaml" # else: # ctx.obj['LOGGER'].critical('You must be in one of the supported submission data type directory: unaligned, alignment or variation') # ctx.abort() # # src_file = os.path.join(os.path.dirname( # os.path.realpath(__file__)), # 'metadata_template', # submission_type,file_name # ) # for d in submission_dirs: # d = d.rstrip('/') # if not re.match(r'^[a-zA-Z0-9_\-]+(\.[a-zA-Z0-9_\-]+){0,1}$', d): # ctx.obj['LOGGER'].warning("Skipping directory '%s'. Submission directory should be named as <sample alias> or <sample alias>.<lane label>, sample alias and lane label may only contain letter, digit, underscore (_) or dash (-)" % d) # continue # # if d.upper().startswith('SA'): # we may want to make this configurable to allow it turned off for non-ICGC submitters # ctx.obj['LOGGER'].warning("Skipping directory '%s'. Submission directory can not start with 'SA' or 'sa', this is reserved for ICGC DCC." % d) # continue # # if d.upper().startswith('EGA'): # ctx.obj['LOGGER'].warning("Skipping directory '%s'. Submission directory can not start with 'EGA' or 'ega', this is reserved for EGA." % d) # continue # # dest_file = os.path.join(d, file_name) # # if os.path.isfile(dest_file): # ctx.obj['LOGGER'].warning("Skipping directory '%s', as it already contains the file: %s" % (d, file_name)) # continue # # copyfile(src_file, dest_file) # ctx.obj['LOGGER'].info("Initialized folder '%s' with a metadata template '%s', please fill it out properly before performing submission." % (d, file_name)) . Output only the next line.
init_submission_dir(ctx,[])
Here is a snippet: <|code_start|> assert alignment.local_validation_errors[0]['object_type'] == _type assert alignment.local_validation_errors[0]['error'] == _message assert len(alignment.ftp_file_validation_errors) == 1 assert alignment.ftp_file_validation_errors[0]['field'] == _field assert alignment.ftp_file_validation_errors[0]['error'] == _message def test_unaligned(): runner = CliRunner() with runner.isolated_filesystem(): submission_dir = "test" os.mkdir(submission_dir) m = hashlib.md5() m.update("secret") md5_file = "fileName.md5" f = open(os.path.join(submission_dir,md5_file),"wb") f.write(m.hexdigest()) f.close() file_path = "experiment.yaml" with open(os.path.join(submission_dir,file_path),"w") as outfile: yaml.dump(dict( sample = dict(alias="an alias"), experiment = dict(title="a title"), run = dict(runFileTypeId="ID"), files=[dict(fileName="fileName", checksumMethod="md5")]) , outfile) <|code_end|> . Write the next line using the current file imports: from egasub.submission.submittable import _get_md5sum, Alignment, Unaligned from click.testing import CliRunner import hashlib import os import yaml and context from other files: # Path: egasub/submission/submittable/unaligned.py # class Unaligned(Experiment): # pass # # Path: egasub/submission/submittable/alignment.py # class Alignment(Analysis): # def __init__(self, path): # super(Alignment, self).__init__(path) # # if not re.match(r'^[a-zA-Z0-9_\-]+(\.[a-zA-Z0-9_\-]+){0,1}$', self.submission_dir): # raise Exception("Submission directory should be named as <sample alias> or <sample alias>.<lane label>, sample alias and lane label may only contain letter, digit, underscore (_) or dash (-)") # # # def local_validate(self, ega_enums): # super(Alignment, self).local_validate(ega_enums) # # Analysis type validation, 0 - Reference Alignment (BAM) # if not str(self.analysis.analysis_type_id) == "0": # self._add_local_validation_error("analysis",self.analysis.alias,"analysisTypes", "Invalid value '%s', analysisTypeId must be '0' for alignment data." % self.analysis.analysis_type_id) # # Path: egasub/submission/submittable/base.py # def _get_md5sum(md5sum_file): # try: # checksum = open(md5sum_file, 'r').readline().rstrip() # except: # raise Md5sumFileError("Please make sure md5sum file '%s' exist" % md5sum_file) # # if not re.findall(r"^[a-fA-F\d]{32}$", checksum): # raise Md5sumFileError("Please make sure md5sum file '%s' contain valid md5sum string" % md5sum_file) # return checksum.lower() , which may include functions, classes, or code. Output only the next line.
unaligned = Unaligned(submission_dir)
Given snippet: <|code_start|> m.update("secret") file_path = "newfile" f = open(file_path,"wb") f.write(m.hexdigest()) f.close() _get_md5sum(file_path) def test_alignment(): runner = CliRunner() with runner.isolated_filesystem(): submission_dir = "test" os.mkdir(submission_dir) m = hashlib.md5() m.update("secret") md5_file = "fileName.md5" f = open(os.path.join(submission_dir,md5_file),"wb") f.write(m.hexdigest()) f.close() file_path = "analysis.yaml" with open(os.path.join(submission_dir,file_path),"w") as outfile: yaml.dump(dict( sample = dict(alias="an alias"), analysis = dict(title="a title"), files=[dict(fileName="fileName", checksumMethod="md5")]) , outfile) <|code_end|> , continue by predicting the next line. Consider current file imports: from egasub.submission.submittable import _get_md5sum, Alignment, Unaligned from click.testing import CliRunner import hashlib import os import yaml and context: # Path: egasub/submission/submittable/unaligned.py # class Unaligned(Experiment): # pass # # Path: egasub/submission/submittable/alignment.py # class Alignment(Analysis): # def __init__(self, path): # super(Alignment, self).__init__(path) # # if not re.match(r'^[a-zA-Z0-9_\-]+(\.[a-zA-Z0-9_\-]+){0,1}$', self.submission_dir): # raise Exception("Submission directory should be named as <sample alias> or <sample alias>.<lane label>, sample alias and lane label may only contain letter, digit, underscore (_) or dash (-)") # # # def local_validate(self, ega_enums): # super(Alignment, self).local_validate(ega_enums) # # Analysis type validation, 0 - Reference Alignment (BAM) # if not str(self.analysis.analysis_type_id) == "0": # self._add_local_validation_error("analysis",self.analysis.alias,"analysisTypes", "Invalid value '%s', analysisTypeId must be '0' for alignment data." % self.analysis.analysis_type_id) # # Path: egasub/submission/submittable/base.py # def _get_md5sum(md5sum_file): # try: # checksum = open(md5sum_file, 'r').readline().rstrip() # except: # raise Md5sumFileError("Please make sure md5sum file '%s' exist" % md5sum_file) # # if not re.findall(r"^[a-fA-F\d]{32}$", checksum): # raise Md5sumFileError("Please make sure md5sum file '%s' contain valid md5sum string" % md5sum_file) # return checksum.lower() which might include code, classes, or functions. Output only the next line.
alignment = Alignment(submission_dir)
Here is a snippet: <|code_start|> def test_get_md5Sum(): runner = CliRunner() with runner.isolated_filesystem(): m = hashlib.md5() m.update("secret") file_path = "newfile" f = open(file_path,"wb") f.write(m.hexdigest()) f.close() <|code_end|> . Write the next line using the current file imports: from egasub.submission.submittable import _get_md5sum, Alignment, Unaligned from click.testing import CliRunner import hashlib import os import yaml and context from other files: # Path: egasub/submission/submittable/unaligned.py # class Unaligned(Experiment): # pass # # Path: egasub/submission/submittable/alignment.py # class Alignment(Analysis): # def __init__(self, path): # super(Alignment, self).__init__(path) # # if not re.match(r'^[a-zA-Z0-9_\-]+(\.[a-zA-Z0-9_\-]+){0,1}$', self.submission_dir): # raise Exception("Submission directory should be named as <sample alias> or <sample alias>.<lane label>, sample alias and lane label may only contain letter, digit, underscore (_) or dash (-)") # # # def local_validate(self, ega_enums): # super(Alignment, self).local_validate(ega_enums) # # Analysis type validation, 0 - Reference Alignment (BAM) # if not str(self.analysis.analysis_type_id) == "0": # self._add_local_validation_error("analysis",self.analysis.alias,"analysisTypes", "Invalid value '%s', analysisTypeId must be '0' for alignment data." % self.analysis.analysis_type_id) # # Path: egasub/submission/submittable/base.py # def _get_md5sum(md5sum_file): # try: # checksum = open(md5sum_file, 'r').readline().rstrip() # except: # raise Md5sumFileError("Please make sure md5sum file '%s' exist" % md5sum_file) # # if not re.findall(r"^[a-fA-F\d]{32}$", checksum): # raise Md5sumFileError("Please make sure md5sum file '%s' contain valid md5sum string" % md5sum_file) # return checksum.lower() , which may include functions, classes, or code. Output only the next line.
_get_md5sum(file_path)
Here is a snippet: <|code_start|>#!/bin/env python # -*- coding: utf-8 -*- """ productporter.weixin.view ~~~~~~~~~~~~~~~~~ weixin backend blueprint :copyright: (c) 2014 by the ProductPorter Team. :license: BSD, see LICENSE for more details. """ weixin = Blueprint('weixin', __name__) #homepage just for fun @weixin.route('/') def index(): """ weixin backend home """ return redirect(url_for('product.posts')) @weixin.route('/mailto/<receiver>') def view_mail_daily_products(receiver): """ mail products to receiver """ <|code_end|> . Write the next line using the current file imports: import hashlib, time import xml.etree.ElementTree as ET from flask import Blueprint, request, current_app, redirect, url_for from productporter.weixin.consts import * from productporter.utils.helper import query_products, format_date, \ query_top_voted_products, query_search_products, send_mail and context from other files: # Path: productporter/utils/helper.py # def query_products(spec_day=None): # """ get all the products of the day """ # day = spec_day # if not day: # day = format_date(datetime.date.today()) # posts = Product.query.filter(Product.date==day).\ # order_by(Product.votes_count.desc()).all() # # # when not specific a day and the content is empty, we show yesterday's data # if not spec_day and len(posts) == 0: # delta = datetime.timedelta(days=-1) # d = datetime.date.today() + delta # day = format_date(d) # posts = Product.query.filter(Product.date==day).\ # order_by(Product.votes_count.desc()).all() # # # when spec_day is some old date and data is empty, we pull from PH server # if spec_day and len(posts) == 0: # today = datetime.date.today() # ymd = spec_day.split('-') # spec_date = datetime.date(int(ymd[0]), int(ymd[1]), int(ymd[2])) # if spec_date < today: # day = spec_day # pull_and_save_posts(day) # posts = Product.query.filter(Product.date==day).\ # order_by(Product.votes_count.desc()).all() # return day, posts # # def format_date(d): # """ format a datetime.date object to string """ # return '%04d-%02d-%02d' % (d.year, d.month, d.day) # # def query_top_voted_products(days_ago=2, limit=10): # """ query to voted products days ago """ # delta = datetime.timedelta(days=-days_ago) # d2 = datetime.date.today() # d1 = d2 + delta # return Product.query.filter(Product.date.between(d1, d2)).\ # order_by(Product.votes_count.desc()).limit(limit).offset(0).all() # # def query_search_products(keyword, limit=10): # """ search product in product's name and tagline """ # k = '%%%s%%' % (keyword) # return Product.query.filter(db.or_(Product.name.like(k), \ # Product.tagline.like(k))).order_by(Product.votes_count.desc()).\ # limit(limit).offset(0).all() # # def send_mail(subject, recipient, body, subtype='plain', as_attachment=False): # """ send mail """ # import smtplib # from email.mime.multipart import MIMEMultipart # from email.mime.text import MIMEText # # sender = current_app.config["MAIL_SENDER"] # smtpserver = current_app.config["MAIL_SERVER"] # username = current_app.config["MAIL_USERNAME"] # password = current_app.config["MAIL_PASSWORD"] # # # attachment # if as_attachment: # msgroot = MIMEMultipart('related') # msgroot['Subject'] = subject # att = MIMEText(body, 'base64', 'utf-8') # att["Content-Type"] = 'text/plain' # att["Content-Disposition"] = \ # 'attachment; filename="%s.txt"' % (time.strftime("%Y%m%d")) # msgroot.attach(att) # else: # msgroot = MIMEText(body, subtype, 'utf-8') # msgroot['Subject'] = subject # # smtp = smtplib.SMTP() # smtp.connect(smtpserver) # smtp.login(username, password) # smtp.sendmail(sender, recipient, msgroot.as_string()) # smtp.quit() , which may include functions, classes, or code. Output only the next line.
day, products = query_products()
Given the code snippet: <|code_start|> token = APP_TOKEN tmplist = [token, timestamp, nonce] tmplist.sort() tmpstr = ''.join(tmplist) hashstr = hashlib.sha1(tmpstr).hexdigest() if hashstr == signature: return True return False def parse_msg(rawmsgstr): """ parse message """ root = ET.fromstring(rawmsgstr) msg = {} for child in root: msg[child.tag] = child.text return msg def response_text_msg(msg, content): """ response text message """ result = TEXT_MSG_TPL % (msg['FromUserName'], msg['ToUserName'], str(int(time.time())), content) return result def response_products_msg(msg, products): """ response xml message """ result = ARTICLES_MSG_TPL_HEAD % (msg['FromUserName'], msg['ToUserName'], str(int(time.time())), len(products)) for prod in products: <|code_end|> , generate the next line using the imports in this file: import hashlib, time import xml.etree.ElementTree as ET from flask import Blueprint, request, current_app, redirect, url_for from productporter.weixin.consts import * from productporter.utils.helper import query_products, format_date, \ query_top_voted_products, query_search_products, send_mail and context (functions, classes, or occasionally code) from other files: # Path: productporter/utils/helper.py # def query_products(spec_day=None): # """ get all the products of the day """ # day = spec_day # if not day: # day = format_date(datetime.date.today()) # posts = Product.query.filter(Product.date==day).\ # order_by(Product.votes_count.desc()).all() # # # when not specific a day and the content is empty, we show yesterday's data # if not spec_day and len(posts) == 0: # delta = datetime.timedelta(days=-1) # d = datetime.date.today() + delta # day = format_date(d) # posts = Product.query.filter(Product.date==day).\ # order_by(Product.votes_count.desc()).all() # # # when spec_day is some old date and data is empty, we pull from PH server # if spec_day and len(posts) == 0: # today = datetime.date.today() # ymd = spec_day.split('-') # spec_date = datetime.date(int(ymd[0]), int(ymd[1]), int(ymd[2])) # if spec_date < today: # day = spec_day # pull_and_save_posts(day) # posts = Product.query.filter(Product.date==day).\ # order_by(Product.votes_count.desc()).all() # return day, posts # # def format_date(d): # """ format a datetime.date object to string """ # return '%04d-%02d-%02d' % (d.year, d.month, d.day) # # def query_top_voted_products(days_ago=2, limit=10): # """ query to voted products days ago """ # delta = datetime.timedelta(days=-days_ago) # d2 = datetime.date.today() # d1 = d2 + delta # return Product.query.filter(Product.date.between(d1, d2)).\ # order_by(Product.votes_count.desc()).limit(limit).offset(0).all() # # def query_search_products(keyword, limit=10): # """ search product in product's name and tagline """ # k = '%%%s%%' % (keyword) # return Product.query.filter(db.or_(Product.name.like(k), \ # Product.tagline.like(k))).order_by(Product.votes_count.desc()).\ # limit(limit).offset(0).all() # # def send_mail(subject, recipient, body, subtype='plain', as_attachment=False): # """ send mail """ # import smtplib # from email.mime.multipart import MIMEMultipart # from email.mime.text import MIMEText # # sender = current_app.config["MAIL_SENDER"] # smtpserver = current_app.config["MAIL_SERVER"] # username = current_app.config["MAIL_USERNAME"] # password = current_app.config["MAIL_PASSWORD"] # # # attachment # if as_attachment: # msgroot = MIMEMultipart('related') # msgroot['Subject'] = subject # att = MIMEText(body, 'base64', 'utf-8') # att["Content-Type"] = 'text/plain' # att["Content-Disposition"] = \ # 'attachment; filename="%s.txt"' % (time.strftime("%Y%m%d")) # msgroot.attach(att) # else: # msgroot = MIMEText(body, subtype, 'utf-8') # msgroot['Subject'] = subject # # smtp = smtplib.SMTP() # smtp.connect(smtpserver) # smtp.login(username, password) # smtp.sendmail(sender, recipient, msgroot.as_string()) # smtp.quit() . Output only the next line.
tagline = '[%s] %s' % (format_date(prod.date), prod.tagline)
Predict the next line for this snippet: <|code_start|> else: return response_text_msg(msg, ERROR_INFO) def mail_products(msg, products, receiver): """ Generate weixin href text and send to receiver """ info = "Mail sent to " + receiver if products is not None and len(products) > 0: body = "" for prod in products: item = WX_TEXT_TPL % (prod.name, prod.redirect_url, prod.tagline) body += item try: send_mail( subject='PH - ' + time.strftime("%Y%m%d"), recipient=receiver, body=body, subtype="html", as_attachment=True) except: info = "Failed to send mail to " + receiver else: info = ERROR_INFO if msg is not None: return response_text_msg(msg, info) else: return info + "\n" def push_day_top_voted_products(msg): """ push day top voted """ <|code_end|> with the help of current file imports: import hashlib, time import xml.etree.ElementTree as ET from flask import Blueprint, request, current_app, redirect, url_for from productporter.weixin.consts import * from productporter.utils.helper import query_products, format_date, \ query_top_voted_products, query_search_products, send_mail and context from other files: # Path: productporter/utils/helper.py # def query_products(spec_day=None): # """ get all the products of the day """ # day = spec_day # if not day: # day = format_date(datetime.date.today()) # posts = Product.query.filter(Product.date==day).\ # order_by(Product.votes_count.desc()).all() # # # when not specific a day and the content is empty, we show yesterday's data # if not spec_day and len(posts) == 0: # delta = datetime.timedelta(days=-1) # d = datetime.date.today() + delta # day = format_date(d) # posts = Product.query.filter(Product.date==day).\ # order_by(Product.votes_count.desc()).all() # # # when spec_day is some old date and data is empty, we pull from PH server # if spec_day and len(posts) == 0: # today = datetime.date.today() # ymd = spec_day.split('-') # spec_date = datetime.date(int(ymd[0]), int(ymd[1]), int(ymd[2])) # if spec_date < today: # day = spec_day # pull_and_save_posts(day) # posts = Product.query.filter(Product.date==day).\ # order_by(Product.votes_count.desc()).all() # return day, posts # # def format_date(d): # """ format a datetime.date object to string """ # return '%04d-%02d-%02d' % (d.year, d.month, d.day) # # def query_top_voted_products(days_ago=2, limit=10): # """ query to voted products days ago """ # delta = datetime.timedelta(days=-days_ago) # d2 = datetime.date.today() # d1 = d2 + delta # return Product.query.filter(Product.date.between(d1, d2)).\ # order_by(Product.votes_count.desc()).limit(limit).offset(0).all() # # def query_search_products(keyword, limit=10): # """ search product in product's name and tagline """ # k = '%%%s%%' % (keyword) # return Product.query.filter(db.or_(Product.name.like(k), \ # Product.tagline.like(k))).order_by(Product.votes_count.desc()).\ # limit(limit).offset(0).all() # # def send_mail(subject, recipient, body, subtype='plain', as_attachment=False): # """ send mail """ # import smtplib # from email.mime.multipart import MIMEMultipart # from email.mime.text import MIMEText # # sender = current_app.config["MAIL_SENDER"] # smtpserver = current_app.config["MAIL_SERVER"] # username = current_app.config["MAIL_USERNAME"] # password = current_app.config["MAIL_PASSWORD"] # # # attachment # if as_attachment: # msgroot = MIMEMultipart('related') # msgroot['Subject'] = subject # att = MIMEText(body, 'base64', 'utf-8') # att["Content-Type"] = 'text/plain' # att["Content-Disposition"] = \ # 'attachment; filename="%s.txt"' % (time.strftime("%Y%m%d")) # msgroot.attach(att) # else: # msgroot = MIMEText(body, subtype, 'utf-8') # msgroot['Subject'] = subject # # smtp = smtplib.SMTP() # smtp.connect(smtpserver) # smtp.login(username, password) # smtp.sendmail(sender, recipient, msgroot.as_string()) # smtp.quit() , which may contain function names, class names, or code. Output only the next line.
products = query_top_voted_products(days_ago=2, limit=10)
Predict the next line after this snippet: <|code_start|> as_attachment=True) except: info = "Failed to send mail to " + receiver else: info = ERROR_INFO if msg is not None: return response_text_msg(msg, info) else: return info + "\n" def push_day_top_voted_products(msg): """ push day top voted """ products = query_top_voted_products(days_ago=2, limit=10) return push_products(msg, products) def push_week_top_voted_products(msg): """ push week top voted """ products = query_top_voted_products(days_ago=7, limit=10) return push_products(msg, products) def push_month_top_voted_products(msg): """ push month top voted """ products = query_top_voted_products(days_ago=30, limit=10) return push_products(msg, products) def push_search_result_products(msg): """ push search result """ # skip prefix 'search:' keyword = msg['Content'][7:] <|code_end|> using the current file's imports: import hashlib, time import xml.etree.ElementTree as ET from flask import Blueprint, request, current_app, redirect, url_for from productporter.weixin.consts import * from productporter.utils.helper import query_products, format_date, \ query_top_voted_products, query_search_products, send_mail and any relevant context from other files: # Path: productporter/utils/helper.py # def query_products(spec_day=None): # """ get all the products of the day """ # day = spec_day # if not day: # day = format_date(datetime.date.today()) # posts = Product.query.filter(Product.date==day).\ # order_by(Product.votes_count.desc()).all() # # # when not specific a day and the content is empty, we show yesterday's data # if not spec_day and len(posts) == 0: # delta = datetime.timedelta(days=-1) # d = datetime.date.today() + delta # day = format_date(d) # posts = Product.query.filter(Product.date==day).\ # order_by(Product.votes_count.desc()).all() # # # when spec_day is some old date and data is empty, we pull from PH server # if spec_day and len(posts) == 0: # today = datetime.date.today() # ymd = spec_day.split('-') # spec_date = datetime.date(int(ymd[0]), int(ymd[1]), int(ymd[2])) # if spec_date < today: # day = spec_day # pull_and_save_posts(day) # posts = Product.query.filter(Product.date==day).\ # order_by(Product.votes_count.desc()).all() # return day, posts # # def format_date(d): # """ format a datetime.date object to string """ # return '%04d-%02d-%02d' % (d.year, d.month, d.day) # # def query_top_voted_products(days_ago=2, limit=10): # """ query to voted products days ago """ # delta = datetime.timedelta(days=-days_ago) # d2 = datetime.date.today() # d1 = d2 + delta # return Product.query.filter(Product.date.between(d1, d2)).\ # order_by(Product.votes_count.desc()).limit(limit).offset(0).all() # # def query_search_products(keyword, limit=10): # """ search product in product's name and tagline """ # k = '%%%s%%' % (keyword) # return Product.query.filter(db.or_(Product.name.like(k), \ # Product.tagline.like(k))).order_by(Product.votes_count.desc()).\ # limit(limit).offset(0).all() # # def send_mail(subject, recipient, body, subtype='plain', as_attachment=False): # """ send mail """ # import smtplib # from email.mime.multipart import MIMEMultipart # from email.mime.text import MIMEText # # sender = current_app.config["MAIL_SENDER"] # smtpserver = current_app.config["MAIL_SERVER"] # username = current_app.config["MAIL_USERNAME"] # password = current_app.config["MAIL_PASSWORD"] # # # attachment # if as_attachment: # msgroot = MIMEMultipart('related') # msgroot['Subject'] = subject # att = MIMEText(body, 'base64', 'utf-8') # att["Content-Type"] = 'text/plain' # att["Content-Disposition"] = \ # 'attachment; filename="%s.txt"' % (time.strftime("%Y%m%d")) # msgroot.attach(att) # else: # msgroot = MIMEText(body, subtype, 'utf-8') # msgroot['Subject'] = subject # # smtp = smtplib.SMTP() # smtp.connect(smtpserver) # smtp.login(username, password) # smtp.sendmail(sender, recipient, msgroot.as_string()) # smtp.quit() . Output only the next line.
products = query_search_products(keyword)
Based on the snippet: <|code_start|> def push_welcome_info(msg): """ push welcome info """ return response_text_msg(msg, WELCOME_INFO + HELP_INFO) def push_help_info(msg): """ push help info """ return response_text_msg(msg, HELP_INFO) def push_thanks_info(msg): """ push thanks info """ return response_text_msg(msg, THANKS_INFO) def push_products(msg, products): """ push products """ current_app.logger.info("push_products: %d products" % (len(products))) if products is not None and len(products) > 0: return response_products_msg(msg, products) else: return response_text_msg(msg, ERROR_INFO) def mail_products(msg, products, receiver): """ Generate weixin href text and send to receiver """ info = "Mail sent to " + receiver if products is not None and len(products) > 0: body = "" for prod in products: item = WX_TEXT_TPL % (prod.name, prod.redirect_url, prod.tagline) body += item try: <|code_end|> , predict the immediate next line with the help of imports: import hashlib, time import xml.etree.ElementTree as ET from flask import Blueprint, request, current_app, redirect, url_for from productporter.weixin.consts import * from productporter.utils.helper import query_products, format_date, \ query_top_voted_products, query_search_products, send_mail and context (classes, functions, sometimes code) from other files: # Path: productporter/utils/helper.py # def query_products(spec_day=None): # """ get all the products of the day """ # day = spec_day # if not day: # day = format_date(datetime.date.today()) # posts = Product.query.filter(Product.date==day).\ # order_by(Product.votes_count.desc()).all() # # # when not specific a day and the content is empty, we show yesterday's data # if not spec_day and len(posts) == 0: # delta = datetime.timedelta(days=-1) # d = datetime.date.today() + delta # day = format_date(d) # posts = Product.query.filter(Product.date==day).\ # order_by(Product.votes_count.desc()).all() # # # when spec_day is some old date and data is empty, we pull from PH server # if spec_day and len(posts) == 0: # today = datetime.date.today() # ymd = spec_day.split('-') # spec_date = datetime.date(int(ymd[0]), int(ymd[1]), int(ymd[2])) # if spec_date < today: # day = spec_day # pull_and_save_posts(day) # posts = Product.query.filter(Product.date==day).\ # order_by(Product.votes_count.desc()).all() # return day, posts # # def format_date(d): # """ format a datetime.date object to string """ # return '%04d-%02d-%02d' % (d.year, d.month, d.day) # # def query_top_voted_products(days_ago=2, limit=10): # """ query to voted products days ago """ # delta = datetime.timedelta(days=-days_ago) # d2 = datetime.date.today() # d1 = d2 + delta # return Product.query.filter(Product.date.between(d1, d2)).\ # order_by(Product.votes_count.desc()).limit(limit).offset(0).all() # # def query_search_products(keyword, limit=10): # """ search product in product's name and tagline """ # k = '%%%s%%' % (keyword) # return Product.query.filter(db.or_(Product.name.like(k), \ # Product.tagline.like(k))).order_by(Product.votes_count.desc()).\ # limit(limit).offset(0).all() # # def send_mail(subject, recipient, body, subtype='plain', as_attachment=False): # """ send mail """ # import smtplib # from email.mime.multipart import MIMEMultipart # from email.mime.text import MIMEText # # sender = current_app.config["MAIL_SENDER"] # smtpserver = current_app.config["MAIL_SERVER"] # username = current_app.config["MAIL_USERNAME"] # password = current_app.config["MAIL_PASSWORD"] # # # attachment # if as_attachment: # msgroot = MIMEMultipart('related') # msgroot['Subject'] = subject # att = MIMEText(body, 'base64', 'utf-8') # att["Content-Type"] = 'text/plain' # att["Content-Disposition"] = \ # 'attachment; filename="%s.txt"' % (time.strftime("%Y%m%d")) # msgroot.attach(att) # else: # msgroot = MIMEText(body, subtype, 'utf-8') # msgroot['Subject'] = subject # # smtp = smtplib.SMTP() # smtp.connect(smtpserver) # smtp.login(username, password) # smtp.sendmail(sender, recipient, msgroot.as_string()) # smtp.quit() . Output only the next line.
send_mail(
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- """ productporter unit test ~~~~~~~~~~~~~~~~~ :copyright: (c) 2014 by the ProductPorter Team. :license: BSD, see LICENSE for more details. """ @pytest.yield_fixture(autouse=True) def app(): """application with context.""" <|code_end|> with the help of current file imports: import pytest import os from productporter import create_app from productporter.extensions import db from productporter.configs.testing import TestingConfig as Config from productporter.utils.helper import create_default_groups and context from other files: # Path: productporter/app.py # def create_app(config=None): # """ # Creates the app. # """ # static_url_path = '' # instance_path = None # if config is None: # static_url_path = DefaultConfig.ROOT_URL_PREFIX + '/static' # instance_path = DefaultConfig.INSTANCE_PATH # else: # static_url_path = config.ROOT_URL_PREFIX + '/static' # instance_path = config.INSTANCE_PATH # # Initialize the app # app = Flask("productporter", # static_url_path=static_url_path, # instance_path=instance_path) # # # Use the default config and override it afterwards # app.config.from_object('productporter.configs.default.DefaultConfig') # # Update the config # app.config.from_object(config) # # configure_blueprints(app) # configure_extensions(app) # configure_template_filters(app) # configure_context_processors(app) # configure_before_handlers(app) # configure_errorhandlers(app) # configure_logging(app) # # return app # # Path: productporter/extensions.py # # Path: productporter/configs/testing.py # class TestingConfig(Config): # # # Indicates that it is a testing environment # DEBUG = False # TESTING = True # # SERVER_NAME = "localhost:5000" # # # Get the app root path # # <_basedir> # # ../../ --> productporter/productporter/configs/base.py # _basedir = os.path.join(os.path.abspath(os.path.dirname(os.path.dirname( # os.path.dirname(__file__))))) # # # a database named productporter.sqlite. # #SQLALCHEMY_DATABASE_URI = "mysql://root@localhost" # SQLALCHEMY_DATABASE_URI = 'sqlite:///' + _basedir + '/' + \ # 'productporter.sqlite' # # # This will print all SQL statements # SQLALCHEMY_ECHO = False # # # Security # SECRET_KEY = "SecretKeyForSessionSigning" # WTF_CSRF_ENABLED = False # WTF_CSRF_SECRET_KEY = "reallyhardtoguess" # # Path: productporter/utils/helper.py # def create_default_groups(): # """ # This will create the 5 default groups # """ # from productporter.fixtures.groups import fixture # result = [] # for key, value in fixture.items(): # group = Group(name=key) # # for k, v in value.items(): # setattr(group, k, v) # # group.save() # result.append(group) # return result , which may contain function names, class names, or code. Output only the next line.
app = create_app(Config)
Given snippet: <|code_start|># -*- coding: utf-8 -*- """ productporter unit test ~~~~~~~~~~~~~~~~~ :copyright: (c) 2014 by the ProductPorter Team. :license: BSD, see LICENSE for more details. """ @pytest.yield_fixture(autouse=True) def app(): """application with context.""" app = create_app(Config) ctx = app.app_context() ctx.push() yield app ctx.pop() @pytest.fixture() def test_client(app): """test client""" return app.test_client() @pytest.yield_fixture() def database(): """database setup.""" <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest import os from productporter import create_app from productporter.extensions import db from productporter.configs.testing import TestingConfig as Config from productporter.utils.helper import create_default_groups and context: # Path: productporter/app.py # def create_app(config=None): # """ # Creates the app. # """ # static_url_path = '' # instance_path = None # if config is None: # static_url_path = DefaultConfig.ROOT_URL_PREFIX + '/static' # instance_path = DefaultConfig.INSTANCE_PATH # else: # static_url_path = config.ROOT_URL_PREFIX + '/static' # instance_path = config.INSTANCE_PATH # # Initialize the app # app = Flask("productporter", # static_url_path=static_url_path, # instance_path=instance_path) # # # Use the default config and override it afterwards # app.config.from_object('productporter.configs.default.DefaultConfig') # # Update the config # app.config.from_object(config) # # configure_blueprints(app) # configure_extensions(app) # configure_template_filters(app) # configure_context_processors(app) # configure_before_handlers(app) # configure_errorhandlers(app) # configure_logging(app) # # return app # # Path: productporter/extensions.py # # Path: productporter/configs/testing.py # class TestingConfig(Config): # # # Indicates that it is a testing environment # DEBUG = False # TESTING = True # # SERVER_NAME = "localhost:5000" # # # Get the app root path # # <_basedir> # # ../../ --> productporter/productporter/configs/base.py # _basedir = os.path.join(os.path.abspath(os.path.dirname(os.path.dirname( # os.path.dirname(__file__))))) # # # a database named productporter.sqlite. # #SQLALCHEMY_DATABASE_URI = "mysql://root@localhost" # SQLALCHEMY_DATABASE_URI = 'sqlite:///' + _basedir + '/' + \ # 'productporter.sqlite' # # # This will print all SQL statements # SQLALCHEMY_ECHO = False # # # Security # SECRET_KEY = "SecretKeyForSessionSigning" # WTF_CSRF_ENABLED = False # WTF_CSRF_SECRET_KEY = "reallyhardtoguess" # # Path: productporter/utils/helper.py # def create_default_groups(): # """ # This will create the 5 default groups # """ # from productporter.fixtures.groups import fixture # result = [] # for key, value in fixture.items(): # group = Group(name=key) # # for k, v in value.items(): # setattr(group, k, v) # # group.save() # result.append(group) # return result which might include code, classes, or functions. Output only the next line.
db.create_all() # Maybe use migration instead?
Using the snippet: <|code_start|># -*- coding: utf-8 -*- """ productporter unit test ~~~~~~~~~~~~~~~~~ :copyright: (c) 2014 by the ProductPorter Team. :license: BSD, see LICENSE for more details. """ @pytest.yield_fixture(autouse=True) def app(): """application with context.""" <|code_end|> , determine the next line of code. You have imports: import pytest import os from productporter import create_app from productporter.extensions import db from productporter.configs.testing import TestingConfig as Config from productporter.utils.helper import create_default_groups and context (class names, function names, or code) available: # Path: productporter/app.py # def create_app(config=None): # """ # Creates the app. # """ # static_url_path = '' # instance_path = None # if config is None: # static_url_path = DefaultConfig.ROOT_URL_PREFIX + '/static' # instance_path = DefaultConfig.INSTANCE_PATH # else: # static_url_path = config.ROOT_URL_PREFIX + '/static' # instance_path = config.INSTANCE_PATH # # Initialize the app # app = Flask("productporter", # static_url_path=static_url_path, # instance_path=instance_path) # # # Use the default config and override it afterwards # app.config.from_object('productporter.configs.default.DefaultConfig') # # Update the config # app.config.from_object(config) # # configure_blueprints(app) # configure_extensions(app) # configure_template_filters(app) # configure_context_processors(app) # configure_before_handlers(app) # configure_errorhandlers(app) # configure_logging(app) # # return app # # Path: productporter/extensions.py # # Path: productporter/configs/testing.py # class TestingConfig(Config): # # # Indicates that it is a testing environment # DEBUG = False # TESTING = True # # SERVER_NAME = "localhost:5000" # # # Get the app root path # # <_basedir> # # ../../ --> productporter/productporter/configs/base.py # _basedir = os.path.join(os.path.abspath(os.path.dirname(os.path.dirname( # os.path.dirname(__file__))))) # # # a database named productporter.sqlite. # #SQLALCHEMY_DATABASE_URI = "mysql://root@localhost" # SQLALCHEMY_DATABASE_URI = 'sqlite:///' + _basedir + '/' + \ # 'productporter.sqlite' # # # This will print all SQL statements # SQLALCHEMY_ECHO = False # # # Security # SECRET_KEY = "SecretKeyForSessionSigning" # WTF_CSRF_ENABLED = False # WTF_CSRF_SECRET_KEY = "reallyhardtoguess" # # Path: productporter/utils/helper.py # def create_default_groups(): # """ # This will create the 5 default groups # """ # from productporter.fixtures.groups import fixture # result = [] # for key, value in fixture.items(): # group = Group(name=key) # # for k, v in value.items(): # setattr(group, k, v) # # group.save() # result.append(group) # return result . Output only the next line.
app = create_app(Config)
Using the snippet: <|code_start|> :copyright: (c) 2014 by the ProductPorter Team. :license: BSD, see LICENSE for more details. """ @pytest.yield_fixture(autouse=True) def app(): """application with context.""" app = create_app(Config) ctx = app.app_context() ctx.push() yield app ctx.pop() @pytest.fixture() def test_client(app): """test client""" return app.test_client() @pytest.yield_fixture() def database(): """database setup.""" db.create_all() # Maybe use migration instead? yield db db.drop_all() @pytest.fixture() def default_groups(database): """Creates the default groups""" <|code_end|> , determine the next line of code. You have imports: import pytest import os from productporter import create_app from productporter.extensions import db from productporter.configs.testing import TestingConfig as Config from productporter.utils.helper import create_default_groups and context (class names, function names, or code) available: # Path: productporter/app.py # def create_app(config=None): # """ # Creates the app. # """ # static_url_path = '' # instance_path = None # if config is None: # static_url_path = DefaultConfig.ROOT_URL_PREFIX + '/static' # instance_path = DefaultConfig.INSTANCE_PATH # else: # static_url_path = config.ROOT_URL_PREFIX + '/static' # instance_path = config.INSTANCE_PATH # # Initialize the app # app = Flask("productporter", # static_url_path=static_url_path, # instance_path=instance_path) # # # Use the default config and override it afterwards # app.config.from_object('productporter.configs.default.DefaultConfig') # # Update the config # app.config.from_object(config) # # configure_blueprints(app) # configure_extensions(app) # configure_template_filters(app) # configure_context_processors(app) # configure_before_handlers(app) # configure_errorhandlers(app) # configure_logging(app) # # return app # # Path: productporter/extensions.py # # Path: productporter/configs/testing.py # class TestingConfig(Config): # # # Indicates that it is a testing environment # DEBUG = False # TESTING = True # # SERVER_NAME = "localhost:5000" # # # Get the app root path # # <_basedir> # # ../../ --> productporter/productporter/configs/base.py # _basedir = os.path.join(os.path.abspath(os.path.dirname(os.path.dirname( # os.path.dirname(__file__))))) # # # a database named productporter.sqlite. # #SQLALCHEMY_DATABASE_URI = "mysql://root@localhost" # SQLALCHEMY_DATABASE_URI = 'sqlite:///' + _basedir + '/' + \ # 'productporter.sqlite' # # # This will print all SQL statements # SQLALCHEMY_ECHO = False # # # Security # SECRET_KEY = "SecretKeyForSessionSigning" # WTF_CSRF_ENABLED = False # WTF_CSRF_SECRET_KEY = "reallyhardtoguess" # # Path: productporter/utils/helper.py # def create_default_groups(): # """ # This will create the 5 default groups # """ # from productporter.fixtures.groups import fixture # result = [] # for key, value in fixture.items(): # group = Group(name=key) # # for k, v in value.items(): # setattr(group, k, v) # # group.save() # result.append(group) # return result . Output only the next line.
return create_default_groups()
Given snippet: <|code_start|>""" productporter ~~~~~~~~~~~~~~~~~~~~ helper for uwsgi :copyright: (c) 2014 by the ProductPorter Team. :license: BSD, see LICENSE for more details. """ <|code_end|> , continue by predicting the next line. Consider current file imports: from productporter.app import create_app from productporter.configs.production import ProductionConfig and context: # Path: productporter/app.py # def create_app(config=None): # """ # Creates the app. # """ # static_url_path = '' # instance_path = None # if config is None: # static_url_path = DefaultConfig.ROOT_URL_PREFIX + '/static' # instance_path = DefaultConfig.INSTANCE_PATH # else: # static_url_path = config.ROOT_URL_PREFIX + '/static' # instance_path = config.INSTANCE_PATH # # Initialize the app # app = Flask("productporter", # static_url_path=static_url_path, # instance_path=instance_path) # # # Use the default config and override it afterwards # app.config.from_object('productporter.configs.default.DefaultConfig') # # Update the config # app.config.from_object(config) # # configure_blueprints(app) # configure_extensions(app) # configure_template_filters(app) # configure_context_processors(app) # configure_before_handlers(app) # configure_errorhandlers(app) # configure_logging(app) # # return app which might include code, classes, or functions. Output only the next line.
app = create_app(config=ProductionConfig())
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- """ productporter.user.models ~~~~~~~~~~~~~~~~~~~~ This module provides the models for the user. :copyright: (c) 2014 by the ProductPorter Team. :license: BSD, see LICENSE for more details. """ # markdown template _MD_TEMPLATE = """## [%s](%s) > %s ![screenshot](%s) """ <|code_end|> . Write the next line using the current file imports: import re import datetime from productporter.extensions import db, cache from productporter._compat import max_integer and context from other files: # Path: productporter/extensions.py # # Path: productporter/_compat.py # PY2 = sys.version_info[0] == 2 , which may include functions, classes, or code. Output only the next line.
products_tags = db.Table(
Continue the code snippet: <|code_start|> class Tag(db.Model): __tablename__ = "tags" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(32), nullable=False) description = db.Column(db.Text) # Methods def __repr__(self): """Set to a unique key specific to the object in the database. Required for cache.memoize() to work across requests. """ return "<{} {}>".format(self.__class__.__name__, self.id) def save(self): """Saves a tag""" db.session.add(self) db.session.commit() Tag.invalidate_cache() return self def delete(self): """Deletes a tag""" db.session.delete(self) db.session.commit() Tag.invalidate_cache() return self @classmethod <|code_end|> . Use current file imports: import re import datetime from productporter.extensions import db, cache from productporter._compat import max_integer and context (classes, functions, or code) from other files: # Path: productporter/extensions.py # # Path: productporter/_compat.py # PY2 = sys.version_info[0] == 2 . Output only the next line.
@cache.memoize(timeout=max_integer)
Next line prediction: <|code_start|> class Tag(db.Model): __tablename__ = "tags" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(32), nullable=False) description = db.Column(db.Text) # Methods def __repr__(self): """Set to a unique key specific to the object in the database. Required for cache.memoize() to work across requests. """ return "<{} {}>".format(self.__class__.__name__, self.id) def save(self): """Saves a tag""" db.session.add(self) db.session.commit() Tag.invalidate_cache() return self def delete(self): """Deletes a tag""" db.session.delete(self) db.session.commit() Tag.invalidate_cache() return self @classmethod <|code_end|> . Use current file imports: (import re import datetime from productporter.extensions import db, cache from productporter._compat import max_integer) and context including class names, function names, or small code snippets from other files: # Path: productporter/extensions.py # # Path: productporter/_compat.py # PY2 = sys.version_info[0] == 2 . Output only the next line.
@cache.memoize(timeout=max_integer)
Predict the next line after this snippet: <|code_start|> """Read angles info from filename """ cpp_obj = CppObj() data = cci_nc.variables['ann_phase'][::] data = np.squeeze(data) setattr(cpp_obj, 'cpp_phase', data) # if hasattr(phase, 'mask'): # phase_out = np.where(phase.mask, -999, phase.data) # else: # phase_out = phase.data # print phase return cpp_obj def read_cci_lwp(cci_nc, cpp_obj): """ Read LWP from CCI file """ data = cci_nc.variables['cwp'][::] data = np.squeeze(data) # split LWP from CWP data = np.where(cpp_obj.cpp_phase == 2, ATRAIN_MATCH_NODATA, data) data = np.where(data < 1, ATRAIN_MATCH_NODATA, data) setattr(cpp_obj, 'cpp_lwp', data) return cpp_obj def read_cci_geoobj(cci_nc): """Read geolocation and time info from filename """ <|code_end|> using the current file's imports: from atrain_match.cloudproducts.read_pps import ( AllImagerData, CppObj, CtthObj, CmaObj, ImagerAngObj) from atrain_match.utils.runutils import do_some_geo_obj_logging import atrain_match.config as config import os import netCDF4 import numpy as np import calendar import datetime import logging and any relevant context from other files: # Path: atrain_match/cloudproducts/read_pps.py # class AllImagerData(object): # """Class to hold all imager cloudproduct data.""" # # def __init__(self, array_dict=None): # """Init with data from array_dict, or empty.""" # self.latitude = None # self.longitude = None # self.nodata = None # latlon nodata # self.sec1970_end = None # self.sec1970_start = None # self.time = None # self.num_of_lines = None # self.instrument = "imager" # # self.imager_geo = None # self.imager_angles = None # self.imager_channeldata = None # self.ctype = None # self.cma = None # self.ctth = None # self.aux = AuxiliaryObj({'surftemp': None}) # self.cpp = None # self.nwp_segments = None # if array_dict is not None: # self.__dict__.update(array_dict) # # class CppObj: # """Class to hold imager data for CPP.""" # # def __init__(self): # """Init all datasets to None.""" # self.cpp_cot = None # self.cpp_cwp = None # self.cpp_dcot = None # self.cpp_dcwp = None # self.cpp_lwp = None # self.cpp_iwp = None # self.cpp_quality = None # self.cpp_status_flag = None # self.cpp_conditions = None # self.cpp_phase = None # self.cpp_phase_extended = None # self.cpp_reff = None # # class CtthObj: # """Class to hold imager data for CTTH.""" # # def __init__(self): # """Init all datasets to None.""" # self.height = None # self.height_corr = None # self.temperature = None # self.pressure = None # self.ctth_statusflag = None # # class CmaObj: # """Class to hold imager data for CMA and CMAPROB.""" # # def __init__(self): # """Init all datasets to None.""" # self.cma_ext = None # self.cma_quality = None # self.cma_bin = None # self.cma_prob = None # self.cma_aflag = None # self.cma_testlist0 = None # new in v2018 # self.cma_testlist1 = None # new in v2018 # self.cma_testlist2 = None # new in v2018 # self.cma_testlist3 = None # new in v2018 # self.cma_testlist4 = None # new in v2018 # self.cma_testlist5 = None # new in v2018 # # class ImagerAngObj(object): # """Class to hold imager angle data.""" # # def __init__(self): # self.satz = SmallDataObject() # self.sunz = SmallDataObject() # self.satazimuth = SmallDataObject() # self.sunazimuth = SmallDataObject() # self.azidiff = SmallDataObject() # # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) . Output only the next line.
cloudproducts = AllImagerData()
Given the following code snippet before the placeholder: <|code_start|> def read_cci_cma(cci_nc): """Read cloudtype and flag info from filename """ cma = CmaObj() # cci_nc.variables['cc_total'][:]) # cci_nc.variables['ls_flag'][:]) # ctype = CtypeObj() # pps 0 cloudfree 3 cloudfree snow 1: cloudy, 2:cloudy # cci lsflag 0:sea 1:land cma.cma_ext = 0*cci_nc.variables['lsflag'][::] cma.cma_ext[cci_nc.variables['cc_total'][::] > 0.5] = 1 # ctype.landseaflag = cci_nc.variables['lsflag'][::] return cma def read_cci_angobj(cci_nc): """Read angles info from filename """ my_angle_obj = ImagerAngObj() my_angle_obj.satz.data = cci_nc.variables['satellite_zenith_view_no1'][::] my_angle_obj.sunz.data = cci_nc.variables['solar_zenith_view_no1'][::] my_angle_obj.azidiff = None # cci_nc.variables['rel_azimuth_view_no1']?? return my_angle_obj def read_cci_phase(cci_nc): """Read angles info from filename """ <|code_end|> , predict the next line using imports from the current file: from atrain_match.cloudproducts.read_pps import ( AllImagerData, CppObj, CtthObj, CmaObj, ImagerAngObj) from atrain_match.utils.runutils import do_some_geo_obj_logging import atrain_match.config as config import os import netCDF4 import numpy as np import calendar import datetime import logging and context including class names, function names, and sometimes code from other files: # Path: atrain_match/cloudproducts/read_pps.py # class AllImagerData(object): # """Class to hold all imager cloudproduct data.""" # # def __init__(self, array_dict=None): # """Init with data from array_dict, or empty.""" # self.latitude = None # self.longitude = None # self.nodata = None # latlon nodata # self.sec1970_end = None # self.sec1970_start = None # self.time = None # self.num_of_lines = None # self.instrument = "imager" # # self.imager_geo = None # self.imager_angles = None # self.imager_channeldata = None # self.ctype = None # self.cma = None # self.ctth = None # self.aux = AuxiliaryObj({'surftemp': None}) # self.cpp = None # self.nwp_segments = None # if array_dict is not None: # self.__dict__.update(array_dict) # # class CppObj: # """Class to hold imager data for CPP.""" # # def __init__(self): # """Init all datasets to None.""" # self.cpp_cot = None # self.cpp_cwp = None # self.cpp_dcot = None # self.cpp_dcwp = None # self.cpp_lwp = None # self.cpp_iwp = None # self.cpp_quality = None # self.cpp_status_flag = None # self.cpp_conditions = None # self.cpp_phase = None # self.cpp_phase_extended = None # self.cpp_reff = None # # class CtthObj: # """Class to hold imager data for CTTH.""" # # def __init__(self): # """Init all datasets to None.""" # self.height = None # self.height_corr = None # self.temperature = None # self.pressure = None # self.ctth_statusflag = None # # class CmaObj: # """Class to hold imager data for CMA and CMAPROB.""" # # def __init__(self): # """Init all datasets to None.""" # self.cma_ext = None # self.cma_quality = None # self.cma_bin = None # self.cma_prob = None # self.cma_aflag = None # self.cma_testlist0 = None # new in v2018 # self.cma_testlist1 = None # new in v2018 # self.cma_testlist2 = None # new in v2018 # self.cma_testlist3 = None # new in v2018 # self.cma_testlist4 = None # new in v2018 # self.cma_testlist5 = None # new in v2018 # # class ImagerAngObj(object): # """Class to hold imager angle data.""" # # def __init__(self): # self.satz = SmallDataObject() # self.sunz = SmallDataObject() # self.satazimuth = SmallDataObject() # self.sunazimuth = SmallDataObject() # self.azidiff = SmallDataObject() # # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) . Output only the next line.
cpp_obj = CppObj()
Next line prediction: <|code_start|> cci_nc.variables['lon'].valid_min), np.less_equal(cci_nc.variables['lon'][::], cci_nc.variables['lon'].valid_max)), cci_nc.variables['lon'][::], cloudproducts.nodata) # cloudproducts.latitude = cci_nc.variables['lat'][::] cloudproducts.latitude = np.where( np.logical_and( np.greater_equal(cci_nc.variables['lat'][::], cci_nc.variables['lat'].valid_min), np.less_equal(cci_nc.variables['lat'][::], cci_nc.variables['lat'].valid_max)), cci_nc.variables['lat'][::], cloudproducts.nodata) # For pps these are calculated in calipso.py, but better read them # from file because time are already available on arrays in the netcdf files # dsec = calendar.timegm((1993, 1, 1, 0, 0, 0, 0, 0, 0)) # TAI to UTC time_temp = daysafter4713bc_to_sec1970(cci_nc.variables['time'][::]) cloudproducts.time = time_temp[::] # [:, 0] # time_temp[:, 0] cloudproducts.sec1970_start = np.min(cloudproducts.time) cloudproducts.sec1970_end = np.max(cloudproducts.time) do_some_geo_obj_logging(cloudproducts) return cloudproducts def read_cci_ctth(cci_nc): """Read cloud top: temperature, height and pressure from filename """ <|code_end|> . Use current file imports: (from atrain_match.cloudproducts.read_pps import ( AllImagerData, CppObj, CtthObj, CmaObj, ImagerAngObj) from atrain_match.utils.runutils import do_some_geo_obj_logging import atrain_match.config as config import os import netCDF4 import numpy as np import calendar import datetime import logging) and context including class names, function names, or small code snippets from other files: # Path: atrain_match/cloudproducts/read_pps.py # class AllImagerData(object): # """Class to hold all imager cloudproduct data.""" # # def __init__(self, array_dict=None): # """Init with data from array_dict, or empty.""" # self.latitude = None # self.longitude = None # self.nodata = None # latlon nodata # self.sec1970_end = None # self.sec1970_start = None # self.time = None # self.num_of_lines = None # self.instrument = "imager" # # self.imager_geo = None # self.imager_angles = None # self.imager_channeldata = None # self.ctype = None # self.cma = None # self.ctth = None # self.aux = AuxiliaryObj({'surftemp': None}) # self.cpp = None # self.nwp_segments = None # if array_dict is not None: # self.__dict__.update(array_dict) # # class CppObj: # """Class to hold imager data for CPP.""" # # def __init__(self): # """Init all datasets to None.""" # self.cpp_cot = None # self.cpp_cwp = None # self.cpp_dcot = None # self.cpp_dcwp = None # self.cpp_lwp = None # self.cpp_iwp = None # self.cpp_quality = None # self.cpp_status_flag = None # self.cpp_conditions = None # self.cpp_phase = None # self.cpp_phase_extended = None # self.cpp_reff = None # # class CtthObj: # """Class to hold imager data for CTTH.""" # # def __init__(self): # """Init all datasets to None.""" # self.height = None # self.height_corr = None # self.temperature = None # self.pressure = None # self.ctth_statusflag = None # # class CmaObj: # """Class to hold imager data for CMA and CMAPROB.""" # # def __init__(self): # """Init all datasets to None.""" # self.cma_ext = None # self.cma_quality = None # self.cma_bin = None # self.cma_prob = None # self.cma_aflag = None # self.cma_testlist0 = None # new in v2018 # self.cma_testlist1 = None # new in v2018 # self.cma_testlist2 = None # new in v2018 # self.cma_testlist3 = None # new in v2018 # self.cma_testlist4 = None # new in v2018 # self.cma_testlist5 = None # new in v2018 # # class ImagerAngObj(object): # """Class to hold imager angle data.""" # # def __init__(self): # self.satz = SmallDataObject() # self.sunz = SmallDataObject() # self.satazimuth = SmallDataObject() # self.sunazimuth = SmallDataObject() # self.azidiff = SmallDataObject() # # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) . Output only the next line.
ctth = CtthObj()
Predict the next line for this snippet: <|code_start|> """ logger.info("Opening file %s", filename) cci_nc = netCDF4.Dataset(filename, 'r', format='NETCDF4') cloudproducts = read_cci_geoobj(cci_nc) logger.debug("Reading ctth ...") cloudproducts.ctth = read_cci_ctth(cci_nc) logger.debug("Reading angles ...") cloudproducts.imager_angles = read_cci_angobj(cci_nc) logger.debug("Reading cloud type ...") cloudproducts.cma = read_cci_cma(cci_nc) logger.debug("Reading longitude, latitude and time ...") cloudproducts.instrument = "imager" for imager in ["avhrr", "viirs", "modis", "seviri"]: if imager in os.path.basename(filename).lower(): cloudproducts.instrument = imager logger.debug("Not reading surface temperature") logger.debug("Reading cloud phase") cloudproducts.cpp = read_cci_phase(cci_nc) logger.debug("Reading LWP") cloudproducts.cpp = read_cci_lwp(cci_nc, cloudproducts.cpp) logger.debug("Not reading channel data") if cci_nc: cci_nc.close() return cloudproducts def read_cci_cma(cci_nc): """Read cloudtype and flag info from filename """ <|code_end|> with the help of current file imports: from atrain_match.cloudproducts.read_pps import ( AllImagerData, CppObj, CtthObj, CmaObj, ImagerAngObj) from atrain_match.utils.runutils import do_some_geo_obj_logging import atrain_match.config as config import os import netCDF4 import numpy as np import calendar import datetime import logging and context from other files: # Path: atrain_match/cloudproducts/read_pps.py # class AllImagerData(object): # """Class to hold all imager cloudproduct data.""" # # def __init__(self, array_dict=None): # """Init with data from array_dict, or empty.""" # self.latitude = None # self.longitude = None # self.nodata = None # latlon nodata # self.sec1970_end = None # self.sec1970_start = None # self.time = None # self.num_of_lines = None # self.instrument = "imager" # # self.imager_geo = None # self.imager_angles = None # self.imager_channeldata = None # self.ctype = None # self.cma = None # self.ctth = None # self.aux = AuxiliaryObj({'surftemp': None}) # self.cpp = None # self.nwp_segments = None # if array_dict is not None: # self.__dict__.update(array_dict) # # class CppObj: # """Class to hold imager data for CPP.""" # # def __init__(self): # """Init all datasets to None.""" # self.cpp_cot = None # self.cpp_cwp = None # self.cpp_dcot = None # self.cpp_dcwp = None # self.cpp_lwp = None # self.cpp_iwp = None # self.cpp_quality = None # self.cpp_status_flag = None # self.cpp_conditions = None # self.cpp_phase = None # self.cpp_phase_extended = None # self.cpp_reff = None # # class CtthObj: # """Class to hold imager data for CTTH.""" # # def __init__(self): # """Init all datasets to None.""" # self.height = None # self.height_corr = None # self.temperature = None # self.pressure = None # self.ctth_statusflag = None # # class CmaObj: # """Class to hold imager data for CMA and CMAPROB.""" # # def __init__(self): # """Init all datasets to None.""" # self.cma_ext = None # self.cma_quality = None # self.cma_bin = None # self.cma_prob = None # self.cma_aflag = None # self.cma_testlist0 = None # new in v2018 # self.cma_testlist1 = None # new in v2018 # self.cma_testlist2 = None # new in v2018 # self.cma_testlist3 = None # new in v2018 # self.cma_testlist4 = None # new in v2018 # self.cma_testlist5 = None # new in v2018 # # class ImagerAngObj(object): # """Class to hold imager angle data.""" # # def __init__(self): # self.satz = SmallDataObject() # self.sunz = SmallDataObject() # self.satazimuth = SmallDataObject() # self.sunazimuth = SmallDataObject() # self.azidiff = SmallDataObject() # # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) , which may contain function names, class names, or code. Output only the next line.
cma = CmaObj()
Given snippet: <|code_start|> cloudproducts.instrument = imager logger.debug("Not reading surface temperature") logger.debug("Reading cloud phase") cloudproducts.cpp = read_cci_phase(cci_nc) logger.debug("Reading LWP") cloudproducts.cpp = read_cci_lwp(cci_nc, cloudproducts.cpp) logger.debug("Not reading channel data") if cci_nc: cci_nc.close() return cloudproducts def read_cci_cma(cci_nc): """Read cloudtype and flag info from filename """ cma = CmaObj() # cci_nc.variables['cc_total'][:]) # cci_nc.variables['ls_flag'][:]) # ctype = CtypeObj() # pps 0 cloudfree 3 cloudfree snow 1: cloudy, 2:cloudy # cci lsflag 0:sea 1:land cma.cma_ext = 0*cci_nc.variables['lsflag'][::] cma.cma_ext[cci_nc.variables['cc_total'][::] > 0.5] = 1 # ctype.landseaflag = cci_nc.variables['lsflag'][::] return cma def read_cci_angobj(cci_nc): """Read angles info from filename """ <|code_end|> , continue by predicting the next line. Consider current file imports: from atrain_match.cloudproducts.read_pps import ( AllImagerData, CppObj, CtthObj, CmaObj, ImagerAngObj) from atrain_match.utils.runutils import do_some_geo_obj_logging import atrain_match.config as config import os import netCDF4 import numpy as np import calendar import datetime import logging and context: # Path: atrain_match/cloudproducts/read_pps.py # class AllImagerData(object): # """Class to hold all imager cloudproduct data.""" # # def __init__(self, array_dict=None): # """Init with data from array_dict, or empty.""" # self.latitude = None # self.longitude = None # self.nodata = None # latlon nodata # self.sec1970_end = None # self.sec1970_start = None # self.time = None # self.num_of_lines = None # self.instrument = "imager" # # self.imager_geo = None # self.imager_angles = None # self.imager_channeldata = None # self.ctype = None # self.cma = None # self.ctth = None # self.aux = AuxiliaryObj({'surftemp': None}) # self.cpp = None # self.nwp_segments = None # if array_dict is not None: # self.__dict__.update(array_dict) # # class CppObj: # """Class to hold imager data for CPP.""" # # def __init__(self): # """Init all datasets to None.""" # self.cpp_cot = None # self.cpp_cwp = None # self.cpp_dcot = None # self.cpp_dcwp = None # self.cpp_lwp = None # self.cpp_iwp = None # self.cpp_quality = None # self.cpp_status_flag = None # self.cpp_conditions = None # self.cpp_phase = None # self.cpp_phase_extended = None # self.cpp_reff = None # # class CtthObj: # """Class to hold imager data for CTTH.""" # # def __init__(self): # """Init all datasets to None.""" # self.height = None # self.height_corr = None # self.temperature = None # self.pressure = None # self.ctth_statusflag = None # # class CmaObj: # """Class to hold imager data for CMA and CMAPROB.""" # # def __init__(self): # """Init all datasets to None.""" # self.cma_ext = None # self.cma_quality = None # self.cma_bin = None # self.cma_prob = None # self.cma_aflag = None # self.cma_testlist0 = None # new in v2018 # self.cma_testlist1 = None # new in v2018 # self.cma_testlist2 = None # new in v2018 # self.cma_testlist3 = None # new in v2018 # self.cma_testlist4 = None # new in v2018 # self.cma_testlist5 = None # new in v2018 # # class ImagerAngObj(object): # """Class to hold imager angle data.""" # # def __init__(self): # self.satz = SmallDataObject() # self.sunz = SmallDataObject() # self.satazimuth = SmallDataObject() # self.sunazimuth = SmallDataObject() # self.azidiff = SmallDataObject() # # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) which might include code, classes, or functions. Output only the next line.
my_angle_obj = ImagerAngObj()
Continue the code snippet: <|code_start|> cloudproducts.longitude = cci_nc.variables['lon'][::] cloudproducts.longitude[cci_nc.variables['lon'][::] == in_fillvalue] = cloudproducts.nodata cloudproducts.latitude = cci_nc.variables['lon'][::] cloudproducts.latitude[cci_nc.variables['lon'][::] == in_fillvalue] = cloudproducts.nodata np.where( np.logical_and( np.greater_equal(cci_nc.variables['lon'][::], cci_nc.variables['lon'].valid_min), np.less_equal(cci_nc.variables['lon'][::], cci_nc.variables['lon'].valid_max)), cci_nc.variables['lon'][::], cloudproducts.nodata) # cloudproducts.latitude = cci_nc.variables['lat'][::] cloudproducts.latitude = np.where( np.logical_and( np.greater_equal(cci_nc.variables['lat'][::], cci_nc.variables['lat'].valid_min), np.less_equal(cci_nc.variables['lat'][::], cci_nc.variables['lat'].valid_max)), cci_nc.variables['lat'][::], cloudproducts.nodata) # For pps these are calculated in calipso.py, but better read them # from file because time are already available on arrays in the netcdf files # dsec = calendar.timegm((1993, 1, 1, 0, 0, 0, 0, 0, 0)) # TAI to UTC time_temp = daysafter4713bc_to_sec1970(cci_nc.variables['time'][::]) cloudproducts.time = time_temp[::] # [:, 0] # time_temp[:, 0] cloudproducts.sec1970_start = np.min(cloudproducts.time) cloudproducts.sec1970_end = np.max(cloudproducts.time) <|code_end|> . Use current file imports: from atrain_match.cloudproducts.read_pps import ( AllImagerData, CppObj, CtthObj, CmaObj, ImagerAngObj) from atrain_match.utils.runutils import do_some_geo_obj_logging import atrain_match.config as config import os import netCDF4 import numpy as np import calendar import datetime import logging and context (classes, functions, or code) from other files: # Path: atrain_match/cloudproducts/read_pps.py # class AllImagerData(object): # """Class to hold all imager cloudproduct data.""" # # def __init__(self, array_dict=None): # """Init with data from array_dict, or empty.""" # self.latitude = None # self.longitude = None # self.nodata = None # latlon nodata # self.sec1970_end = None # self.sec1970_start = None # self.time = None # self.num_of_lines = None # self.instrument = "imager" # # self.imager_geo = None # self.imager_angles = None # self.imager_channeldata = None # self.ctype = None # self.cma = None # self.ctth = None # self.aux = AuxiliaryObj({'surftemp': None}) # self.cpp = None # self.nwp_segments = None # if array_dict is not None: # self.__dict__.update(array_dict) # # class CppObj: # """Class to hold imager data for CPP.""" # # def __init__(self): # """Init all datasets to None.""" # self.cpp_cot = None # self.cpp_cwp = None # self.cpp_dcot = None # self.cpp_dcwp = None # self.cpp_lwp = None # self.cpp_iwp = None # self.cpp_quality = None # self.cpp_status_flag = None # self.cpp_conditions = None # self.cpp_phase = None # self.cpp_phase_extended = None # self.cpp_reff = None # # class CtthObj: # """Class to hold imager data for CTTH.""" # # def __init__(self): # """Init all datasets to None.""" # self.height = None # self.height_corr = None # self.temperature = None # self.pressure = None # self.ctth_statusflag = None # # class CmaObj: # """Class to hold imager data for CMA and CMAPROB.""" # # def __init__(self): # """Init all datasets to None.""" # self.cma_ext = None # self.cma_quality = None # self.cma_bin = None # self.cma_prob = None # self.cma_aflag = None # self.cma_testlist0 = None # new in v2018 # self.cma_testlist1 = None # new in v2018 # self.cma_testlist2 = None # new in v2018 # self.cma_testlist3 = None # new in v2018 # self.cma_testlist4 = None # new in v2018 # self.cma_testlist5 = None # new in v2018 # # class ImagerAngObj(object): # """Class to hold imager angle data.""" # # def __init__(self): # self.satz = SmallDataObject() # self.sunz = SmallDataObject() # self.satazimuth = SmallDataObject() # self.sunazimuth = SmallDataObject() # self.azidiff = SmallDataObject() # # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) . Output only the next line.
do_some_geo_obj_logging(cloudproducts)
Next line prediction: <|code_start|> if atrain_match_name in ["snow_ice_surface_type"]: atrain_match_name = "nsidc_surface_type" setattr(data_obj, atrain_match_name, group[dataset][...]) retv.diff_sec_1970 = h5file['diff_sec_1970'][...] h5file.close() return retv def read_files(files, truth='calipso', read_all=True, read_var=[], skip_var=[]): my_files = files.copy() tObj = read_truth_imager_match_obj(my_files.pop(), truth=truth, read_all=read_all, read_var=read_var, skip_var=skip_var) if len(my_files) > 0: for filename in my_files: tObj += read_truth_imager_match_obj(filename, truth=truth, read_all=read_all, read_var=read_var, skip_var=skip_var) return tObj # write matchup files def write_truth_imager_match_obj(filename, match_obj, SETTINGS=None, imager_obj_name='pps'): """Write *match_obj* to *filename*.""" datasets = {'diff_sec_1970': match_obj.diff_sec_1970} groups = {imager_obj_name: match_obj.imager.all_arrays} imager_attrs = {'imager_instrument': match_obj.imager_instrument} groups_attrs = {imager_obj_name: imager_attrs} for name in ['calipso', 'calipso_aerosol', 'iss', 'modis_lvl2', 'amsr', 'synop', 'mora', 'cloudsat', 'extra']: if hasattr(match_obj, name): groups[name] = getattr(match_obj, name).all_arrays <|code_end|> . Use current file imports: (import numpy as np import h5py import os.path from atrain_match.utils.common import write_match_objects from scipy.ndimage.filters import uniform_filter) and context including class names, function names, or small code snippets from other files: # Path: atrain_match/utils/common.py # def write_match_objects(filename, datasets, groups, group_attrs_dict, SETTINGS=None): # """Write match objects to HDF5 file *filename*. # # Arguments: # # *diff_sec_1970*: `numpy.ndarray` # time diff between matched satellites # *groups*: dict # each key/value pair should hold a list of `numpy.ndarray` instances # to be written under HDF5 group with the same name as the key # # E.g. to write a calipso match: # # >>> groups = {'calipso': ca_obj.calipso.all_arrays, # ... 'imager': ca_obj.imager.all_arrays} # >>> write_match_objects('match.h5', ca_obj.diff_sec_1970, groups) # # The match object data can then be read using `read_match_objects`: # # >>> diff_sec_1970, groups = read_match_objects('match.h5') # # """ # from atrain_match.config import COMPRESS_LVL # import h5py # from atrain_match.matchobject_io import the_used_variables # with h5py.File(filename, 'w') as f: # for name in datasets.keys(): # f.create_dataset(name, data=datasets[name], # compression=COMPRESS_LVL) # # for group_name, group_object in groups.items(): # if SETTINGS is not None and group_name in ['calipso', # 'calipso_aerosol' # 'cloudsat', # 'iss', # 'mora', # 'synop']: # skip_some = SETTINGS["WRITE_ONLY_THE_MOST_IMPORTANT_STUFF_TO_FILE"] # else: # #modis_lvl2, pps, oca, patmosx, or maia # skip_some = False # # try: # attrs_dict = group_attrs_dict[group_name] # except KeyError: # attrs_dict = {} # g = f.create_group(group_name) # for key in attrs_dict: # g.attrs[key] = attrs_dict[key] # for array_name, array in group_object.items(): # if array is None: # continue # if (skip_some and # array_name not in the_used_variables): # logger.debug("Not writing unimportant %s to file", # array_name) # continue # # if len(array) == 0: # continue # # Scalar data can't be compressed # # TODO: Write it as and attribute instead? # # g.create_dataset(array_name, data=array) # else: # # print("writing", array_name) # g.create_dataset(array_name, data=array, # compression=COMPRESS_LVL) . Output only the next line.
write_match_objects(filename, datasets, groups, groups_attrs, SETTINGS=SETTINGS)
Given the following code snippet before the placeholder: <|code_start|> ctype.ct_conditions = None return ctype, cma, ctth def read_patmosx_angobj(patmosx_nc): """Read angles info from filename.""" angle_obj = ImagerAngObj() angle_obj.satz.data = patmosx_nc.variables['sensor_zenith_angle'][0, :, :].astype(np.float) angle_obj.sunz.data = patmosx_nc.variables['solar_zenith_angle'][0, :, :].astype(np.float) angle_obj.azidiff.data = None return angle_obj def read_patmosx_geoobj(patmosx_nc, filename, cross, SETTINGS): """Read geolocation and time info from filename.""" cloudproducts = AllImagerData() latitude_v = patmosx_nc.variables['latitude'][:].astype(np.float) longitude_v = patmosx_nc.variables['longitude'][:].astype(np.float) cloudproducts.latitude = np.repeat(latitude_v[:, np.newaxis], len(longitude_v), axis=1) cloudproducts.longitude = np.repeat(longitude_v[np.newaxis, :], len(latitude_v), axis=0) cloudproducts.nodata = -999 date_time_start = cross.time date_time_end = cross.time + timedelta(seconds=SETTINGS['SAT_ORBIT_DURATION']) cloudproducts.sec1970_start = calendar.timegm(date_time_start.timetuple()) cloudproducts.sec1970_end = calendar.timegm(date_time_end.timetuple()) frac_hour = patmosx_nc.variables['scan_line_time'][0, :, :].astype(np.float) if np.ma.is_masked(frac_hour): frac_hour = frac_hour.data seconds = frac_hour*60*60.0 cloudproducts.time = seconds + patmosx_nc.variables['time'] <|code_end|> , predict the next line using imports from the current file: import atrain_match.config as config import os import netCDF4 import numpy as np import calendar import logging from atrain_match.utils.runutils import do_some_geo_obj_logging from atrain_match.cloudproducts.read_pps import ( AllImagerData, CtypeObj, CtthObj, CmaObj, ImagerAngObj) from datetime import datetime from datetime import timedelta from pyhdf.SD import SD, SDC and context including class names, function names, and sometimes code from other files: # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) # # Path: atrain_match/cloudproducts/read_pps.py # class AllImagerData(object): # """Class to hold all imager cloudproduct data.""" # # def __init__(self, array_dict=None): # """Init with data from array_dict, or empty.""" # self.latitude = None # self.longitude = None # self.nodata = None # latlon nodata # self.sec1970_end = None # self.sec1970_start = None # self.time = None # self.num_of_lines = None # self.instrument = "imager" # # self.imager_geo = None # self.imager_angles = None # self.imager_channeldata = None # self.ctype = None # self.cma = None # self.ctth = None # self.aux = AuxiliaryObj({'surftemp': None}) # self.cpp = None # self.nwp_segments = None # if array_dict is not None: # self.__dict__.update(array_dict) # # class CtypeObj: # """Class to hold imager data for cloud type.""" # # def __init__(self): # """Init all datasets to None.""" # self.cloudtype = None # self.ct_statusflag = None # self.ct_quality = None # self.ct_conditions = None # self.phaseflag = None # v2012 # # class CtthObj: # """Class to hold imager data for CTTH.""" # # def __init__(self): # """Init all datasets to None.""" # self.height = None # self.height_corr = None # self.temperature = None # self.pressure = None # self.ctth_statusflag = None # # class CmaObj: # """Class to hold imager data for CMA and CMAPROB.""" # # def __init__(self): # """Init all datasets to None.""" # self.cma_ext = None # self.cma_quality = None # self.cma_bin = None # self.cma_prob = None # self.cma_aflag = None # self.cma_testlist0 = None # new in v2018 # self.cma_testlist1 = None # new in v2018 # self.cma_testlist2 = None # new in v2018 # self.cma_testlist3 = None # new in v2018 # self.cma_testlist4 = None # new in v2018 # self.cma_testlist5 = None # new in v2018 # # class ImagerAngObj(object): # """Class to hold imager angle data.""" # # def __init__(self): # self.satz = SmallDataObject() # self.sunz = SmallDataObject() # self.satazimuth = SmallDataObject() # self.sunazimuth = SmallDataObject() # self.azidiff = SmallDataObject() . Output only the next line.
do_some_geo_obj_logging(cloudproducts)
Continue the code snippet: <|code_start|> """Read cloudtype and flag info from filename.""" ctth = CtthObj() ctype = CtypeObj() cma = CmaObj() ctth.height = patmosx_nc.variables['cld_height_acha'][0, :, :].astype(np.float) ctth.h_nodata = patmosx_nc.variables['cld_height_acha']._FillValue if np.ma.is_masked(ctth.height): ctth.height.data[ctth.height.mask] = ATRAIN_MATCH_NODATA ctth.height = ctth.height.data ctth.height = 1000*ctth.height cf = patmosx_nc.variables['cloud_fraction'][0, :, :].astype(np.float) cma.cma_ext = np.where(cf >= 0.5, 1, 0) if np.ma.is_masked(cf): cma.cma_ext[cf.mask] = 255 ctype.phaseflag = None ctype.ct_conditions = None return ctype, cma, ctth def read_patmosx_angobj(patmosx_nc): """Read angles info from filename.""" angle_obj = ImagerAngObj() angle_obj.satz.data = patmosx_nc.variables['sensor_zenith_angle'][0, :, :].astype(np.float) angle_obj.sunz.data = patmosx_nc.variables['solar_zenith_angle'][0, :, :].astype(np.float) angle_obj.azidiff.data = None return angle_obj def read_patmosx_geoobj(patmosx_nc, filename, cross, SETTINGS): """Read geolocation and time info from filename.""" <|code_end|> . Use current file imports: import atrain_match.config as config import os import netCDF4 import numpy as np import calendar import logging from atrain_match.utils.runutils import do_some_geo_obj_logging from atrain_match.cloudproducts.read_pps import ( AllImagerData, CtypeObj, CtthObj, CmaObj, ImagerAngObj) from datetime import datetime from datetime import timedelta from pyhdf.SD import SD, SDC and context (classes, functions, or code) from other files: # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) # # Path: atrain_match/cloudproducts/read_pps.py # class AllImagerData(object): # """Class to hold all imager cloudproduct data.""" # # def __init__(self, array_dict=None): # """Init with data from array_dict, or empty.""" # self.latitude = None # self.longitude = None # self.nodata = None # latlon nodata # self.sec1970_end = None # self.sec1970_start = None # self.time = None # self.num_of_lines = None # self.instrument = "imager" # # self.imager_geo = None # self.imager_angles = None # self.imager_channeldata = None # self.ctype = None # self.cma = None # self.ctth = None # self.aux = AuxiliaryObj({'surftemp': None}) # self.cpp = None # self.nwp_segments = None # if array_dict is not None: # self.__dict__.update(array_dict) # # class CtypeObj: # """Class to hold imager data for cloud type.""" # # def __init__(self): # """Init all datasets to None.""" # self.cloudtype = None # self.ct_statusflag = None # self.ct_quality = None # self.ct_conditions = None # self.phaseflag = None # v2012 # # class CtthObj: # """Class to hold imager data for CTTH.""" # # def __init__(self): # """Init all datasets to None.""" # self.height = None # self.height_corr = None # self.temperature = None # self.pressure = None # self.ctth_statusflag = None # # class CmaObj: # """Class to hold imager data for CMA and CMAPROB.""" # # def __init__(self): # """Init all datasets to None.""" # self.cma_ext = None # self.cma_quality = None # self.cma_bin = None # self.cma_prob = None # self.cma_aflag = None # self.cma_testlist0 = None # new in v2018 # self.cma_testlist1 = None # new in v2018 # self.cma_testlist2 = None # new in v2018 # self.cma_testlist3 = None # new in v2018 # self.cma_testlist4 = None # new in v2018 # self.cma_testlist5 = None # new in v2018 # # class ImagerAngObj(object): # """Class to hold imager angle data.""" # # def __init__(self): # self.satz = SmallDataObject() # self.sunz = SmallDataObject() # self.satazimuth = SmallDataObject() # self.sunazimuth = SmallDataObject() # self.azidiff = SmallDataObject() . Output only the next line.
cloudproducts = AllImagerData()
Next line prediction: <|code_start|> if ".nc" in filename: return patmosx_read_all_nc(filename, cross, SETTINGS) else: return patmosx_read_all_hdf(filename, cross, SETTINGS) def patmosx_read_all_nc(filename, cross, SETTINGS): """Read geolocation, angles info, ctth, and cma.""" patmosx_nc = netCDF4.Dataset(filename, 'r', format='NETCDF4') logger.info("Opening file %s", filename) logger.info("Reading longitude, latitude and time ...") cloudproducts = read_patmosx_geoobj(patmosx_nc, filename, cross, SETTINGS) logger.info("Reading angles ...") cloudproducts.imager_angles = read_patmosx_angobj(patmosx_nc) logger.info("Reading cloud type ...") # , angle_obj) ctype, cma, ctth = read_patmosx_ctype_cmask_ctth(patmosx_nc) cloudproducts.cma = cma cloudproducts.ctth = ctth cloudproducts.ctype = ctype logger.info("Not reading surface temperature") logger.info("Not reading cloud microphysical properties") logger.info("Not reading channel data") return cloudproducts def read_patmosx_ctype_cmask_ctth(patmosx_nc): """Read cloudtype and flag info from filename.""" ctth = CtthObj() <|code_end|> . Use current file imports: (import atrain_match.config as config import os import netCDF4 import numpy as np import calendar import logging from atrain_match.utils.runutils import do_some_geo_obj_logging from atrain_match.cloudproducts.read_pps import ( AllImagerData, CtypeObj, CtthObj, CmaObj, ImagerAngObj) from datetime import datetime from datetime import timedelta from pyhdf.SD import SD, SDC) and context including class names, function names, or small code snippets from other files: # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) # # Path: atrain_match/cloudproducts/read_pps.py # class AllImagerData(object): # """Class to hold all imager cloudproduct data.""" # # def __init__(self, array_dict=None): # """Init with data from array_dict, or empty.""" # self.latitude = None # self.longitude = None # self.nodata = None # latlon nodata # self.sec1970_end = None # self.sec1970_start = None # self.time = None # self.num_of_lines = None # self.instrument = "imager" # # self.imager_geo = None # self.imager_angles = None # self.imager_channeldata = None # self.ctype = None # self.cma = None # self.ctth = None # self.aux = AuxiliaryObj({'surftemp': None}) # self.cpp = None # self.nwp_segments = None # if array_dict is not None: # self.__dict__.update(array_dict) # # class CtypeObj: # """Class to hold imager data for cloud type.""" # # def __init__(self): # """Init all datasets to None.""" # self.cloudtype = None # self.ct_statusflag = None # self.ct_quality = None # self.ct_conditions = None # self.phaseflag = None # v2012 # # class CtthObj: # """Class to hold imager data for CTTH.""" # # def __init__(self): # """Init all datasets to None.""" # self.height = None # self.height_corr = None # self.temperature = None # self.pressure = None # self.ctth_statusflag = None # # class CmaObj: # """Class to hold imager data for CMA and CMAPROB.""" # # def __init__(self): # """Init all datasets to None.""" # self.cma_ext = None # self.cma_quality = None # self.cma_bin = None # self.cma_prob = None # self.cma_aflag = None # self.cma_testlist0 = None # new in v2018 # self.cma_testlist1 = None # new in v2018 # self.cma_testlist2 = None # new in v2018 # self.cma_testlist3 = None # new in v2018 # self.cma_testlist4 = None # new in v2018 # self.cma_testlist5 = None # new in v2018 # # class ImagerAngObj(object): # """Class to hold imager angle data.""" # # def __init__(self): # self.satz = SmallDataObject() # self.sunz = SmallDataObject() # self.satazimuth = SmallDataObject() # self.sunazimuth = SmallDataObject() # self.azidiff = SmallDataObject() . Output only the next line.
ctype = CtypeObj()
Based on the snippet: <|code_start|>def patmosx_read_all(filename, cross, SETTINGS): if ".nc" in filename: return patmosx_read_all_nc(filename, cross, SETTINGS) else: return patmosx_read_all_hdf(filename, cross, SETTINGS) def patmosx_read_all_nc(filename, cross, SETTINGS): """Read geolocation, angles info, ctth, and cma.""" patmosx_nc = netCDF4.Dataset(filename, 'r', format='NETCDF4') logger.info("Opening file %s", filename) logger.info("Reading longitude, latitude and time ...") cloudproducts = read_patmosx_geoobj(patmosx_nc, filename, cross, SETTINGS) logger.info("Reading angles ...") cloudproducts.imager_angles = read_patmosx_angobj(patmosx_nc) logger.info("Reading cloud type ...") # , angle_obj) ctype, cma, ctth = read_patmosx_ctype_cmask_ctth(patmosx_nc) cloudproducts.cma = cma cloudproducts.ctth = ctth cloudproducts.ctype = ctype logger.info("Not reading surface temperature") logger.info("Not reading cloud microphysical properties") logger.info("Not reading channel data") return cloudproducts def read_patmosx_ctype_cmask_ctth(patmosx_nc): """Read cloudtype and flag info from filename.""" <|code_end|> , predict the immediate next line with the help of imports: import atrain_match.config as config import os import netCDF4 import numpy as np import calendar import logging from atrain_match.utils.runutils import do_some_geo_obj_logging from atrain_match.cloudproducts.read_pps import ( AllImagerData, CtypeObj, CtthObj, CmaObj, ImagerAngObj) from datetime import datetime from datetime import timedelta from pyhdf.SD import SD, SDC and context (classes, functions, sometimes code) from other files: # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) # # Path: atrain_match/cloudproducts/read_pps.py # class AllImagerData(object): # """Class to hold all imager cloudproduct data.""" # # def __init__(self, array_dict=None): # """Init with data from array_dict, or empty.""" # self.latitude = None # self.longitude = None # self.nodata = None # latlon nodata # self.sec1970_end = None # self.sec1970_start = None # self.time = None # self.num_of_lines = None # self.instrument = "imager" # # self.imager_geo = None # self.imager_angles = None # self.imager_channeldata = None # self.ctype = None # self.cma = None # self.ctth = None # self.aux = AuxiliaryObj({'surftemp': None}) # self.cpp = None # self.nwp_segments = None # if array_dict is not None: # self.__dict__.update(array_dict) # # class CtypeObj: # """Class to hold imager data for cloud type.""" # # def __init__(self): # """Init all datasets to None.""" # self.cloudtype = None # self.ct_statusflag = None # self.ct_quality = None # self.ct_conditions = None # self.phaseflag = None # v2012 # # class CtthObj: # """Class to hold imager data for CTTH.""" # # def __init__(self): # """Init all datasets to None.""" # self.height = None # self.height_corr = None # self.temperature = None # self.pressure = None # self.ctth_statusflag = None # # class CmaObj: # """Class to hold imager data for CMA and CMAPROB.""" # # def __init__(self): # """Init all datasets to None.""" # self.cma_ext = None # self.cma_quality = None # self.cma_bin = None # self.cma_prob = None # self.cma_aflag = None # self.cma_testlist0 = None # new in v2018 # self.cma_testlist1 = None # new in v2018 # self.cma_testlist2 = None # new in v2018 # self.cma_testlist3 = None # new in v2018 # self.cma_testlist4 = None # new in v2018 # self.cma_testlist5 = None # new in v2018 # # class ImagerAngObj(object): # """Class to hold imager angle data.""" # # def __init__(self): # self.satz = SmallDataObject() # self.sunz = SmallDataObject() # self.satazimuth = SmallDataObject() # self.sunazimuth = SmallDataObject() # self.azidiff = SmallDataObject() . Output only the next line.
ctth = CtthObj()
Given snippet: <|code_start|> return patmosx_read_all_nc(filename, cross, SETTINGS) else: return patmosx_read_all_hdf(filename, cross, SETTINGS) def patmosx_read_all_nc(filename, cross, SETTINGS): """Read geolocation, angles info, ctth, and cma.""" patmosx_nc = netCDF4.Dataset(filename, 'r', format='NETCDF4') logger.info("Opening file %s", filename) logger.info("Reading longitude, latitude and time ...") cloudproducts = read_patmosx_geoobj(patmosx_nc, filename, cross, SETTINGS) logger.info("Reading angles ...") cloudproducts.imager_angles = read_patmosx_angobj(patmosx_nc) logger.info("Reading cloud type ...") # , angle_obj) ctype, cma, ctth = read_patmosx_ctype_cmask_ctth(patmosx_nc) cloudproducts.cma = cma cloudproducts.ctth = ctth cloudproducts.ctype = ctype logger.info("Not reading surface temperature") logger.info("Not reading cloud microphysical properties") logger.info("Not reading channel data") return cloudproducts def read_patmosx_ctype_cmask_ctth(patmosx_nc): """Read cloudtype and flag info from filename.""" ctth = CtthObj() ctype = CtypeObj() <|code_end|> , continue by predicting the next line. Consider current file imports: import atrain_match.config as config import os import netCDF4 import numpy as np import calendar import logging from atrain_match.utils.runutils import do_some_geo_obj_logging from atrain_match.cloudproducts.read_pps import ( AllImagerData, CtypeObj, CtthObj, CmaObj, ImagerAngObj) from datetime import datetime from datetime import timedelta from pyhdf.SD import SD, SDC and context: # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) # # Path: atrain_match/cloudproducts/read_pps.py # class AllImagerData(object): # """Class to hold all imager cloudproduct data.""" # # def __init__(self, array_dict=None): # """Init with data from array_dict, or empty.""" # self.latitude = None # self.longitude = None # self.nodata = None # latlon nodata # self.sec1970_end = None # self.sec1970_start = None # self.time = None # self.num_of_lines = None # self.instrument = "imager" # # self.imager_geo = None # self.imager_angles = None # self.imager_channeldata = None # self.ctype = None # self.cma = None # self.ctth = None # self.aux = AuxiliaryObj({'surftemp': None}) # self.cpp = None # self.nwp_segments = None # if array_dict is not None: # self.__dict__.update(array_dict) # # class CtypeObj: # """Class to hold imager data for cloud type.""" # # def __init__(self): # """Init all datasets to None.""" # self.cloudtype = None # self.ct_statusflag = None # self.ct_quality = None # self.ct_conditions = None # self.phaseflag = None # v2012 # # class CtthObj: # """Class to hold imager data for CTTH.""" # # def __init__(self): # """Init all datasets to None.""" # self.height = None # self.height_corr = None # self.temperature = None # self.pressure = None # self.ctth_statusflag = None # # class CmaObj: # """Class to hold imager data for CMA and CMAPROB.""" # # def __init__(self): # """Init all datasets to None.""" # self.cma_ext = None # self.cma_quality = None # self.cma_bin = None # self.cma_prob = None # self.cma_aflag = None # self.cma_testlist0 = None # new in v2018 # self.cma_testlist1 = None # new in v2018 # self.cma_testlist2 = None # new in v2018 # self.cma_testlist3 = None # new in v2018 # self.cma_testlist4 = None # new in v2018 # self.cma_testlist5 = None # new in v2018 # # class ImagerAngObj(object): # """Class to hold imager angle data.""" # # def __init__(self): # self.satz = SmallDataObject() # self.sunz = SmallDataObject() # self.satazimuth = SmallDataObject() # self.sunazimuth = SmallDataObject() # self.azidiff = SmallDataObject() which might include code, classes, or functions. Output only the next line.
cma = CmaObj()
Predict the next line for this snippet: <|code_start|> cloudproducts.ctype = ctype logger.info("Not reading surface temperature") logger.info("Not reading cloud microphysical properties") logger.info("Not reading channel data") return cloudproducts def read_patmosx_ctype_cmask_ctth(patmosx_nc): """Read cloudtype and flag info from filename.""" ctth = CtthObj() ctype = CtypeObj() cma = CmaObj() ctth.height = patmosx_nc.variables['cld_height_acha'][0, :, :].astype(np.float) ctth.h_nodata = patmosx_nc.variables['cld_height_acha']._FillValue if np.ma.is_masked(ctth.height): ctth.height.data[ctth.height.mask] = ATRAIN_MATCH_NODATA ctth.height = ctth.height.data ctth.height = 1000*ctth.height cf = patmosx_nc.variables['cloud_fraction'][0, :, :].astype(np.float) cma.cma_ext = np.where(cf >= 0.5, 1, 0) if np.ma.is_masked(cf): cma.cma_ext[cf.mask] = 255 ctype.phaseflag = None ctype.ct_conditions = None return ctype, cma, ctth def read_patmosx_angobj(patmosx_nc): """Read angles info from filename.""" <|code_end|> with the help of current file imports: import atrain_match.config as config import os import netCDF4 import numpy as np import calendar import logging from atrain_match.utils.runutils import do_some_geo_obj_logging from atrain_match.cloudproducts.read_pps import ( AllImagerData, CtypeObj, CtthObj, CmaObj, ImagerAngObj) from datetime import datetime from datetime import timedelta from pyhdf.SD import SD, SDC and context from other files: # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) # # Path: atrain_match/cloudproducts/read_pps.py # class AllImagerData(object): # """Class to hold all imager cloudproduct data.""" # # def __init__(self, array_dict=None): # """Init with data from array_dict, or empty.""" # self.latitude = None # self.longitude = None # self.nodata = None # latlon nodata # self.sec1970_end = None # self.sec1970_start = None # self.time = None # self.num_of_lines = None # self.instrument = "imager" # # self.imager_geo = None # self.imager_angles = None # self.imager_channeldata = None # self.ctype = None # self.cma = None # self.ctth = None # self.aux = AuxiliaryObj({'surftemp': None}) # self.cpp = None # self.nwp_segments = None # if array_dict is not None: # self.__dict__.update(array_dict) # # class CtypeObj: # """Class to hold imager data for cloud type.""" # # def __init__(self): # """Init all datasets to None.""" # self.cloudtype = None # self.ct_statusflag = None # self.ct_quality = None # self.ct_conditions = None # self.phaseflag = None # v2012 # # class CtthObj: # """Class to hold imager data for CTTH.""" # # def __init__(self): # """Init all datasets to None.""" # self.height = None # self.height_corr = None # self.temperature = None # self.pressure = None # self.ctth_statusflag = None # # class CmaObj: # """Class to hold imager data for CMA and CMAPROB.""" # # def __init__(self): # """Init all datasets to None.""" # self.cma_ext = None # self.cma_quality = None # self.cma_bin = None # self.cma_prob = None # self.cma_aflag = None # self.cma_testlist0 = None # new in v2018 # self.cma_testlist1 = None # new in v2018 # self.cma_testlist2 = None # new in v2018 # self.cma_testlist3 = None # new in v2018 # self.cma_testlist4 = None # new in v2018 # self.cma_testlist5 = None # new in v2018 # # class ImagerAngObj(object): # """Class to hold imager angle data.""" # # def __init__(self): # self.satz = SmallDataObject() # self.sunz = SmallDataObject() # self.satazimuth = SmallDataObject() # self.sunazimuth = SmallDataObject() # self.azidiff = SmallDataObject() , which may contain function names, class names, or code. Output only the next line.
angle_obj = ImagerAngObj()
Next line prediction: <|code_start|> @property def cols(self): # self._cols = np.array(self._cols, dtype=np.int64) return np.ma.array(self._cols, mask=self.mask, fill_value=-NODATA, hard_mask=True) @property def time_diff(self): """Time difference in seconds""" if self._time_diff is None: return None # Only use pixel mask return np.ma.array(self._time_diff, mask=self._pixel_mask, fill_value=np.inf, hard_mask=True) @time_diff.setter def time_diff(self, value): self._time_diff = value @property def mask(self): if None not in (self.time_diff, self.time_threshold): return (self._pixel_mask + (abs(self.time_diff) > self.time_threshold)) return self._pixel_mask def match_lonlat(source, target, <|code_end|> . Use current file imports: (import numpy as np import logging from atrain_match.config import RESOLUTION, NODATA from pyresample.geometry import SwathDefinition from pyresample.kd_tree import get_neighbour_info from pyresample.kd_tree import get_sample_from_neighbour_info) and context including class names, function names, or small code snippets from other files: # Path: atrain_match/config.py # RESOLUTION = int(os.environ.get('ATRAIN_RESOLUTION', 5)) # # NODATA = -9 . Output only the next line.
radius_of_influence=0.7*RESOLUTION*1000.0,
Based on the snippet: <|code_start|># along with atrain_match. If not, see <http://www.gnu.org/licenses/>. """Match TRUTH and IMAGER data.""" # from __future__ import with_statement logger = logging.getLogger(__name__) class MatchMapper(object): """ Map arrays from one swath to another. Note that MatchMapper always works with an extra dimension: neighbour """ def __init__(self, rows, cols, pixel_mask, time_diff=None, time_threshold=None): self._rows = np.array(rows).astype(np.int) self._cols = np.array(cols).astype(np.int) self._pixel_mask = pixel_mask self._time_diff = time_diff self.time_threshold = time_threshold def __call__(self, array): """Maps *array* to target swath.""" return np.ma.array(array[self.rows, self.cols], mask=self.mask) @property def rows(self): # self._rows = np.array(self._rows, dtype=np.int64) <|code_end|> , predict the immediate next line with the help of imports: import numpy as np import logging from atrain_match.config import RESOLUTION, NODATA from pyresample.geometry import SwathDefinition from pyresample.kd_tree import get_neighbour_info from pyresample.kd_tree import get_sample_from_neighbour_info and context (classes, functions, sometimes code) from other files: # Path: atrain_match/config.py # RESOLUTION = int(os.environ.get('ATRAIN_RESOLUTION', 5)) # # NODATA = -9 . Output only the next line.
return np.ma.array(self._rows, mask=self.mask, fill_value=NODATA,
Predict the next line for this snippet: <|code_start|> size=5, mode='constant', cval=-9999999999999) flat_index = np.array(flat_index, dtype=np.int) delta_row, delta_col = np.unravel_index(flat_index, (5, 5)) delta_row = delta_row - 2 delta_col = delta_col - 2 new_row = row + delta_row new_col = col + delta_col new_row_matched = np.array([new_row[matched['row'][idx], matched['col'][idx]] for idx in range(matched['row'].shape[0])]) new_col_matched = np.array([new_col[matched['row'][idx], matched['col'][idx]] for idx in range(matched['row'].shape[0])]) return new_row_matched, new_col_matched class test_prototyping_utils(unittest.TestCase): def setUp(self): self.t11 = np.array([[1, 43, 3, 4, 5, 6, 7, 8, 9, 35], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 25, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5, 6, 7, 8, 9, 101], [11, 2, 3, 4, 5, 6, 7, 8, 9, 101]]) self.matched = {'row': np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4]), 'col': np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])} def test_warmest(self): <|code_end|> with the help of current file imports: import numpy as np import unittest from atrain_match.utils.pps_prototyping_util import (get_warmest_or_coldest_index) from atrain_match.utils import match from scipy.ndimage.filters import generic_filter from pyresample.geometry import SwathDefinition from pyresample.kd_tree import get_neighbour_info and context from other files: # Path: atrain_match/utils/pps_prototyping_util.py # def get_warmest_or_coldest_index(t11, matched, warmest=True): # """Get index for coldedest pixel in 5x5 neighbourhood.""" # FILL = 999999.9 # coldest # if warmest: # FILL = -99 # # steps = [(i, j) for i in [-2, -1, 0, 1, 2] for j in [-2, -1, 0, 1, 2]] # t11_neighbour_i = np.zeros((25, matched['row'].shape[0])) # for i, (step_r, step_c) in enumerate(steps): # new_row_col = {'row': matched['row'] + step_r, # 'col': matched['col'] + step_c} # t11_neighbour_i[i, :] = get_data_from_array_fill_outside(t11, # new_row_col, # Fill=FILL) # if warmest: # neigbour_index = np.argmax(t11_neighbour_i, axis=0) # else: # coldest # neigbour_index = np.argmin(t11_neighbour_i, axis=0) # new_row_matched = np.array( # [matched['row'][idx] + steps[neigbour_index[idx]][0] # for idx in range(matched['row'].shape[0])]) # new_col_matched = np.array( # [matched['col'][idx] + steps[neigbour_index[idx]][1] # for idx in range(matched['row'].shape[0])]) # new_row_col = {'row': new_row_matched, 'col': new_col_matched} # return new_row_col # # Path: atrain_match/utils/match.py # class MatchMapper(object): # def __init__(self, rows, cols, pixel_mask, time_diff=None, # time_threshold=None): # def __call__(self, array): # def rows(self): # def cols(self): # def time_diff(self): # def time_diff(self, value): # def mask(self): # def match_lonlat(source, target, # radius_of_influence=0.7*RESOLUTION*1000.0, # n_neighbours=1): , which may contain function names, class names, or code. Output only the next line.
retv = get_warmest_or_coldest_index(self.t11, self.matched)
Given the code snippet: <|code_start|>class test_match_lon_lat(unittest.TestCase): def setUp(self): lon = np.array([[999, 10, 15], [-999, 20, 25]]).astype(np.float64) lat = np.array([[999, 10, 15], [-999, 20, 25]]).astype(np.float64) lon_t = np.array([31, 10, 15]).astype(np.float64) lat_t = np.array([89, 10, 15]).astype(np.float64) lon3 = np.array([[25, 10, 15], [10, 10, 15]]).astype(np.float64) lat3 = np.array([[10, 11, 16], [12, 10, 15]]).astype(np.float64) self.source = (lon, lat) self.source3 = (lon3, lat3) self.target = (lon_t, lat_t) self.RESOLUTION = 5 def test_match_integers(self): lon = np.array([0, 10, 25]) source_def = SwathDefinition(*(lon, lon)) target_def = SwathDefinition(*(lon, lon)) valid_in, valid_out, indices_int, distances = get_neighbour_info(source_def, target_def, 1000, neighbours=1) lon = np.array([0, 10, 25]).astype(np.float64) source_def = SwathDefinition(*(lon, lon)) target_def = SwathDefinition(*(lon, lon)) valid_in, valid_out, indices_float, distances = get_neighbour_info(source_def, target_def, 1000, neighbours=1) def test_match(self): <|code_end|> , generate the next line using the imports in this file: import numpy as np import unittest from atrain_match.utils.pps_prototyping_util import (get_warmest_or_coldest_index) from atrain_match.utils import match from scipy.ndimage.filters import generic_filter from pyresample.geometry import SwathDefinition from pyresample.kd_tree import get_neighbour_info and context (functions, classes, or occasionally code) from other files: # Path: atrain_match/utils/pps_prototyping_util.py # def get_warmest_or_coldest_index(t11, matched, warmest=True): # """Get index for coldedest pixel in 5x5 neighbourhood.""" # FILL = 999999.9 # coldest # if warmest: # FILL = -99 # # steps = [(i, j) for i in [-2, -1, 0, 1, 2] for j in [-2, -1, 0, 1, 2]] # t11_neighbour_i = np.zeros((25, matched['row'].shape[0])) # for i, (step_r, step_c) in enumerate(steps): # new_row_col = {'row': matched['row'] + step_r, # 'col': matched['col'] + step_c} # t11_neighbour_i[i, :] = get_data_from_array_fill_outside(t11, # new_row_col, # Fill=FILL) # if warmest: # neigbour_index = np.argmax(t11_neighbour_i, axis=0) # else: # coldest # neigbour_index = np.argmin(t11_neighbour_i, axis=0) # new_row_matched = np.array( # [matched['row'][idx] + steps[neigbour_index[idx]][0] # for idx in range(matched['row'].shape[0])]) # new_col_matched = np.array( # [matched['col'][idx] + steps[neigbour_index[idx]][1] # for idx in range(matched['row'].shape[0])]) # new_row_col = {'row': new_row_matched, 'col': new_col_matched} # return new_row_col # # Path: atrain_match/utils/match.py # class MatchMapper(object): # def __init__(self, rows, cols, pixel_mask, time_diff=None, # time_threshold=None): # def __call__(self, array): # def rows(self): # def cols(self): # def time_diff(self): # def time_diff(self, value): # def mask(self): # def match_lonlat(source, target, # radius_of_influence=0.7*RESOLUTION*1000.0, # n_neighbours=1): . Output only the next line.
mapper, _ = match.match_lonlat(self.source3, self.target,
Given the following code snippet before the placeholder: <|code_start|> class MOD06Obj: # skeleton container for MODIS Level2 data def __init__(self): self.height = None self.temperature = None self.pressure = None self.cloud_emissivity = None self.cloud_phase = None self.lwp = None self.multilayer = None self.optical_depth = None def add_modis_06(ca_matchup, AM_PATHS, cross): mfile = find_modis_lvl2_file(AM_PATHS, cross) if mfile.endswith('.h5'): modis_06 = read_modis_h5(mfile) else: modis_06 = read_modis_hdf(mfile) ca_matchup_truth_sat = getattr(ca_matchup, ca_matchup.truth_sat) row_matched = ca_matchup_truth_sat.imager_linnum col_matched = ca_matchup_truth_sat.imager_pixnum index = {'row': row_matched, 'col': col_matched} index_5km = {'row': np.floor(row_matched/5).astype(np.int), 'col': np.floor(col_matched/5).astype(np.int)} <|code_end|> , predict the next line using imports from the current file: from atrain_match.libs.extract_imager_along_track import get_data_from_array from atrain_match.config import NODATA from atrain_match.libs.truth_imager_match import find_main_cloudproduct_file from pyhdf.SD import SD, SDC import numpy as np import os import h5py import logging and context including class names, function names, and sometimes code from other files: # Path: atrain_match/libs/extract_imager_along_track.py # def get_data_from_array(array, matched): # if array is None: # return None # return np.array([array[matched['row'][idx], matched['col'][idx]] # for idx in range(matched['row'].shape[0])]) # # Path: atrain_match/config.py # NODATA = -9 . Output only the next line.
ca_matchup.modis_lvl2.height = get_data_from_array(modis_06.height, index)
Continue the code snippet: <|code_start|># # You should have received a copy of the GNU General Public License # along with atrain_match. If not, see <http://www.gnu.org/licenses/>. # -*- coding: utf-8 -*- # Program truth_imager_plot.py """Plotting functions to plot CALIOP, CPR (CloudSat) and colocated imager data along track.""" def plot_cal_clsat_geoprof_imager(match_clsat, match_calipso, imager_ctth_m_above_seasurface, plotpath, basename, mode, file_type='png', **options): """Plot imager co-located data on CALIOP and CPR (Cloudsat) track.""" instrument = 'imager' if 'instrument' in options: instrument = options['instrument'] MAXHEIGHT = None if 'MAXHEIGHT' in options: MAXHEIGHT = options["MAXHEIGHT"] caliop_height = match_calipso.calipso.layer_top_altitude * 1000 caliop_base = match_calipso.calipso.layer_base_altitude * 1000 calipso_val_h = match_calipso.calipso.validation_height caliop_base[caliop_base < 0] = -9 caliop_height[caliop_height < 0] = -9 <|code_end|> . Use current file imports: import numpy as np from atrain_match.config import RESOLUTION from matplotlib import pyplot as plt and context (classes, functions, or code) from other files: # Path: atrain_match/config.py # RESOLUTION = int(os.environ.get('ATRAIN_RESOLUTION', 5)) . Output only the next line.
if RESOLUTION == 5 and match_clsat is not None:
Next line prediction: <|code_start|> MY_SATELLITES = options.satellites if options.years: MY_YEARS = options.years years_string = "_".join(MY_YEARS) satellites_string = "_".join(MY_SATELLITES) # get cases CASES = [] month_list = ["*"] day_list = ["*"] if "MONTH" in SETTINGS.keys() and len(SETTINGS["MONTHS"]) > 0: month_list = ["{:02d}".format(int(ind)) for ind in SETTINGS["MONTHS"]] if options.months: month_list = ["{:02d}".format(int(ind)) for ind in options.months] if "DAY" in SETTINGS.keys() and len(SETTINGS["DAYS"]) > 0: day_list = ["{:02d}".format(int(ind)) for ind in SETTINGS["DAYS"]] for sat in MY_SATELLITES: for year in MY_YEARS: for month in month_list: for day in day_list: CASES.append({'satname': sat, 'month': month, 'year': year, 'day': day}) if len(modes_dnt_list) == 0: logger.warning("No modes selected!") parser.print_help() # For each mode calcualte the statistics for process_mode_dnt in modes_dnt_list: <|code_end|> . Use current file imports: (from atrain_match.config import (RESOLUTION, _validation_results_dir, SURFACES) from atrain_match.statistics import orrb_CFC_stat from atrain_match.statistics import orrb_CTH_stat from atrain_match.statistics import orrb_CTY_stat from atrain_match.statistics import orrb_CPH_stat from atrain_match.statistics import orrb_LWP_stat from glob import glob from atrain_match.utils.runutils import read_config_info import logging import os import argparse) and context including class names, function names, or small code snippets from other files: # Path: atrain_match/config.py # def str2bool(v): # RESOLUTION = int(os.environ.get('ATRAIN_RESOLUTION', 5)) # AREA_CONFIG_FILE = os.environ.get('AREA_CONFIG_FILE', './areas.def') # AREA_CONFIG_FILE_PLOTS_ON_AREA = os.environ.get('AREA_CONFIG_FILE_PLOTS_ON_AREA', './region_config_test.cfg') # ATRAIN_MATCH_CONFIG_PATH = os.environ.get('ATRAINMATCH_CONFIG_DIR', './etc') # ATRAIN_MATCH_CONFIG_FILE = os.environ.get('ATRAINMATCH_CONFIG_FILE', 'atrain_match.cfg') # INSTRUMENT = {'npp': 'viirs', # 'noaa18': 'avhrr', # 'meteosat8': 'seviri', # 'meteosat9': 'seviri', # 'meteosat10': 'seviri', # 'meteosat11': 'seviri', # 'fy3d': 'mersi2', # 'noaa20': 'viirs', # 'sga1': 'metimage', # 'epsga1': 'metimage', # 'metopsga1': 'metimage', # 'eos1': 'modis', # 'eos2': 'modis'} # ALLOWED_MODES = [] # MODES_NO_DNT = ['BASIC'] # PROCESS_SURFACES = [ # "ICE_COVER_SEA", "ICE_FREE_SEA", "SNOW_COVER_LAND", "SNOW_FREE_LAND", # "COASTAL_ZONE", # "TROPIC_ZONE", "TROPIC_ZONE_SNOW_FREE_LAND", "TROPIC_ZONE_ICE_FREE_SEA", # "SUB_TROPIC_ZONE", # "SUB_TROPIC_ZONE_SNOW_FREE_LAND", "SUB_TROPIC_ZONE_ICE_FREE_SEA", # "HIGH-LATITUDES", # "HIGH-LATITUDES_SNOW_FREE_LAND", "HIGH-LATITUDES_ICE_FREE_SEA", # "HIGH-LATITUDES_SNOW_COVER_LAND", "HIGH-LATITUDES_ICE_COVER_SEA", # "POLAR", "POLAR_SNOW_FREE_LAND", "POLAR_ICE_FREE_SEA", # "POLAR_SNOW_COVER_LAND", "POLAR_ICE_COVER_SEA"] # COMPRESS_LVL = 6 # : Compresssion level for generated matched files (h5) # NODATA = -9 # CLOUDSAT_CLOUDY_THR = 30.0 # CALIPSO_FILE_LENGTH = 60*60 # s calipso files are shorter 60 minutes # CLOUDSAT_FILE_LENGTH = 120*60 # s cloudsat files are shorter 120 minutes # ISS_FILE_LENGTH = 60*60 # s iss files are shorter 60 minutes # AMSR_FILE_LENGTH = 60*60 # AMSR-Es files are shorter 60 minutes # SYNOP_FILE_LENGTH = 24*60 # s Our synop data comes in 1 day files # MORA_FILE_LENGTH = 24*60 # s Our MORA data comes in 1 day files # PPS_FORMAT_2012_OR_EARLIER = False # SURFACES = PROCESS_SURFACES # DNT_FLAG = ['ALL', 'DAY', 'NIGHT', 'TWILIGHT'] . Output only the next line.
print(RESOLUTION)
Next line prediction: <|code_start|> if "MONTH" in SETTINGS.keys() and len(SETTINGS["MONTHS"]) > 0: month_list = ["{:02d}".format(int(ind)) for ind in SETTINGS["MONTHS"]] if options.months: month_list = ["{:02d}".format(int(ind)) for ind in options.months] if "DAY" in SETTINGS.keys() and len(SETTINGS["DAYS"]) > 0: day_list = ["{:02d}".format(int(ind)) for ind in SETTINGS["DAYS"]] for sat in MY_SATELLITES: for year in MY_YEARS: for month in month_list: for day in day_list: CASES.append({'satname': sat, 'month': month, 'year': year, 'day': day}) if len(modes_dnt_list) == 0: logger.warning("No modes selected!") parser.print_help() # For each mode calcualte the statistics for process_mode_dnt in modes_dnt_list: print(RESOLUTION) # get result files for all cases for truth_sat in SETTINGS["COMPILE_STATISTICS_TRUTH"]: logger.info("PROCESS MODE %s, truth: %s", process_mode_dnt, truth_sat.upper()) print("Gathering statistics from all validation results files in the " "following directories:") results_files = [] for case in CASES: indata_dir = AM_PATHS['result_dir'].format( <|code_end|> . Use current file imports: (from atrain_match.config import (RESOLUTION, _validation_results_dir, SURFACES) from atrain_match.statistics import orrb_CFC_stat from atrain_match.statistics import orrb_CTH_stat from atrain_match.statistics import orrb_CTY_stat from atrain_match.statistics import orrb_CPH_stat from atrain_match.statistics import orrb_LWP_stat from glob import glob from atrain_match.utils.runutils import read_config_info import logging import os import argparse) and context including class names, function names, or small code snippets from other files: # Path: atrain_match/config.py # def str2bool(v): # RESOLUTION = int(os.environ.get('ATRAIN_RESOLUTION', 5)) # AREA_CONFIG_FILE = os.environ.get('AREA_CONFIG_FILE', './areas.def') # AREA_CONFIG_FILE_PLOTS_ON_AREA = os.environ.get('AREA_CONFIG_FILE_PLOTS_ON_AREA', './region_config_test.cfg') # ATRAIN_MATCH_CONFIG_PATH = os.environ.get('ATRAINMATCH_CONFIG_DIR', './etc') # ATRAIN_MATCH_CONFIG_FILE = os.environ.get('ATRAINMATCH_CONFIG_FILE', 'atrain_match.cfg') # INSTRUMENT = {'npp': 'viirs', # 'noaa18': 'avhrr', # 'meteosat8': 'seviri', # 'meteosat9': 'seviri', # 'meteosat10': 'seviri', # 'meteosat11': 'seviri', # 'fy3d': 'mersi2', # 'noaa20': 'viirs', # 'sga1': 'metimage', # 'epsga1': 'metimage', # 'metopsga1': 'metimage', # 'eos1': 'modis', # 'eos2': 'modis'} # ALLOWED_MODES = [] # MODES_NO_DNT = ['BASIC'] # PROCESS_SURFACES = [ # "ICE_COVER_SEA", "ICE_FREE_SEA", "SNOW_COVER_LAND", "SNOW_FREE_LAND", # "COASTAL_ZONE", # "TROPIC_ZONE", "TROPIC_ZONE_SNOW_FREE_LAND", "TROPIC_ZONE_ICE_FREE_SEA", # "SUB_TROPIC_ZONE", # "SUB_TROPIC_ZONE_SNOW_FREE_LAND", "SUB_TROPIC_ZONE_ICE_FREE_SEA", # "HIGH-LATITUDES", # "HIGH-LATITUDES_SNOW_FREE_LAND", "HIGH-LATITUDES_ICE_FREE_SEA", # "HIGH-LATITUDES_SNOW_COVER_LAND", "HIGH-LATITUDES_ICE_COVER_SEA", # "POLAR", "POLAR_SNOW_FREE_LAND", "POLAR_ICE_FREE_SEA", # "POLAR_SNOW_COVER_LAND", "POLAR_ICE_COVER_SEA"] # COMPRESS_LVL = 6 # : Compresssion level for generated matched files (h5) # NODATA = -9 # CLOUDSAT_CLOUDY_THR = 30.0 # CALIPSO_FILE_LENGTH = 60*60 # s calipso files are shorter 60 minutes # CLOUDSAT_FILE_LENGTH = 120*60 # s cloudsat files are shorter 120 minutes # ISS_FILE_LENGTH = 60*60 # s iss files are shorter 60 minutes # AMSR_FILE_LENGTH = 60*60 # AMSR-Es files are shorter 60 minutes # SYNOP_FILE_LENGTH = 24*60 # s Our synop data comes in 1 day files # MORA_FILE_LENGTH = 24*60 # s Our MORA data comes in 1 day files # PPS_FORMAT_2012_OR_EARLIER = False # SURFACES = PROCESS_SURFACES # DNT_FLAG = ['ALL', 'DAY', 'NIGHT', 'TWILIGHT'] . Output only the next line.
val_dir=_validation_results_dir,
Predict the next line for this snippet: <|code_start|> parser.add_argument('--years', '-y', metavar='YYYY', type=str, nargs='*', required=False, help='List of year to combine, ' 'overrides YEARS in atrain_match.cfg') parser.add_argument('--months', '-m', metavar='mm', type=str, nargs='*', required=False, help='List of year to combine, ' 'overrides YEARS in atrain_match.cfg') (options) = parser.parse_args() AM_PATHS, SETTINGS = read_config_info() # Find all wanted modes (dnt) modes_list = [] if options.nodnt: New_DNT_FLAG = [''] else: New_DNT_FLAG = ['', '_DAY', '_NIGHT', '_TWILIGHT'] if options.basic: modes_list.append('BASIC') if options.standard: modes_list.append('STANDARD') if options.satz: for mode in ['SATZ_LOW', 'SATZ_70', 'SATZ_HIGH', 'SATZ_0_20', 'SATZ_20_40', 'SATZ_40_60', 'SATZ_60_80', 'SATZ_80_100',]: modes_list.append(mode) if options.odticfilter: # I prefer this one! /KG print('Will calculate statistic for mode OPTICAL_DEPTH_THIN_IS_CLEAR') modes_list.append('OPTICAL_DEPTH_THIN_IS_CLEAR') if options.surface_new_way: print('Will calculate statistic for the different surfaces') <|code_end|> with the help of current file imports: from atrain_match.config import (RESOLUTION, _validation_results_dir, SURFACES) from atrain_match.statistics import orrb_CFC_stat from atrain_match.statistics import orrb_CTH_stat from atrain_match.statistics import orrb_CTY_stat from atrain_match.statistics import orrb_CPH_stat from atrain_match.statistics import orrb_LWP_stat from glob import glob from atrain_match.utils.runutils import read_config_info import logging import os import argparse and context from other files: # Path: atrain_match/config.py # def str2bool(v): # RESOLUTION = int(os.environ.get('ATRAIN_RESOLUTION', 5)) # AREA_CONFIG_FILE = os.environ.get('AREA_CONFIG_FILE', './areas.def') # AREA_CONFIG_FILE_PLOTS_ON_AREA = os.environ.get('AREA_CONFIG_FILE_PLOTS_ON_AREA', './region_config_test.cfg') # ATRAIN_MATCH_CONFIG_PATH = os.environ.get('ATRAINMATCH_CONFIG_DIR', './etc') # ATRAIN_MATCH_CONFIG_FILE = os.environ.get('ATRAINMATCH_CONFIG_FILE', 'atrain_match.cfg') # INSTRUMENT = {'npp': 'viirs', # 'noaa18': 'avhrr', # 'meteosat8': 'seviri', # 'meteosat9': 'seviri', # 'meteosat10': 'seviri', # 'meteosat11': 'seviri', # 'fy3d': 'mersi2', # 'noaa20': 'viirs', # 'sga1': 'metimage', # 'epsga1': 'metimage', # 'metopsga1': 'metimage', # 'eos1': 'modis', # 'eos2': 'modis'} # ALLOWED_MODES = [] # MODES_NO_DNT = ['BASIC'] # PROCESS_SURFACES = [ # "ICE_COVER_SEA", "ICE_FREE_SEA", "SNOW_COVER_LAND", "SNOW_FREE_LAND", # "COASTAL_ZONE", # "TROPIC_ZONE", "TROPIC_ZONE_SNOW_FREE_LAND", "TROPIC_ZONE_ICE_FREE_SEA", # "SUB_TROPIC_ZONE", # "SUB_TROPIC_ZONE_SNOW_FREE_LAND", "SUB_TROPIC_ZONE_ICE_FREE_SEA", # "HIGH-LATITUDES", # "HIGH-LATITUDES_SNOW_FREE_LAND", "HIGH-LATITUDES_ICE_FREE_SEA", # "HIGH-LATITUDES_SNOW_COVER_LAND", "HIGH-LATITUDES_ICE_COVER_SEA", # "POLAR", "POLAR_SNOW_FREE_LAND", "POLAR_ICE_FREE_SEA", # "POLAR_SNOW_COVER_LAND", "POLAR_ICE_COVER_SEA"] # COMPRESS_LVL = 6 # : Compresssion level for generated matched files (h5) # NODATA = -9 # CLOUDSAT_CLOUDY_THR = 30.0 # CALIPSO_FILE_LENGTH = 60*60 # s calipso files are shorter 60 minutes # CLOUDSAT_FILE_LENGTH = 120*60 # s cloudsat files are shorter 120 minutes # ISS_FILE_LENGTH = 60*60 # s iss files are shorter 60 minutes # AMSR_FILE_LENGTH = 60*60 # AMSR-Es files are shorter 60 minutes # SYNOP_FILE_LENGTH = 24*60 # s Our synop data comes in 1 day files # MORA_FILE_LENGTH = 24*60 # s Our MORA data comes in 1 day files # PPS_FORMAT_2012_OR_EARLIER = False # SURFACES = PROCESS_SURFACES # DNT_FLAG = ['ALL', 'DAY', 'NIGHT', 'TWILIGHT'] , which may contain function names, class names, or code. Output only the next line.
for surface in SURFACES:
Given the following code snippet before the placeholder: <|code_start|> data = _interpolate_height_and_temperature_from_pressure(obt.imager, 440) setattr(obt.imager, 'segment_nwp_h440', data) data = _interpolate_height_and_temperature_from_pressure(obt.imager, 680) setattr(obt.imager, 'segment_nwp_h680', data) return obt # --------------------------------------------------------------------------- def imager_track_from_matched(obt, SETTINGS, cloudproducts, extract_radiances=True, extract_cma=True, extract_ctth=True, extract_ctype=True, extract_cpp=True, extract_aux_segments=True, extract_aux=True, aux_params=None, extract_some_data_for_x_neighbours=False, find_mean_data_for_x_neighbours=False): aux_params_all = ["surftemp", "t500", "t700", "t850", "t950", "ttro", "ciwv", "t900", "t1000", "t800", "t250", "t2m", "ptro", "psur", "h2m", "u10m", "v10m", "t2m", "snowa", "snowd", "seaice", "landuse", "fractionofland", "elevation", "r37_sza_correction_done", <|code_end|> , predict the next line using imports from the current file: import numpy as np import logging import os from atrain_match.cloudproducts.read_oca import OCA_READ_EXTRA from atrain_match.utils.pps_prototyping_util import (get_coldest_values, get_darkest_values, get_warmest_values) from atrain_match.utils.pps_prototyping_util import add_cnn_features and context including class names, function names, and sometimes code from other files: # Path: atrain_match/cloudproducts/read_oca.py # OCA_READ_EXTRA = OCA_READ_EXTRA_ONLY_OCA + ['flag_cm'] . Output only the next line.
] + OCA_READ_EXTRA # And NN-extra!
Predict the next line after this snippet: <|code_start|> seconds = np.float64(pps_nc.variables['time'][::]) # from PPS often 0 if 'seconds' in time_temp: if 'T' in time_temp: time_obj = time.strptime(time_temp, 'seconds since %Y-%m-%dT%H:%M:%S+00:00') elif time_temp == u'seconds since 1970-01-01': time_obj = time.strptime(time_temp, 'seconds since %Y-%m-%d') else: time_obj = time.strptime(time_temp, 'seconds since %Y-%m-%d %H:%M:%S.%f +00:00') sec_since_1970 = calendar.timegm(time_obj) all_imager_obj.sec1970_start = (sec_since_1970 + np.float64(np.min(pps_nc.variables['time_bnds'][::])) + seconds) all_imager_obj.sec1970_end = (sec_since_1970 + np.float64(np.max(pps_nc.variables['time_bnds'][::])) + seconds) else: try: all_imager_obj.sec1970_start = calendar.timegm(time.strptime(pps_nc.variables['lon'].start_time, '%Y-%m-%d %H:%M:%S.%f')) all_imager_obj.sec1970_end = calendar.timegm(time.strptime(pps_nc.variables['lon'].end_time, '%Y-%m-%d %H:%M:%S.%f')) except: all_imager_obj.sec1970_start = calendar.timegm(time.strptime(pps_nc.start_time, '%Y-%m-%d %H:%M:%S')) all_imager_obj.sec1970_end = calendar.timegm(time.strptime(pps_nc.end_time, '%Y-%m-%d %H:%M:%S')) # print type(all_imager_obj.sec1970_start) all_imager_obj.sec1970_start = np.float64(all_imager_obj.sec1970_start) all_imager_obj.sec1970_end = np.float64(all_imager_obj.sec1970_end) <|code_end|> using the current file's imports: from atrain_match.utils.runutils import do_some_geo_obj_logging from datetime import datetime import atrain_match.config as config import numpy as np import os import netCDF4 import h5py import logging import time import calendar import h5py import h5py import h5py and any relevant context from other files: # Path: atrain_match/utils/runutils.py # def do_some_geo_obj_logging(GeoObj): # import time # tim1 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_start)) # tim2 = time.strftime("%Y%m%d %H:%M", # time.gmtime(GeoObj.sec1970_end)) # logger.debug("Starttime: %s, end time: %s", tim1, tim2) # logger.debug("Min lon: %f, max lon: %d", # np.min(np.where( # np.equal(GeoObj.longitude, GeoObj.nodata), # 99999, # GeoObj.longitude)), # np.max(GeoObj.longitude)) # logger.debug("Min lat: %d, max lat: %d", # np.min(np.where( # np.equal(GeoObj.latitude, GeoObj.nodata), # 99999, # GeoObj.latitude)), # np.max(GeoObj.latitude)) . Output only the next line.
do_some_geo_obj_logging(all_imager_obj)