Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Continue the code snippet: <|code_start|> (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ UTIL_BLOCK_SIZE = 1000000 def _compute_rule_importances(rule_classifications, model_rules_idx, training_example_idx): model_rule_classifications = rule_classifications.get_columns(model_rules_idx)[training_example_idx] model_neg_prediction_idx = np.where(np.prod(model_rule_classifications, axis=1) == 0)[0] return (float(len(model_neg_prediction_idx)) - model_rule_classifications[model_neg_prediction_idx].sum(axis=0)) / \ len(model_neg_prediction_idx) class BaseSetCoveringMachine(object): def __init__(self, model_type, max_rules): if model_type == conjunction: self._add_rule_to_model = self._append_conjunction_model self.model_type = conjunction <|code_end|> . Use current file imports: import logging import numpy as np from math import ceil from ..common.models import scm, conjunction, ConjunctionModel, disjunction, DisjunctionModel from ...utils import _class_to_string and context (classes, functions, or code) from other files: # Path: core/kover/learning/common/models.py # class BaseModel(object): # class CARTModel(BaseModel): # class SCMModel(BaseModel): # class ConjunctionModel(SCMModel): # class DisjunctionModel(SCMModel): # def __init__(self): # def predict(self, X): # def predict_proba(self, X): # def learner(self): # def __str__(self): # def __init__(self, class_tags=None): # def predict(self, X): # def predict_proba(self, X): # def learner(self): # def _to_string(self, node=None,depth=0): # def __len__(self): # def depth(self): # def __init__(self): # def add(self, rule): # def predict(self, X): # def predict_proba(self, X): # def remove(self, index): # def example_dependencies(self): # def learner(self): # def type(self): # def _to_string(self, separator=" "): # def __eq__(self, other): # def __iter__(self): # def __len__(self): # def predict_proba(self, X): # def type(self): # def __str__(self): # def predict_proba(self, X): # def type(self): # def __str__(self): # # Path: core/kover/utils.py # def _class_to_string(instance): # """ # Returns a string representation of the public attributes of a class. # # Parameters: # ----------- # instance: object # An instance of any class. # # Returns: # -------- # string_rep: string # A string representation of the class and its public attributes. # # Notes: # ----- # Private attributes must be marked with a leading underscore. # """ # return instance.__class__.__name__ + "(" + ",".join( # [str(k) + "=" + str(v) for k, v in instance.__dict__.iteritems() if str(k[0]) != "_"]) + ")" . Output only the next line.
elif model_type == disjunction:
Predict the next line for this snippet: <|code_start|> raise RuntimeError("The predictor does not support probabilistic predictions.") return self.model.predict_proba(X) def __str__(self): return _class_to_string(self) class SetCoveringMachine(BaseSetCoveringMachine): """ The Set Covering Machine (SCM). Marchand, M., & Taylor, J. S. (2003). The set covering machine. Journal of Machine Learning Research, 3, 723–746. Parameters: ----------- model_type: pyscm.model.conjunction or pyscm.model.disjunction, default=pyscm.model.conjunction The type of model to be built. p: float, default=1.0 A parameter to control the importance of making prediction errors on positive examples in the utility function. max_rules: int, default=10 The maximum number of binary rules to include in the model. verbose: bool, default=False Sets verbose mode on/off. """ def __init__(self, model_type=conjunction, p=1.0, max_rules=10): super(SetCoveringMachine, self).__init__(model_type=model_type, max_rules=max_rules) if model_type == conjunction: self.model = ConjunctionModel() elif model_type == disjunction: <|code_end|> with the help of current file imports: import logging import numpy as np from math import ceil from ..common.models import scm, conjunction, ConjunctionModel, disjunction, DisjunctionModel from ...utils import _class_to_string and context from other files: # Path: core/kover/learning/common/models.py # class BaseModel(object): # class CARTModel(BaseModel): # class SCMModel(BaseModel): # class ConjunctionModel(SCMModel): # class DisjunctionModel(SCMModel): # def __init__(self): # def predict(self, X): # def predict_proba(self, X): # def learner(self): # def __str__(self): # def __init__(self, class_tags=None): # def predict(self, X): # def predict_proba(self, X): # def learner(self): # def _to_string(self, node=None,depth=0): # def __len__(self): # def depth(self): # def __init__(self): # def add(self, rule): # def predict(self, X): # def predict_proba(self, X): # def remove(self, index): # def example_dependencies(self): # def learner(self): # def type(self): # def _to_string(self, separator=" "): # def __eq__(self, other): # def __iter__(self): # def __len__(self): # def predict_proba(self, X): # def type(self): # def __str__(self): # def predict_proba(self, X): # def type(self): # def __str__(self): # # Path: core/kover/utils.py # def _class_to_string(instance): # """ # Returns a string representation of the public attributes of a class. # # Parameters: # ----------- # instance: object # An instance of any class. # # Returns: # -------- # string_rep: string # A string representation of the class and its public attributes. # # Notes: # ----- # Private attributes must be marked with a leading underscore. # """ # return instance.__class__.__name__ + "(" + ",".join( # [str(k) + "=" + str(v) for k, v in instance.__dict__.iteritems() if str(k[0]) != "_"]) + ")" , which may contain function names, class names, or code. Output only the next line.
self.model = DisjunctionModel()
Here is a snippet: <|code_start|> logging.debug("Rule added to the model: " + str(new_rule)) return new_rule def _append_disjunction_model(self, new_rule): new_rule = new_rule.inverse() self.model.add(new_rule) logging.debug("Rule added to the model: " + str(new_rule)) return new_rule def _is_fitted(self): return len(self.model) > 0 def _predict(self, X): if not self._is_fitted(): raise RuntimeError("A model must be fitted prior to calling predict.") return self.model.predict(X) def _predict_proba(self, X): """ Child classes must have the PROBABILISTIC_PREDICTIONS set to True to use this method. """ if not self._is_fitted(): raise RuntimeError("A model must be fitted prior to calling predict.") if not self._flags.get("PROBABILISTIC_PREDICTIONS", False): raise RuntimeError("The predictor does not support probabilistic predictions.") return self.model.predict_proba(X) def __str__(self): <|code_end|> . Write the next line using the current file imports: import logging import numpy as np from math import ceil from ..common.models import scm, conjunction, ConjunctionModel, disjunction, DisjunctionModel from ...utils import _class_to_string and context from other files: # Path: core/kover/learning/common/models.py # class BaseModel(object): # class CARTModel(BaseModel): # class SCMModel(BaseModel): # class ConjunctionModel(SCMModel): # class DisjunctionModel(SCMModel): # def __init__(self): # def predict(self, X): # def predict_proba(self, X): # def learner(self): # def __str__(self): # def __init__(self, class_tags=None): # def predict(self, X): # def predict_proba(self, X): # def learner(self): # def _to_string(self, node=None,depth=0): # def __len__(self): # def depth(self): # def __init__(self): # def add(self, rule): # def predict(self, X): # def predict_proba(self, X): # def remove(self, index): # def example_dependencies(self): # def learner(self): # def type(self): # def _to_string(self, separator=" "): # def __eq__(self, other): # def __iter__(self): # def __len__(self): # def predict_proba(self, X): # def type(self): # def __str__(self): # def predict_proba(self, X): # def type(self): # def __str__(self): # # Path: core/kover/utils.py # def _class_to_string(instance): # """ # Returns a string representation of the public attributes of a class. # # Parameters: # ----------- # instance: object # An instance of any class. # # Returns: # -------- # string_rep: string # A string representation of the class and its public attributes. # # Notes: # ----- # Private attributes must be marked with a leading underscore. # """ # return instance.__class__.__name__ + "(" + ",".join( # [str(k) + "=" + str(v) for k, v in instance.__dict__.iteritems() if str(k[0]) != "_"]) + ")" , which may include functions, classes, or code. Output only the next line.
return _class_to_string(self)
Given the following code snippet before the placeholder: <|code_start|> GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ class BreimanInfo(object): def __init__(self, node_n_examples_by_class, class_priors, total_n_examples_by_class): # Eq. 2.2 Probability that an example is in class j and falls into node t self.p_j_t = {c: class_priors[c] * node_n_examples_by_class[c] / total_n_examples_by_class[c] for c in class_priors.iterkeys()} # Eq. 2.3 Probability that any example falls in node t self.p_t = sum(self.p_j_t.values()) # Eq. 2.4 Probability that an example is in class j given that it falls in node t self.p_j_given_t = {c: self.p_j_t[c] / self.p_t for c in class_priors.iterkeys()} # Def. 2.10 Probability of misclassification given that an example falls into node t self.r_t = 1.0 - max(self.p_j_given_t.values()) # Contribution of the node to the tree's overall missclassification rate self.R_t = self.r_t * self.p_t <|code_end|> , predict the next line using imports from the current file: import logging import numpy as np from .models import BaseModel and context including class names, function names, and sometimes code from other files: # Path: core/kover/learning/common/models.py # class BaseModel(object): # def __init__(self): # super(BaseModel, self).__init__() # # def predict(self, X): # raise NotImplementedError() # # def predict_proba(self, X): # raise NotImplementedError() # # @property # def learner(self): # raise NotImplementedError() # # def __str__(self): # return self._to_string() . Output only the next line.
class TreeNode(BaseModel):
Based on the snippet: <|code_start|> # genome (left child) and those that have the k-mer in their genome (right child). # XXX: We keep only the first half of the rule list and classifications, since sum_rows returns the counts # XXX: for presence and absence rules, which we don't need here. # TODO: We could have a parameter called return_absence=True, which avoid using twice the RAM. last_presence_rule_idx = int(1.0 * len(rules) / 2) # Just because sum_rows returns pres/abs rules left_count = {c:np.asarray(rule_classifications.sum_rows(example_idx[c])[: last_presence_rule_idx],dtype=np.float) \ for c in example_idx.keys() if example_idx[c].size} right_count = {c:np.asarray(example_idx[c].shape[0] - left_count[c], dtype=np.float) for c in left_count.keys()} # Left child: cross_entropy = _cross_entropy(left_count, multiply_by_node_proba=True) # Right child: cross_entropy += _cross_entropy(right_count, multiply_by_node_proba=True) # Don't consider rules that lead to empty nodes cross_entropy[sum(left_count.values()) == 0] = np.infty cross_entropy[sum(right_count.values()) == 0] = np.infty return cross_entropy if self.criterion == "gini": get_criterion = _gini_impurity score_rules = _gini_rule_score choice_func = min elif self.criterion == "cross-entropy": get_criterion = _cross_entropy score_rules = _cross_entropy_rule_score choice_func = min <|code_end|> , predict the immediate next line with the help of imports: import logging import numpy as np from collections import defaultdict, deque from math import ceil from copy import deepcopy from sys import setrecursionlimit; setrecursionlimit(1500) from ..common.models import cart, CARTModel from ..common.tree import ProbabilisticTreeNode and context (classes, functions, sometimes code) from other files: # Path: core/kover/learning/common/models.py # class BaseModel(object): # class CARTModel(BaseModel): # class SCMModel(BaseModel): # class ConjunctionModel(SCMModel): # class DisjunctionModel(SCMModel): # def __init__(self): # def predict(self, X): # def predict_proba(self, X): # def learner(self): # def __str__(self): # def __init__(self, class_tags=None): # def predict(self, X): # def predict_proba(self, X): # def learner(self): # def _to_string(self, node=None,depth=0): # def __len__(self): # def depth(self): # def __init__(self): # def add(self, rule): # def predict(self, X): # def predict_proba(self, X): # def remove(self, index): # def example_dependencies(self): # def learner(self): # def type(self): # def _to_string(self, separator=" "): # def __eq__(self, other): # def __iter__(self): # def __len__(self): # def predict_proba(self, X): # def type(self): # def __str__(self): # def predict_proba(self, X): # def type(self): # def __str__(self): # # Path: core/kover/learning/common/tree.py # class ProbabilisticTreeNode(TreeNode): # def predict(self, X): # """ # Multi-class predictions using the current node's rule # # """ # X = np.ascontiguousarray(X) # # # Get probabilistic predictions # class_probabilities = self.predict_proba(X) # # # Find class with the max probability # predictions = np.argmax(class_probabilities, axis=0) # return predictions # # # def predict_proba(self, X): # """ # Probabilistic class predictions using the current node's rule # # """ # X = np.ascontiguousarray(X) # # class_probabilities = np.zeros((len(self.class_examples_idx.keys()), X.shape[0])) # # # Push each example down the tree (an example is a row of X) # for i, x in enumerate(X): # x = x.reshape(1, -1) # current_node = self # # # While we are not at a leaf # while not current_node.is_leaf: # # If the rule of the current node returns TRUE, branch left # if current_node.rule.classify(x): # current_node = current_node.left_child # # Otherwise, branch right # else: # current_node = current_node.right_child # # # A leaf has been reached. Use the leaf class proportions as the the class probabilities. # for c in self.class_examples_idx.iterkeys(): # class_probabilities[c][i] = current_node.breiman_info.p_j_given_t[c] # # return class_probabilities . Output only the next line.
node_type = ProbabilisticTreeNode
Using the snippet: <|code_start|>#!/usr/bin/env python """ Kover: Learn interpretable computational phenotyping models from k-merized genomic data Copyright (C) 2018 Alexandre Drouin & Gael Letarte This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ class KoverDataset(object): def __init__(self, file): self.path = file <|code_end|> , determine the next line of code. You have imports: import numpy as np from functools import partial from ..utils import _hdf5_open_no_chunk_cache and context (class names, function names, or code) available: # Path: core/kover/utils.py # def _hdf5_open_no_chunk_cache(filename, access_type=h.h5f.ACC_RDONLY): # fid = h.h5f.open(filename, access_type) # access_property_list = fid.get_access_plist() # cache_properties = list(access_property_list.get_cache()) # fid.close() # # Disable chunk caching # cache_properties[2] = 0 # No chunk caching # access_property_list.set_cache(*cache_properties) # file_id = h.h5f.open(filename, access_type, fapl=access_property_list) # return h.File(file_id) . Output only the next line.
self.dataset_open = partial(_hdf5_open_no_chunk_cache, file)
Next line prediction: <|code_start|> maps = Blueprint('map', __name__, template_folder='templates') @maps.route('/map/location/CERN/room/<room_name>/', methods=['GET']) def get_map(room_name): <|code_end|> . Use current file imports: (import urllib, urllib2 from flask import json, current_app, render_template, Blueprint from indicomobile.core.indico_api import get_room) and context including class names, function names, or small code snippets from other files: # Path: indicomobile/core/indico_api.py # def get_room(room_name): # path = '/export/roomName/CERN/{room_name}.json'.format(urllib.quote(room_name)) # response = perform_request(path) # return response['results'] . Output only the next line.
results = get_room(room_name)
Continue the code snippet: <|code_start|> PAGE_SIZE = 15 # EVENTS @cache.cached(key_prefix=make_cache_key) def search_event(search, pageNumber): return api.search_event(search, pageNumber) def update_event_info(event_id): if event_id: event_http = api.get_event_info(event_id) if event_http: event_db = db_event.get_event(event_id) if not event_db: event_tt = api.fetch_timetable(event_id) db_event.store_event(event_http, event_tt) <|code_end|> . Use current file imports: from pytz import utc from datetime import timedelta, datetime from flask import session as flask_session, abort from indicomobile.util.date_time import dt_from_indico from indicomobile.core.cache import cache, make_cache_key import urllib import indicomobile.db.event as db_event import indicomobile.db.session as db_session import indicomobile.db.contribution as db_contribution import indicomobile.core.indico_api as api import indicomobile.core.favorites as favorites and context (classes, functions, or code) from other files: # Path: indicomobile/util/date_time.py # def dt_from_indico(dt_dict): # dt = datetime.combine(datetime.strptime(dt_dict['date'], "%Y-%m-%d"), # datetime.strptime(dt_dict['time'].split('.')[0], "%H:%M:%S").time()) # return timezone(dt_dict['tz']).localize(dt) # # Path: indicomobile/core/cache.py # def setup_caching(app): # def make_cache_key(*args, **kwargs): . Output only the next line.
elif utc.localize(event_db['modificationDate']) < dt_from_indico(event_http['modificationDate']):
Next line prediction: <|code_start|> def store_material(block): materials = [] for material_dict in block.get('material', []): resources = [] for resource_dict in material_dict.get('resources', []): resource_dict.pop('_type') resource_dict['conferenceId'] = block.get('conferenceId') <|code_end|> . Use current file imports: (from indicomobile.db.schema import db) and context including class names, function names, or small code snippets from other files: # Path: indicomobile/db/schema.py # class Presenter(Document): # class Resource(Document): # class Material(Document): # class Chair(Document): # class Event(Document): # class Contribution(Document): # class SessionSlot(Document): # class Contribution(Document): # class Day(Document): # class FavoritesContribution(Document): # class FavoritesSessionSlot(Document): # class FavoritesEvent(Document): # class HistoryEvent(Document): # class CachedLatestEvent(Document): # def cleanup(self, event_id): # def cleanup(self, user_id, event_id): . Output only the next line.
resource = db.Resource()
Continue the code snippet: <|code_start|> CallbackDict.__init__(self, initial, on_update) self.sid = sid self.new = new self.modified = False class IndicoMobileSessionInterfaceBasic(SessionInterface): temporary_session_lifetime = timedelta(days=7) def generate_sid(self): return uuid.uuid4().hex def get_storage_expiration_time(self, app, session): if session.permanent: return int(session.get("oauth_token_ttl")) else: return self.temporary_session_lifetime def get_expiration_time(self, app, session): if session.permanent: return parse(session.get("oauth_token_expiration_timestamp")) def open_session(self, app, request): sid = request.cookies.get(app.session_cookie_name) if not sid: return self.session_class(sid=self.generate_sid(), new=True) stored_session = self._get_session(sid) if stored_session is not None: if (stored_session.get("oauth_token_expiration_timestamp")): <|code_end|> . Use current file imports: import uuid import pickle from datetime import timedelta from flask.sessions import SessionInterface, SessionMixin from werkzeug.datastructures import CallbackDict from redis import StrictRedis from dateutil.parser import parse from indicomobile.util.date_time import nowutc and context (classes, functions, or code) from other files: # Path: indicomobile/util/date_time.py # def nowutc(): # return timezone('UTC').localize(datetime.utcnow()) . Output only the next line.
if parse(stored_session.get("oauth_token_expiration_timestamp")) > nowutc():
Given the following code snippet before the placeholder: <|code_start|>class SparseLOL: def __init__(self, csr): self.indptr = csr.indptr self.indices = csr.indices self.data = csr.data def __getitem__(self, item): if np.isscalar(item): # get the column indices for the given row start, stop = self.indptr[item : item+2] return self.indices[start:stop] else: raise ValueError('SparseLOL can only be indexed by an integer.') def extents(labels, input_indices=None): """Compute the extents of every integer value in ``arr``. Parameters ---------- labels : array of int The array of values to be mapped. input_indices : array of int The indices corresponding to the label values passed. If `None`, we assume ``range(labels.size)``. Returns ------- locs : sparse.csr_matrix A sparse matrix in which the nonzero elements of row i are the indices of value i in ``arr``. """ <|code_end|> , predict the next line using imports from the current file: import numpy as np from numpy.lib import stride_tricks from scipy import sparse from .sparselol_cy import extents_count from .dtypes import label_dtype and context including class names, function names, and sometimes code from other files: # Path: gala/dtypes.py . Output only the next line.
labels = labels.astype(label_dtype).ravel()
Predict the next line after this snippet: <|code_start|> class MergeQueue(object): def __init__(self, items=[], length=None, with_progress=False, prog_title='Agglomerating... '): if length is None: self.num_valid_items = len(items) else: self.num_valid_items = length self.original_length = self.num_valid_items self.q = items heapify(self.q) self.is_null_queue = len(items) == 0 if with_progress: self.pbar = StandardProgressBar(prog_title) else: <|code_end|> using the current file's imports: from heapq import heapify, heappush, heappop from .iterprogress import NoProgressBar, StandardProgressBar and any relevant context from other files: # Path: gala/iterprogress.py # class NoProgressBar(object): # def __init__(self, *args, **kwargs): pass # def start(self, *args, **kwargs): pass # def update(self, *args, **kwargs): pass # def update_i(self, *args, **kwargs): pass # def finish(self, *args, **kwargs): pass # def set_title(self, *args, **kwargs): pass # # class StandardProgressBar(object): # def __init__(self, title='Progress: '): # self.title = title # self.is_finished = False # # def start(self, total, widgets=None): # if widgets is None: # widgets = [self.title, RotatingMarker(), ' ', # Percentage(), ' ', Bar(marker='='), ' ', ETA()] # self.pbar = ProgressBar(widgets=widgets, maxval=total) # self.pbar.start() # self.i = 0 # # def update(self, step=1): # self.i += step # self.pbar.update(self.i) # if self.i == self.pbar.maxval: # self.finish() # # def update_i(self, value): # self.i = value # self.pbar.update(value) # if value == self.pbar.maxval: # self.finish() # # def finish(self): # if self.is_finished: # pass # else: # self.pbar.finish() # self.is_finished = True # # def set_title(self, title): # self.title = title . Output only the next line.
self.pbar = NoProgressBar()
Next line prediction: <|code_start|> class MergeQueue(object): def __init__(self, items=[], length=None, with_progress=False, prog_title='Agglomerating... '): if length is None: self.num_valid_items = len(items) else: self.num_valid_items = length self.original_length = self.num_valid_items self.q = items heapify(self.q) self.is_null_queue = len(items) == 0 if with_progress: <|code_end|> . Use current file imports: (from heapq import heapify, heappush, heappop from .iterprogress import NoProgressBar, StandardProgressBar) and context including class names, function names, or small code snippets from other files: # Path: gala/iterprogress.py # class NoProgressBar(object): # def __init__(self, *args, **kwargs): pass # def start(self, *args, **kwargs): pass # def update(self, *args, **kwargs): pass # def update_i(self, *args, **kwargs): pass # def finish(self, *args, **kwargs): pass # def set_title(self, *args, **kwargs): pass # # class StandardProgressBar(object): # def __init__(self, title='Progress: '): # self.title = title # self.is_finished = False # # def start(self, total, widgets=None): # if widgets is None: # widgets = [self.title, RotatingMarker(), ' ', # Percentage(), ' ', Bar(marker='='), ' ', ETA()] # self.pbar = ProgressBar(widgets=widgets, maxval=total) # self.pbar.start() # self.i = 0 # # def update(self, step=1): # self.i += step # self.pbar.update(self.i) # if self.i == self.pbar.maxval: # self.finish() # # def update_i(self, value): # self.i = value # self.pbar.update(value) # if value == self.pbar.maxval: # self.finish() # # def finish(self): # if self.is_finished: # pass # else: # self.pbar.finish() # self.is_finished = True # # def set_title(self, title): # self.title = title . Output only the next line.
self.pbar = StandardProgressBar(prog_title)
Using the snippet: <|code_start|> def test_contingency_table(): seg = np.array([0, 1, 1, 1, 2, 2, 2, 3]) gt = np.array([1, 1, 1, 2, 2, 2, 2, 0]) <|code_end|> , determine the next line of code. You have imports: import numpy as np from numpy.testing import assert_equal, assert_almost_equal from gala import evaluate as ev and context (class names, function names, or code) available: # Path: gala/evaluate.py # def nzcol(mat, row_idx): # def pixel_wise_boundary_precision_recall(pred, gt): # def wiggle_room_precision_recall(pred, boundary, margin=2, connectivity=1): # def get_stratified_sample(ar, n): # def edit_distance(aseg, gt, size_threshold=1000, sp=None): # def raw_edit_distance(aseg, gt, size_threshold=1000): # def contingency_table(seg, gt, *, ignore_seg=(), ignore_gt=(), norm=True): # def assignment_table(seg_or_ctable, gt=None, *, dtype=np.bool_): # def _mindiff(arr): # def __init__(self, arg1, shape=None, dtype=None, copy=False, # max_num_rows=None, max_nonzero=None, # expansion_factor=2): # def data(self): # def data(self, value): # def indices(self): # def indices(self, value): # def indptr(self): # def indptr(self, value): # def __setitem__(self, index, value): # def _append_row_at(self, index, value): # def _zero_row(self, index): # def _double_indptr(self): # def _double_data_and_indices(self): # def merge_contingency_table(a, b, ignore_seg=[0], ignore_gt=[0]): # def xlogx(x, out=None, in_place=False): # def special_points_evaluate(eval_fct, coords, flatten=True, coord_format=True): # def special_eval_fct(x, y, *args, **kwargs): # def make_synaptic_functions(fn, fcts): # def make_synaptic_vi(fn): # def vi(x, y=None, weights=np.ones(2), ignore_x=[0], ignore_y=[0]): # def split_vi(x, y=None, ignore_x=[0], ignore_y=[0]): # def vi_pairwise_matrix(segs, split=False): # def dmerge(x, y): return split_vi(x, y)[0] # def dsplit(x, y): return split_vi(x, y)[1] # def split_vi_threshold(tup): # def vi_by_threshold(ucm, gt, ignore_seg=[], ignore_gt=[], npoints=None, # nprocessors=None): # def rand_by_threshold(ucm, gt, npoints=None): # def adapted_rand_error(seg, gt, all_stats=False): # def calc_entropy(split_vals, count): # def split_vi_mem(x, y): # def divide_rows(matrix, column, in_place=False): # def divide_columns(matrix, row, in_place=False): # def vi_tables(x, y=None, ignore_x=[0], ignore_y=[0]): # def sorted_vi_components(s1, s2, ignore1=[0], ignore2=[0], compress=False): # def split_components(idx, cont, num_elems=4, axis=0): # def rand_values(cont_table): # def rand_index(x, y=None): # def adj_rand_index(x, y=None): # def fm_index(x, y=None): # def reduce_vi(fn_pattern='testing/%i/flat-single-channel-tr%i-%i-%.2f.lzf.h5', # iterable=[(ts, tr, ts) for ts, tr in it.permutations(range(8), 2)], # thresholds=np.arange(0, 1.01, 0.01)): # def sem(ar, axis=None): # def vi_statistics(vi_table): # class csrRowExpandableCSR(sparse.csr_matrix): . Output only the next line.
ct = ev.contingency_table(seg, gt, ignore_seg=[], ignore_gt=[])
Using the snippet: <|code_start|> rundir = os.path.dirname(__file__) def time_me(function): def wrapped(*args, **kwargs): start = time.time() r = function(*args, **kwargs) end = time.time() return r, (end-start)*1000 return wrapped test_idxs = list(range(4)) num_tests = len(test_idxs) fns = [os.path.join(rundir, 'toy-data/test-%02i-probabilities.txt' % i) for i in test_idxs] probs = list(map(np.loadtxt, fns)) fns = [os.path.join(rundir, 'toy-data/test-%02i-watershed.txt' % i) for i in test_idxs] results = [np.loadtxt(fn, dtype=np.int32) for fn in fns] landscape = np.array([1,0,1,2,1,3,2,0,2,4,1,0]) def test_watershed_images(): <|code_end|> , determine the next line of code. You have imports: import os import time import numpy as np from scipy import ndimage as nd from numpy.testing import assert_array_equal, assert_array_less from gala import morpho from numpy import testing and context (class names, function names, or code) available: # Path: gala/morpho.py # def complement(a): # def remove_merged_boundaries(labels, connectivity=1): # def morphological_reconstruction(marker, mask, connectivity=1): # def hminima(a, thresh): # def regional_minima(a, connectivity=1): # def impose_minima(a, minima, connectivity=1): # def minimum_seeds(current_seeds, min_seed_coordinates, connectivity=1): # def split_exclusions(image, labels, exclusions, dilation=0, connectivity=1, # standard_seeds=False): # def watershed(a, seeds=None, connectivity=1, mask=None, smooth_thresh=0.0, # smooth_seeds=False, minimum_seed_size=0, dams=False, # override_skimage=False, show_progress=False): # def multiscale_regular_seeds(off_limits, num_seeds): # def _thin_seeds(seeds_img, step): # def multiscale_seed_sequence(prob, l1_threshold=0, grid_density=10): # def pipeline_compact_watershed(prob, *, # invert_prob=True, # l1_threshold=0, # grid_density=10, # compactness=0.01, # n_jobs=1): # def _euclid_dist(a, b): # def compact_watershed(a, seeds, *, compactness=0.01, connectivity=1): # def watershed_sequence(a, seeds=None, mask=None, axis=0, n_jobs=1, **kwargs): # def manual_split(probs, seg, body, seeds, connectivity=1, boundary_seeds=None): # def relabel_connected(im, connectivity=1): # def smallest_int_dtype(number, signed=False, mindtype=None): # def _is_container(a): # def pad(ar, vals, axes=None): # def juicy_center(ar, skinsize=1): # def surfaces(ar, skinsize=1): # def hollowed(ar, skinsize=1): # def build_levels_dict(a): # def build_neighbors_array(ar, connectivity=1): # def raveled_steps_to_neighbors(shape, connectivity=1): # def get_neighbor_idxs(ar, idxs, connectivity=1): # def orphans(a): # def non_traversing_segments(a): # def damify(a, in_place=False): # def seg_to_bdry(seg, connectivity=1): # def undam(seg): . Output only the next line.
wss = [morpho.watershed(probs[i], dams=(i == 0)) for i in range(2)]
Given snippet: <|code_start|> def test_cremi_roundtrip(): raw_image = np.random.randint(256, size=(5, 100, 100), dtype=np.uint8) labels = np.random.randint(4096, size=raw_image.shape, dtype=np.uint64) for ax in range(labels.ndim): labels.sort(axis=ax) # try to get something vaguely contiguous. =P with temporary_file('.hdf') as fout: <|code_end|> , continue by predicting the next line. Consider current file imports: from gala import imio from skimage._shared._tempfile import temporary_file import h5py import numpy as np and context: # Path: gala/imio.py # def read_image_stack(fn, *args, **kwargs): # def write_image_stack(npy_vol, fn, **kwargs): # def pil_to_numpy(img): # def read_multi_page_tif(fn, crop=[None]*6): # def write_png_image_stack(npy_vol, fn, axis=-1, bitdepth=None): # def extract_segments(seg, ids): # def write_vtk(ar, fn, spacing=[1.0, 1.0, 1.0]): # def read_vtk(fin): # def read_h5_stack(fn, group='stack', crop=[None]*6, **kwargs): # def compute_sp_to_body_map(sps, bodies): # def write_mapped_segmentation(superpixel_map, sp_to_body_map, fn, # sp_group='stack', sp_to_body_group='transforms'): # def read_mapped_segmentation(fn, # sp_group='stack', sp_to_body_group='transforms'): # def apply_segmentation_map(superpixels, sp_to_body_map): # def read_mapped_segmentation_raw(fn, # sp_group='stack', sp_to_body_group='transforms'): # def write_h5_stack(npy_vol, fn, group='stack', compression=None, chunks=None, # shuffle=None, attrs=None): # def ucm_to_raveler(ucm, sp_threshold=0.0, body_threshold=0.1, **kwargs): # def segs_to_raveler(sps, bodies, min_size=0, do_conn_comp=False, sps_out=None): # def raveler_serial_section_map(nd_map, min_size=0, do_conn_comp=False, # globally_unique_ids=True): # def serial_section_map(nd_map, min_size=0, do_conn_comp=False, # globally_unique_ids=True): # def label_fct(a): # def remove_small(a): # def write_to_raveler(sps, sp_to_segment, segment_to_body, directory, gray=None, # raveler_dir='/usr/local/raveler-hdf', nproc_contours=16, # body_annot=None): # def call(arglist): # def raveler_output_shortcut(svs, seg, gray, outdir, sps_out=None): # def raveler_body_annotations(orphans, non_traversing=None): # def write_json(annot, fn='annotations-body.json', directory=None): # def raveler_rgba_to_int(im, ignore_alpha=True): # def raveler_to_labeled_volume(rav_export_dir, get_glia=False, # use_watershed=False, probability_map=None, crop=None): # def write_ilastik_project(images, labels, fn, label_names=None): # def write_ilastik_batch_volume(im, fn): # def read_prediction_from_ilastik_batch(fn, **kwargs): # def read_cremi(fn, datasets=['/volumes/raw', '/volumes/labels/neuron_ids']): # def write_cremi(data_dict, fn, resolution=(40., 4., 4.)): which might include code, classes, or functions. Output only the next line.
imio.write_cremi({'/volumes/raw': raw_image,
Predict the next line after this snippet: <|code_start|># -*- test-case-name: mamba.scripts.test.test_mamba_admin -*- # Copyright (c) 2012 - 2013 Oscar Campos <oscar.campos@member.fsf.org> # See LICENSE for more details from __future__ import print_function try: assert pip PIP_IS_AVAILABLE = True except ImportError: PIP_IS_AVAILABLE = False # This is an auto-generated property, Do not edit it. version = versions.Version('package', 0, 0, 0) def show_version(): print('Mamba Package tools v{}'.format(version.short())) <|code_end|> using the current file's imports: import os import sys import zipfile import tarfile import getpass import subprocess import pip from string import Template from twisted.python import usage, filepath from mamba import copyright from mamba.scripts import commons from mamba._version import versions from mamba.utils import json from mamba.utils.checkers import Checkers from mamba.utils.output import darkred, darkgreen from setuptools.command.easy_install import main and any relevant context from other files: # Path: mamba/copyright.py # # Path: mamba/_version.py # # Path: mamba/utils/checkers.py # class Checkers(object): # """Just implement common methods to perform checks on user inputs # # .. versionadded:: 0.3.6 # """ # # NONE, CAPS, NUMERIC, SYMBOLS = [1 << i for i in range(4)] # MIN_LENGTH, NO_CAPS, NO_NUMBERS, NO_SYMBOLS = range(4) # # def __init__(self): # super(Checkers, self).__init__() # # @staticmethod # def check_email(email): # """Checks if the given email is RFC2822 compliant # # http://www.rfc-editor.org/rfc/rfc2822.txt # """ # # RFC2822 = re.compile( # r"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*" # "+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9]" # ")?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?" # ) # return True if RFC2822.match(email) is not None else False # # @staticmethod # def check_password(password, min_length=8, characters=NONE): # """Check for valid password using the given parameters # # :param password: the password to check # :type password: str # :param min_length: minimum password length (default 8) # :type min_length: int # :param characters: the valid cahracters to be used. # A complete list of the possible options is as follows: # # * CAPS: Whatever can be used, we force some cap # * NUMERIC: Whatever can be used, we force numbers # * SYMBOLS: Whatever can be used, we force symbols # # :returns: a tuple containing a boolean value and a list of dicts # """ # # errors = [] # if len(password) < min_length: # errors.append({ # 'eng_desc': 'Minimum length is {}, but {} given'.format( # min_length, len(password)), # 'type': Checkers.MIN_LENGTH, # 'data': {'min_length': min_length, 'given': len(password)} # }) # # if characters & Checkers.CAPS > 0: # if len(filter(str.isupper, password)) == 0: # errors.append({ # 'eng_desc': 'String must contain caps', # 'type': Checkers.NO_CAPS # }) # # if characters & Checkers.NUMERIC > 0: # if len(filter(str.isdigit, password)) == 0: # errors.append({ # 'eng_desc': 'String must comntain numbers', # 'type': Checkers.NO_NUMBERS # }) # # if characters & Checkers.SYMBOLS > 0: # if len(filter(lambda x: x in string.punctuation, password)) == 0: # errors.append({ # 'eng_desc': 'String must comntain symbols', # 'type': Checkers.NO_SYMBOLS # }) # # return len(errors) == 0, errors # # Path: mamba/utils/output.py # def resetColor(): # def style_to_ansi_code(style): # def colorize(color_key, text): # def create_color_func(color): # def closure(*args): . Output only the next line.
print(copyright.copyright)
Predict the next line after this snippet: <|code_start|># -*- test-case-name: mamba.scripts.test.test_mamba_admin -*- # Copyright (c) 2012 - 2013 Oscar Campos <oscar.campos@member.fsf.org> # See LICENSE for more details from __future__ import print_function try: assert pip PIP_IS_AVAILABLE = True except ImportError: PIP_IS_AVAILABLE = False # This is an auto-generated property, Do not edit it. <|code_end|> using the current file's imports: import os import sys import zipfile import tarfile import getpass import subprocess import pip from string import Template from twisted.python import usage, filepath from mamba import copyright from mamba.scripts import commons from mamba._version import versions from mamba.utils import json from mamba.utils.checkers import Checkers from mamba.utils.output import darkred, darkgreen from setuptools.command.easy_install import main and any relevant context from other files: # Path: mamba/copyright.py # # Path: mamba/_version.py # # Path: mamba/utils/checkers.py # class Checkers(object): # """Just implement common methods to perform checks on user inputs # # .. versionadded:: 0.3.6 # """ # # NONE, CAPS, NUMERIC, SYMBOLS = [1 << i for i in range(4)] # MIN_LENGTH, NO_CAPS, NO_NUMBERS, NO_SYMBOLS = range(4) # # def __init__(self): # super(Checkers, self).__init__() # # @staticmethod # def check_email(email): # """Checks if the given email is RFC2822 compliant # # http://www.rfc-editor.org/rfc/rfc2822.txt # """ # # RFC2822 = re.compile( # r"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*" # "+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9]" # ")?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?" # ) # return True if RFC2822.match(email) is not None else False # # @staticmethod # def check_password(password, min_length=8, characters=NONE): # """Check for valid password using the given parameters # # :param password: the password to check # :type password: str # :param min_length: minimum password length (default 8) # :type min_length: int # :param characters: the valid cahracters to be used. # A complete list of the possible options is as follows: # # * CAPS: Whatever can be used, we force some cap # * NUMERIC: Whatever can be used, we force numbers # * SYMBOLS: Whatever can be used, we force symbols # # :returns: a tuple containing a boolean value and a list of dicts # """ # # errors = [] # if len(password) < min_length: # errors.append({ # 'eng_desc': 'Minimum length is {}, but {} given'.format( # min_length, len(password)), # 'type': Checkers.MIN_LENGTH, # 'data': {'min_length': min_length, 'given': len(password)} # }) # # if characters & Checkers.CAPS > 0: # if len(filter(str.isupper, password)) == 0: # errors.append({ # 'eng_desc': 'String must contain caps', # 'type': Checkers.NO_CAPS # }) # # if characters & Checkers.NUMERIC > 0: # if len(filter(str.isdigit, password)) == 0: # errors.append({ # 'eng_desc': 'String must comntain numbers', # 'type': Checkers.NO_NUMBERS # }) # # if characters & Checkers.SYMBOLS > 0: # if len(filter(lambda x: x in string.punctuation, password)) == 0: # errors.append({ # 'eng_desc': 'String must comntain symbols', # 'type': Checkers.NO_SYMBOLS # }) # # return len(errors) == 0, errors # # Path: mamba/utils/output.py # def resetColor(): # def style_to_ansi_code(style): # def colorize(color_key, text): # def create_color_func(color): # def closure(*args): . Output only the next line.
version = versions.Version('package', 0, 0, 0)
Next line prediction: <|code_start|> if type(self['entry_points']) is not dict: raise usage.UsageError( 'the entry_points JSON string must be decoded as a dict' ) else: self['entry_points'] = {} if self['extra_directories'] is not None: try: self['extra_directories'] = json.loads( self['extra_directories'] ) except ValueError: raise usage.UsageError( 'invalid JSON extra_directories structure' ) if type(self['extra_directories']) is not list: raise usage.UsageError( 'the extra_directories JSON string ' 'must be decoded as a list' ) else: self['extra_directories'] = [] if self['author'] is None: self['author'] = getpass.getuser() if self['email'] is not None: <|code_end|> . Use current file imports: (import os import sys import zipfile import tarfile import getpass import subprocess import pip from string import Template from twisted.python import usage, filepath from mamba import copyright from mamba.scripts import commons from mamba._version import versions from mamba.utils import json from mamba.utils.checkers import Checkers from mamba.utils.output import darkred, darkgreen from setuptools.command.easy_install import main) and context including class names, function names, or small code snippets from other files: # Path: mamba/copyright.py # # Path: mamba/_version.py # # Path: mamba/utils/checkers.py # class Checkers(object): # """Just implement common methods to perform checks on user inputs # # .. versionadded:: 0.3.6 # """ # # NONE, CAPS, NUMERIC, SYMBOLS = [1 << i for i in range(4)] # MIN_LENGTH, NO_CAPS, NO_NUMBERS, NO_SYMBOLS = range(4) # # def __init__(self): # super(Checkers, self).__init__() # # @staticmethod # def check_email(email): # """Checks if the given email is RFC2822 compliant # # http://www.rfc-editor.org/rfc/rfc2822.txt # """ # # RFC2822 = re.compile( # r"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*" # "+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9]" # ")?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?" # ) # return True if RFC2822.match(email) is not None else False # # @staticmethod # def check_password(password, min_length=8, characters=NONE): # """Check for valid password using the given parameters # # :param password: the password to check # :type password: str # :param min_length: minimum password length (default 8) # :type min_length: int # :param characters: the valid cahracters to be used. # A complete list of the possible options is as follows: # # * CAPS: Whatever can be used, we force some cap # * NUMERIC: Whatever can be used, we force numbers # * SYMBOLS: Whatever can be used, we force symbols # # :returns: a tuple containing a boolean value and a list of dicts # """ # # errors = [] # if len(password) < min_length: # errors.append({ # 'eng_desc': 'Minimum length is {}, but {} given'.format( # min_length, len(password)), # 'type': Checkers.MIN_LENGTH, # 'data': {'min_length': min_length, 'given': len(password)} # }) # # if characters & Checkers.CAPS > 0: # if len(filter(str.isupper, password)) == 0: # errors.append({ # 'eng_desc': 'String must contain caps', # 'type': Checkers.NO_CAPS # }) # # if characters & Checkers.NUMERIC > 0: # if len(filter(str.isdigit, password)) == 0: # errors.append({ # 'eng_desc': 'String must comntain numbers', # 'type': Checkers.NO_NUMBERS # }) # # if characters & Checkers.SYMBOLS > 0: # if len(filter(lambda x: x in string.punctuation, password)) == 0: # errors.append({ # 'eng_desc': 'String must comntain symbols', # 'type': Checkers.NO_SYMBOLS # }) # # return len(errors) == 0, errors # # Path: mamba/utils/output.py # def resetColor(): # def style_to_ansi_code(style): # def colorize(color_key, text): # def create_color_func(color): # def closure(*args): . Output only the next line.
if not Checkers.check_email(self['email']):
Here is a snippet: <|code_start|> elif self.options.subCommand == 'uninstall': self._handle_uninstall_command() else: print(self.options) def _handle_pack_command(self): """Pack the current mamba application """ try: mamba_services = commons.import_services() mamba_services.config.Application('config/application.json') except Exception: mamba_services_not_found() use_egg = self.options.subOptions.opts['egg'] command = 'bdist_egg' if use_egg else 'sdist' try: print('Packing {} application into {} format...'.format( self.options.subOptions.opts['name'], 'egg' if use_egg else 'source' ).ljust(73), end='') Packer().pack_application( command, self.options.subOptions, mamba_services.config.Application() ) print('[{}]'.format(darkgreen('Ok'))) except: <|code_end|> . Write the next line using the current file imports: import os import sys import zipfile import tarfile import getpass import subprocess import pip from string import Template from twisted.python import usage, filepath from mamba import copyright from mamba.scripts import commons from mamba._version import versions from mamba.utils import json from mamba.utils.checkers import Checkers from mamba.utils.output import darkred, darkgreen from setuptools.command.easy_install import main and context from other files: # Path: mamba/copyright.py # # Path: mamba/_version.py # # Path: mamba/utils/checkers.py # class Checkers(object): # """Just implement common methods to perform checks on user inputs # # .. versionadded:: 0.3.6 # """ # # NONE, CAPS, NUMERIC, SYMBOLS = [1 << i for i in range(4)] # MIN_LENGTH, NO_CAPS, NO_NUMBERS, NO_SYMBOLS = range(4) # # def __init__(self): # super(Checkers, self).__init__() # # @staticmethod # def check_email(email): # """Checks if the given email is RFC2822 compliant # # http://www.rfc-editor.org/rfc/rfc2822.txt # """ # # RFC2822 = re.compile( # r"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*" # "+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9]" # ")?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?" # ) # return True if RFC2822.match(email) is not None else False # # @staticmethod # def check_password(password, min_length=8, characters=NONE): # """Check for valid password using the given parameters # # :param password: the password to check # :type password: str # :param min_length: minimum password length (default 8) # :type min_length: int # :param characters: the valid cahracters to be used. # A complete list of the possible options is as follows: # # * CAPS: Whatever can be used, we force some cap # * NUMERIC: Whatever can be used, we force numbers # * SYMBOLS: Whatever can be used, we force symbols # # :returns: a tuple containing a boolean value and a list of dicts # """ # # errors = [] # if len(password) < min_length: # errors.append({ # 'eng_desc': 'Minimum length is {}, but {} given'.format( # min_length, len(password)), # 'type': Checkers.MIN_LENGTH, # 'data': {'min_length': min_length, 'given': len(password)} # }) # # if characters & Checkers.CAPS > 0: # if len(filter(str.isupper, password)) == 0: # errors.append({ # 'eng_desc': 'String must contain caps', # 'type': Checkers.NO_CAPS # }) # # if characters & Checkers.NUMERIC > 0: # if len(filter(str.isdigit, password)) == 0: # errors.append({ # 'eng_desc': 'String must comntain numbers', # 'type': Checkers.NO_NUMBERS # }) # # if characters & Checkers.SYMBOLS > 0: # if len(filter(lambda x: x in string.punctuation, password)) == 0: # errors.append({ # 'eng_desc': 'String must comntain symbols', # 'type': Checkers.NO_SYMBOLS # }) # # return len(errors) == 0, errors # # Path: mamba/utils/output.py # def resetColor(): # def style_to_ansi_code(style): # def colorize(color_key, text): # def create_color_func(color): # def closure(*args): , which may include functions, classes, or code. Output only the next line.
print('[{}]'.format(darkred('Fail')))
Using the snippet: <|code_start|> elif self.options.subCommand == 'install': self._handle_install_command() elif self.options.subCommand == 'uninstall': self._handle_uninstall_command() else: print(self.options) def _handle_pack_command(self): """Pack the current mamba application """ try: mamba_services = commons.import_services() mamba_services.config.Application('config/application.json') except Exception: mamba_services_not_found() use_egg = self.options.subOptions.opts['egg'] command = 'bdist_egg' if use_egg else 'sdist' try: print('Packing {} application into {} format...'.format( self.options.subOptions.opts['name'], 'egg' if use_egg else 'source' ).ljust(73), end='') Packer().pack_application( command, self.options.subOptions, mamba_services.config.Application() ) <|code_end|> , determine the next line of code. You have imports: import os import sys import zipfile import tarfile import getpass import subprocess import pip from string import Template from twisted.python import usage, filepath from mamba import copyright from mamba.scripts import commons from mamba._version import versions from mamba.utils import json from mamba.utils.checkers import Checkers from mamba.utils.output import darkred, darkgreen from setuptools.command.easy_install import main and context (class names, function names, or code) available: # Path: mamba/copyright.py # # Path: mamba/_version.py # # Path: mamba/utils/checkers.py # class Checkers(object): # """Just implement common methods to perform checks on user inputs # # .. versionadded:: 0.3.6 # """ # # NONE, CAPS, NUMERIC, SYMBOLS = [1 << i for i in range(4)] # MIN_LENGTH, NO_CAPS, NO_NUMBERS, NO_SYMBOLS = range(4) # # def __init__(self): # super(Checkers, self).__init__() # # @staticmethod # def check_email(email): # """Checks if the given email is RFC2822 compliant # # http://www.rfc-editor.org/rfc/rfc2822.txt # """ # # RFC2822 = re.compile( # r"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*" # "+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9]" # ")?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?" # ) # return True if RFC2822.match(email) is not None else False # # @staticmethod # def check_password(password, min_length=8, characters=NONE): # """Check for valid password using the given parameters # # :param password: the password to check # :type password: str # :param min_length: minimum password length (default 8) # :type min_length: int # :param characters: the valid cahracters to be used. # A complete list of the possible options is as follows: # # * CAPS: Whatever can be used, we force some cap # * NUMERIC: Whatever can be used, we force numbers # * SYMBOLS: Whatever can be used, we force symbols # # :returns: a tuple containing a boolean value and a list of dicts # """ # # errors = [] # if len(password) < min_length: # errors.append({ # 'eng_desc': 'Minimum length is {}, but {} given'.format( # min_length, len(password)), # 'type': Checkers.MIN_LENGTH, # 'data': {'min_length': min_length, 'given': len(password)} # }) # # if characters & Checkers.CAPS > 0: # if len(filter(str.isupper, password)) == 0: # errors.append({ # 'eng_desc': 'String must contain caps', # 'type': Checkers.NO_CAPS # }) # # if characters & Checkers.NUMERIC > 0: # if len(filter(str.isdigit, password)) == 0: # errors.append({ # 'eng_desc': 'String must comntain numbers', # 'type': Checkers.NO_NUMBERS # }) # # if characters & Checkers.SYMBOLS > 0: # if len(filter(lambda x: x in string.punctuation, password)) == 0: # errors.append({ # 'eng_desc': 'String must comntain symbols', # 'type': Checkers.NO_SYMBOLS # }) # # return len(errors) == 0, errors # # Path: mamba/utils/output.py # def resetColor(): # def style_to_ansi_code(style): # def colorize(color_key, text): # def create_color_func(color): # def closure(*args): . Output only the next line.
print('[{}]'.format(darkgreen('Ok')))
Here is a snippet: <|code_start|> if (config.Database().create_table_behaviours.get('drop_table') and not config.Database().create_table_behaviours.get( 'create_if_not_exists')): query = '{};\n{}'.format( self.drop_table(), query ) return query def drop_table(self): """Return SQLite syntax for drop this model table """ existance = config.Database().drop_table_behaviours.get( 'drop_if_exists', True) query = 'DROP TABLE {}{}'.format( 'IF EXISTS ' if existance else '', self.model.__storm_table__ ) return query @staticmethod def register(): """Register this component """ try: <|code_end|> . Write the next line using the current file imports: import inspect from sqlite3 import sqlite_version_info from storm import properties from twisted.python import components from storm.references import Reference from singledispatch import singledispatch from mamba.utils import config from mamba.core.interfaces import IMambaSQL from mamba.core.adapters import MambaSQLAdapter from mamba.enterprise.common import CommonSQL, NativeEnum and context from other files: # Path: mamba/core/adapters.py # class MambaSQLAdapter: # # implements(IMambaSQL) # # def __init__(self, original): # self.original = original # # if not hasattr(self.original.model, '_storm_columns'): # get_obj_info(self.original.model) # # def parse_column(self, column): # """Parse a Storm column to the correct SQL value # """ # # return self.original.parse_column(column) # # def detect_primary_key(self): # """Detect and reeturn the primary key for the table # """ # # return self.original.detect_primary_key() # # def create_table(self): # """ # Return the SQL syntax string to create a table to the selected # underlying database system # """ # # return self.original.create_table() # # def drop_table(self): # """ # Return the SQL syntax string to drop a table from the selected # underlying database system # """ # # return self.original.drop_table() # # def insert_data(self, scheme): # """Return the SQL syntax string to insert data that populate a table # """ # # return self.original.insert_data(scheme) # # def parse_references(self): # """Return the SQL syntax to create foreign keys for PostgreSQL # """ # # return self.original.parse_references() # # def parse_indexes(self): # """Return the SQL syntax to create indexes for PostgreSQL or SQLite # """ # # return self.original.parse_indexes() , which may include functions, classes, or code. Output only the next line.
components.registerAdapter(MambaSQLAdapter, SQLite, IMambaSQL)
Given the code snippet: <|code_start|># -*- test-case-name: mamba.scripts.test.test_mamba_admin -*- # Copyright (c) 2012 - 2013 Oscar Campos <oscar.campos@member.fsf.org> # See LICENSE for more details from __future__ import print_function # This is an auto-generated property. Do not edit it. version = versions.Version('model', 0, 2, 2) def show_version(): print('Mamba Model tools v{}'.format(version.short())) <|code_end|> , generate the next line using the imports in this file: import re import sys import getpass import datetime from string import Template from twisted.python import usage, filepath from mamba import copyright from mamba.scripts import commons from mamba._version import versions from mamba.utils.camelcase import CamelCase and context (functions, classes, or occasionally code) from other files: # Path: mamba/copyright.py # # Path: mamba/_version.py . Output only the next line.
print(copyright.copyright)
Predict the next line for this snippet: <|code_start|> # Copyright (c) 2012 - Oscar Campos <oscar.campos@member.fsf.org> # See LICENSE for more details """ Tests for mamba.utils.converter """ class ConverterTest(unittest.TestCase): def setUp(self): self.test_data = { int: 1, long: 1L, float: 1.0, bool: True, str: 'String', unicode: u'Unicode', tuple: (1, 2), list: [1, 2], dict: {} } def test_converts_primitives_to_json(self): <|code_end|> with the help of current file imports: import decimal from twisted.trial import unittest from mamba.utils import json from mamba.utils.converter import Converter and context from other files: # Path: mamba/utils/converter.py # class Converter(object): # """ # Object Converter class # """ # # primitives = (int, long, float, bool, str, unicode) # containers = (str, tuple, list, dict) # # def __init__(self): # super(Converter, self).__init__() # # @staticmethod # def serialize(obj): # """Serialize an object and returns it back""" # try: # if type(obj) not in Converter.primitives: # if type(obj) is dict: # tmpdict = {} # for key, value in obj.iteritems(): # tmpdict.update({ # key: Converter.serialize(value) # }) # # return tmpdict # elif getattr(obj, '__class__', False): # if type(obj) not in Converter.containers: # tmpdict = {} # if getattr(obj, '__dict__', False): # for key, value in obj.__dict__.iteritems(): # if not key.startswith('_'): # value = Converter.fix_common(value) # if hasattr(value, '__class__'): # value = Converter.serialize(value) # tmpdict.update({key: value}) # else: # for item in [ # p for p in dir(obj) if not p.startswith('_') # ]: # data = Converter.fix_common(getattr(obj, item)) # # if (data not in Converter.primitives # and data not in Converter.containers): # data = Converter.serialize(data) # tmpdict.update({item: data}) # # return tmpdict # elif type(obj) is collections.Iterable: # values = [] # for value in obj: # values.append(Converter.serialize(value)) # # return values # except AttributeError as error: # log.msg(error, logLevel=logging.WARN) # # return obj # # @staticmethod # def fix_common(value): # """Fix commons uncommons # """ # # if type(value) is decimal.Decimal: # value = str(value) # elif value is None: # value = 'null' # # return value , which may contain function names, class names, or code. Output only the next line.
for t in set(Converter.primitives + Converter.containers):
Continue the code snippet: <|code_start|> # Copyright (c) 2012 - Oscar Campos <oscar.campos@member.fsf.org> # See LICENSE for more details """ Tests for mamba.core.decorators """ hit_count = 0 class TestDecorators(unittest.TestCase): def setUp(self): global hit_count hit_count = 0 def test_cache_is_cahing(self): <|code_end|> . Use current file imports: from twisted.trial import unittest from mamba.core import decorators and context (classes, functions, or code) from other files: # Path: mamba/core/decorators.py # def cache(size=16): # def decorator(func): # def wrapper(*args, **kwargs): # def unlimited_cache(func): # def wrapper(*args, **kwargs): . Output only the next line.
@decorators.cache(size=16)
Predict the next line for this snippet: <|code_start|># See LICENSE for more details """ .. module:: fixtures :paltform: Unix, Windows :synopsis: Wrapper around Storm patch/schema mechanism to make mamba model objects testing easier .. moduleauthor:: Oscar Campos <oscar.campos@member.fsf.org> """ class FixtureError(Exception): """Raised on fixture errors """ class Fixture(schema.Schema): """Create, insert, drop and clean table schemas. """ def __init__(self, model=None, path='../', engine=ENGINE.NATIVE): super(Fixture, self).__init__( creates=set(), drops=set(), deletes=set(), patch_package=None) self._path = path self._model = model self._original_databases = {} <|code_end|> with the help of current file imports: import os from contextlib import contextmanager from mamba.enterprise import schema from mamba.unittest.database_helpers import TestableDatabase, ENGINE and context from other files: # Path: mamba/unittest/database_helpers.py # class TestableDatabase(Database): # """Testable database object # """ # # pool = DummyThreadPool() # # def __init__(self, engine=ENGINE.NATIVE): # super(TestableDatabase, self).__init__(testing=True) # self.engine = engine # self.tmp_file = None # self._initialize() # # def __del__(self): # if self.tmp_file is not None: # os.unlink(self.tmp_file) # self.tmp_file = None # # def _initialize(self): # """Initialize the object with the right database configuration # """ # # provideUtility(global_zstorm, IZStorm) # zstorm = getUtility(IZStorm) # zstorm._reset() # make sure we are not using an old configuration # if self.engine == ENGINE.NATIVE: # if self.backend == 'sqlite' and sqlite_version_info >= (3, 6, 19): # uri = '{}?foreign_keys=1'.format(config.Database().uri) # else: # uri = config.Database().uri # elif self.engine == ENGINE.INMEMORY: # if sqlite_version_info >= (3, 6, 19): # uri = 'sqlite:?foreign_keys=1' # else: # uri = 'sqlite:' # else: # tmpfile = tempfile.NamedTemporaryFile(delete=False) # self.tmp_file = tmpfile.name # if sqlite_version_info >= (3, 6, 19): # uri = 'sqlite:{}?foreign_keys=1'.format(tmpfile.name) # else: # uri = 'sqlite:{}'.format(tmpfile.name) # tmpfile.close() # # zstorm.set_default_uri('mamba', uri) # self.started = True # # def start(self): # """Stub method that mimic Database.start # """ # # if not self.started: # self.started = True # # def stop(self): # """Stub method that mimic Database.stop # """ # # if self.started: # self.started = False # # class ENGINE(Names): # """Constants representing different ENGINE options # """ # # NATIVE = NamedConstant() # what is configured # INMEMORY = NamedConstant() # in memory SQLite # PERSISTENT = NamedConstant() # persistent SQLite , which may contain function names, class names, or code. Output only the next line.
self.testable_database = TestableDatabase(engine)
Given the following code snippet before the placeholder: <|code_start|># -*- test-case-name: mamba.test.test_fixtures -*- # Copyright (c) 2012 - 2014 Oscar Campos <oscar.campos@member.fsf.org> # See LICENSE for more details """ .. module:: fixtures :paltform: Unix, Windows :synopsis: Wrapper around Storm patch/schema mechanism to make mamba model objects testing easier .. moduleauthor:: Oscar Campos <oscar.campos@member.fsf.org> """ class FixtureError(Exception): """Raised on fixture errors """ class Fixture(schema.Schema): """Create, insert, drop and clean table schemas. """ <|code_end|> , predict the next line using imports from the current file: import os from contextlib import contextmanager from mamba.enterprise import schema from mamba.unittest.database_helpers import TestableDatabase, ENGINE and context including class names, function names, and sometimes code from other files: # Path: mamba/unittest/database_helpers.py # class TestableDatabase(Database): # """Testable database object # """ # # pool = DummyThreadPool() # # def __init__(self, engine=ENGINE.NATIVE): # super(TestableDatabase, self).__init__(testing=True) # self.engine = engine # self.tmp_file = None # self._initialize() # # def __del__(self): # if self.tmp_file is not None: # os.unlink(self.tmp_file) # self.tmp_file = None # # def _initialize(self): # """Initialize the object with the right database configuration # """ # # provideUtility(global_zstorm, IZStorm) # zstorm = getUtility(IZStorm) # zstorm._reset() # make sure we are not using an old configuration # if self.engine == ENGINE.NATIVE: # if self.backend == 'sqlite' and sqlite_version_info >= (3, 6, 19): # uri = '{}?foreign_keys=1'.format(config.Database().uri) # else: # uri = config.Database().uri # elif self.engine == ENGINE.INMEMORY: # if sqlite_version_info >= (3, 6, 19): # uri = 'sqlite:?foreign_keys=1' # else: # uri = 'sqlite:' # else: # tmpfile = tempfile.NamedTemporaryFile(delete=False) # self.tmp_file = tmpfile.name # if sqlite_version_info >= (3, 6, 19): # uri = 'sqlite:{}?foreign_keys=1'.format(tmpfile.name) # else: # uri = 'sqlite:{}'.format(tmpfile.name) # tmpfile.close() # # zstorm.set_default_uri('mamba', uri) # self.started = True # # def start(self): # """Stub method that mimic Database.start # """ # # if not self.started: # self.started = True # # def stop(self): # """Stub method that mimic Database.stop # """ # # if self.started: # self.started = False # # class ENGINE(Names): # """Constants representing different ENGINE options # """ # # NATIVE = NamedConstant() # what is configured # INMEMORY = NamedConstant() # in memory SQLite # PERSISTENT = NamedConstant() # persistent SQLite . Output only the next line.
def __init__(self, model=None, path='../', engine=ENGINE.NATIVE):
Here is a snippet: <|code_start|> tmp_data = '\r\n'.join(tmp_data) tmp_data += '\r\nSec-WebSocket-Version: 29\r\n\r\n' self.port.dataReceived(tmp_data) self.assertEqual( self.tr.value(), 'HTTP/1.1 400 Bad RequestServer: MambaWebSocketWrapper/1.0\r\n' 'Date: {}\r\n' 'Upgrade: WebSocket\r\n' 'Connection: Upgrade\r\n' 'Sec-WebSocket-Version: 13\r\n' 'Sec-WebSocket-Version: 8, 7\r\n'.format(datetimeToString()) ) def test_returned_key_for_hybi00(self): key1 = '4 @1 46546xW\%0l 1 5' key2 = '12998 5 Y3 1 .P00' challenge = '^n:ds[4U' first = int(''.join(i for i in key1 if i in digits)) / key1.count(' ') second = int(''.join(i for i in key2 if i in digits)) / key2.count(' ') nonce = pack('>II8s', first, second, challenge) self.port.dataReceived(hybi00_data) self.assertTrue(md5(nonce).digest() in self.tr.value()) def test_generate_hybi00frame(self): <|code_end|> . Write the next line using the current file imports: import hashlib from twisted.trial import unittest from twisted.internet import address, task from twisted.web.http import datetimeToString from twisted.test import test_policies, proto_helpers from mamba.web import websocket from string import digits from struct import pack from hashlib import md5 and context from other files: # Path: mamba/web/websocket.py # DATA, CLOSE, PING, PONG = range(4) # frame control # HYBI00, HYBI07, HYBI10, RFC6455 = range(4) # supported versions # HANDSHAKE, NEGOTIATION, CHALLENGE, FRAMES = range(4) # state machine. # NORMAL_CLOSURE = 0x3e8 # class WebSocketError(Exception): # class InvalidProtocol(WebSocketError): # class NoWebSocketCodec(WebSocketError): # class InvalidProtocolVersion(WebSocketError): # class InvalidCharacterInHyBi00Frame(WebSocketError): # class ReservedFlagsInFrame(WebSocketError): # class UnknownFrameOpcode(WebSocketError): # class HandshakePreamble(object): # class HyBi00HandshakePreamble(HandshakePreamble): # class HyBi07HandshakePreamble(HandshakePreamble): # class InvalidProtocolVersionPreamble(HandshakePreamble): # class HyBi00Frame(object): # class HyBi07Frame(object): # class WebSocketProtocol(ProtocolWrapper): # class WebSocketFactory(WrappingFactory): # def __init__(self): # def write_to_transport(self, transport): # def __init__(self, protocol): # def write_to_transport(self, transport, response): # def __init__(self, protocol): # def generate_accept_opening(self, protocol): # def __init__(self): # def __init__(self, buf): # def is_valid(self): # def generate(self, opcode=0x00): # def parse(self): # def __init__(self, buf): # def generate(self, opcode=0x1): # def parse(self): # def mask(self, buf, key): # def __init__(self, *args, **kwargs): # def secure(self): # def codecs(self): # def is_hybi00(self): # def dataReceived(self, data): # def handle_handshake(self): # def handle_negotiation(self): # def handle_challenge(self): # def handle_frames(self): # def write(self, data): # def writeSequence(self, data): # def _send(self, binary=False): # def close(self, reason=''): # def complete_hybi00(self, challenge): # def parse_headers(self, headers): , which may include functions, classes, or code. Output only the next line.
frame = websocket.HyBi00Frame('LEMOOOOOOOOOON')
Given the code snippet: <|code_start|># -*- test-case-name: mamba.scripts.test.test_mamba_admin -*- # Copyright (c) 2012 - 2013 Oscar Campos <oscar.campos@member.fsf.org> # See LICENSE for more details from __future__ import print_function # This is an auto-generated property. Do not edit it. version = versions.Version('view', 0, 1, 4) def show_version(): print('Mamba View Tools v{}'.format(version.short())) <|code_end|> , generate the next line using the imports in this file: import re import sys import datetime from string import Template from twisted.python import usage, filepath from mamba import copyright from mamba.scripts import commons from mamba._version import versions from mamba.utils.camelcase import CamelCase from mamba.scripts._sql import mamba_services_not_found and context (functions, classes, or occasionally code) from other files: # Path: mamba/copyright.py # # Path: mamba/_version.py . Output only the next line.
print('{}'.format(copyright.copyright))
Given snippet: <|code_start|> class TestScoreManager(unittest.TestCase): def setUp(self): self.stride_pattern = r'^(\d)(\d)(\d)(\d)(\d)(\d)$' self.skipped_pattern = r'^(19|20)(\d\d)[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$|^(19|20)(\d\d)(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])$' <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest from elem.score import ScoreManager from elem.score import InvalidExample and context: # Path: elem/score/score_manager.py # class ScoreManager(object): # def __init__(self): # self.scores = dict() # # def add_score(self, name, pattern, example=None): # if name not in self.scores.keys(): # self.scores[name] = Score(name, pattern, example) # # def delete_score(self, name): # self.scores.pop(name) # # def get_pattern(self, name): # return self.scores[name].pattern # # def update_score(self, name, pattern): # self.scores[name] = Score(name, pattern) # # def is_valid(self, name, value): # return self.scores[name].is_valid(value) # # def __str__(self): # score_strings = ['name,pattern,example'] # for _, score in self.scores.iteritems(): # score_strings.append(str(score)) # return '\n'.join(score_strings) # # def __iter__(self): # return iter(self.scores) # # Path: elem/score/score.py # class InvalidExample(Exception): # def __init__(self, name, pattern, example): # message = "For score {0}, example {1} does not match pattern {2}.".format(name, example, pattern) # super(InvalidExample, self).__init__(message) which might include code, classes, or functions. Output only the next line.
self.manager = ScoreManager()
Using the snippet: <|code_start|> self.stride_pattern = r'^(\d)(\d)(\d)(\d)(\d)(\d)$' self.skipped_pattern = r'^(19|20)(\d\d)[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$|^(19|20)(\d\d)(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])$' self.manager = ScoreManager() def test_add(self): self.assertEqual(len(self.manager.scores), 0) self.manager.add_score('stride', self.stride_pattern) self.assertEqual(len(self.manager.scores), 1) self.assertIn('stride', self.manager.scores.keys()) #Add again, ensure it doesn't grow and the patter doesn't change self.manager.add_score('stride', r'\d\d\d\d\d\d\d') self.assertEqual(len(self.manager.scores), 1) self.assertEqual(self.stride_pattern, self.manager.get_pattern('stride')) #Add new score self.manager.add_score('skipped', self.skipped_pattern) self.assertEqual(len(self.manager.scores), 2) self.assertIn('stride', self.manager.scores.keys()) self.assertIn('skipped', self.manager.scores.keys()) def test_delete_no_key(self): with self.assertRaises(KeyError): self.manager.delete_score('stride') def test_delete(self): self.manager.add_score('stride', self.stride_pattern) self.assertEqual(len(self.manager.scores), 1) self.manager.delete_score('stride') self.assertEqual(len(self.manager.scores), 0) def test_bad_example(self): <|code_end|> , determine the next line of code. You have imports: import unittest from elem.score import ScoreManager from elem.score import InvalidExample and context (class names, function names, or code) available: # Path: elem/score/score_manager.py # class ScoreManager(object): # def __init__(self): # self.scores = dict() # # def add_score(self, name, pattern, example=None): # if name not in self.scores.keys(): # self.scores[name] = Score(name, pattern, example) # # def delete_score(self, name): # self.scores.pop(name) # # def get_pattern(self, name): # return self.scores[name].pattern # # def update_score(self, name, pattern): # self.scores[name] = Score(name, pattern) # # def is_valid(self, name, value): # return self.scores[name].is_valid(value) # # def __str__(self): # score_strings = ['name,pattern,example'] # for _, score in self.scores.iteritems(): # score_strings.append(str(score)) # return '\n'.join(score_strings) # # def __iter__(self): # return iter(self.scores) # # Path: elem/score/score.py # class InvalidExample(Exception): # def __init__(self, name, pattern, example): # message = "For score {0}, example {1} does not match pattern {2}.".format(name, example, pattern) # super(InvalidExample, self).__init__(message) . Output only the next line.
with self.assertRaises(InvalidExample) as error:
Given snippet: <|code_start|> class ScoreManager(object): def __init__(self): self.scores = dict() def add_score(self, name, pattern, example=None): if name not in self.scores.keys(): <|code_end|> , continue by predicting the next line. Consider current file imports: from elem.score import Score and context: # Path: elem/score/score.py # class Score(object): # def __init__(self, name, pattern, example=None): # self.name = name # self.pattern = pattern # self.regex = re.compile(pattern) # self.example = example # if self.example and not self.is_valid(self.example): # raise InvalidExample(self.name, self.pattern, self.example) # # def is_valid(self, score_string): # if not isinstance(score_string, str): # score_string = str(score_string) # matches = re.search(self.regex, score_string) # if not matches: # return False # return True # # def __str__(self): # return "{0},{1},{2}".format(self.name, self.pattern, self.example or '') # # def __iter__(self): # score_dict = dict() # score_dict[self.name] = dict(pattern=self.pattern, example=self.example or '') # return iter(score_dict) which might include code, classes, or functions. Output only the next line.
self.scores[name] = Score(name, pattern, example)
Here is a snippet: <|code_start|> class TestExploitSourceDir(unittest.TestCase): def setUp(self): self.test_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'test_data') self.exploit_dir = os.path.join(self.test_data_path, 'exploit-source') <|code_end|> . Write the next line using the current file imports: import unittest import os import mock from elem.exploit import ExploitSource and context from other files: # Path: elem/exploit/exploit_source.py # class ExploitSource(Resource): # """ # ExploitSource is the source of an exploit or exploits. # """ # def __init__(self, source_name, location): # super(ExploitSource, self).__init__(location) # self.token = 0 # # self.source_name = source_name # # # def exploits(self): # exploits = [] # if isinstance(self.data, list): # for location in self.data: # data = Resource(location).read() # exploit = ExploitSource.generate_exploit(data, location, self.source_name) # exploits.append(exploit) # elif isinstance(self.data, str): # exploits.append(ExploitSource.generate_exploit(self.data, self.location, self.source_name)) # return exploits # # @classmethod # def generate_exploit(cls, data, location, source_name): # matches = re.findall(CVE_STRING, data, re.MULTILINE) # if ResourceConnectorFactory.location_is_url(location): # location_path = urlparse.urlparse(location).path # elif os.path.isfile(location): # location_path = location # location_base = os.path.basename(location_path) # eid = os.path.splitext(location_base)[0] # # exploit = dict(source=source_name, # cves=list(set(matches)), # id=eid, # exploit=base64.b64encode(data)) # return exploit , which may include functions, classes, or code. Output only the next line.
self.exploit_source = ExploitSource('exploit-source', self.exploit_dir)
Based on the snippet: <|code_start|> class TestYumAssessor(unittest.TestCase): def setUp(self): test_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'test_data', 'assess', 'cve_list.txt') with open(test_data_path, 'r') as cve_file: self.test_cves = cve_file.readlines() self.test_cves = [cve.replace('\n', '') for cve in self.test_cves] yum_output_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'test_data', 'assess', 'yum_output.txt') with open(yum_output_path, 'r') as yum_file: self.yum_output = yum_file.read() yum_error_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'test_data', 'assess', 'yum_errors.txt') with open(yum_error_path, 'r') as yum_file: self.yum_error = yum_file.read() <|code_end|> , predict the immediate next line with the help of imports: import unittest import os import mock from elem.host import YumAssessor and context (classes, functions, sometimes code) from other files: # Path: elem/host/assessor.py # class YumAssessor(Assessor): # def __init__(self): # super(YumAssessor, self).__init__() # # def assess(self): # lines = [] # error_lines = [] # # command = ["yum", "updateinfo", "list", "cves"] # p = subprocess.Popen(command, # stdout=subprocess.PIPE, # stderr=subprocess.PIPE) # out, err = p.communicate() # # if p.returncode != 0: # raise OSError((p.returncode, err)) # # lines = out.split('\n') # # pattern = re.compile(r'\s(.*CVE-\d{4}-\d{4,})') # for line in lines: # result = re.findall(pattern, line) # if result and result[0] not in self.cves: # self.cves.append(result[0]) # # self.cves = list(set(self.cves)) . Output only the next line.
self.yum_assessor = YumAssessor()
Next line prediction: <|code_start|> class VulnerabilityManager(object): def __init__(self): self.readers = dict() self.data = dict() self.cves = dict() def add_api_source(self, name, location, tlsverify=True, cache_path=None): <|code_end|> . Use current file imports: (from elem.vulnerability import SecurityApiSource) and context including class names, function names, or small code snippets from other files: # Path: elem/vulnerability/security_api_source.py # class SecurityApiSource(VulnerabilitySource): # def __init__(self, name, location, tlsverify=True, cache_location=None): # super(SecurityApiSource, self).__init__(name, # location, # VulnerabilitySource.API_SOURCE, # tlsverify, # cache_location=cache_location) # # def cves(self): # cve_result = dict() # # for cve in self.data: # published_date = None # if cve['public_date']: # published_date = dateutil.parser.parse(cve['public_date']).replace(tzinfo=None).date() # cve_result[cve['CVE']] = dict(published_date=str(published_date), # source_name=self.name, # source_type=self.source_type, # affected_packages=[Rpm(package) for package in cve['affected_packages']]) # return cve_result # # # def update_cves(self): # cves = [] # # update_resoure = Resource(self.after_url()) # new_data = update_resoure.read() # # for cve in new_data: # cves.append(cve['CVE']) # return cves # # def latest_date(self): # latest = dateutil.parser.parse('01-01-1970') # for cve in self.data: # if cve['public_date']: # cve_date = dateutil.parser.parse(cve['public_date']).replace(tzinfo=None) # if cve_date > latest: # latest = cve_date # return latest.date() # # def after_date(self): # return self.latest_date() + timedelta(days=1) # # def after_url(self): # if '?' in self.location: # return self.location + '&after=' + str(self.after_date()) # return self.location + '?after=' + str(self.after_date()) . Output only the next line.
self.readers[name] = SecurityApiSource(name,
Given snippet: <|code_start|> class TestSecurityApi(unittest.TestCase): def setUp(self): self.test_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'test_data') self.url = 'https://access.redhat.com/labs/securitydataapi/cves.json' self.mock_data_file = os.path.join(self.test_data_path, 'security_api', 'redhat_security_api.json') self.mock_resource = Resource(self.mock_data_file) self.update_url = 'https://access.redhat.com/labs/securitydataapi/cves.json?after=2017-10-17' self.mock_update_file = os.path.join(self.test_data_path, 'security_api', 'red_hat_security_api_after_2017_10_17.json') self.mock_update_resource = Resource(self.mock_update_file) <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest import os import mock import dateutil.parser from redteamcore import Resource from elem.vulnerability import SecurityApiSource and context: # Path: elem/vulnerability/security_api_source.py # class SecurityApiSource(VulnerabilitySource): # def __init__(self, name, location, tlsverify=True, cache_location=None): # super(SecurityApiSource, self).__init__(name, # location, # VulnerabilitySource.API_SOURCE, # tlsverify, # cache_location=cache_location) # # def cves(self): # cve_result = dict() # # for cve in self.data: # published_date = None # if cve['public_date']: # published_date = dateutil.parser.parse(cve['public_date']).replace(tzinfo=None).date() # cve_result[cve['CVE']] = dict(published_date=str(published_date), # source_name=self.name, # source_type=self.source_type, # affected_packages=[Rpm(package) for package in cve['affected_packages']]) # return cve_result # # # def update_cves(self): # cves = [] # # update_resoure = Resource(self.after_url()) # new_data = update_resoure.read() # # for cve in new_data: # cves.append(cve['CVE']) # return cves # # def latest_date(self): # latest = dateutil.parser.parse('01-01-1970') # for cve in self.data: # if cve['public_date']: # cve_date = dateutil.parser.parse(cve['public_date']).replace(tzinfo=None) # if cve_date > latest: # latest = cve_date # return latest.date() # # def after_date(self): # return self.latest_date() + timedelta(days=1) # # def after_url(self): # if '?' in self.location: # return self.location + '&after=' + str(self.after_date()) # return self.location + '?after=' + str(self.after_date()) which might include code, classes, or functions. Output only the next line.
self.sapi = SecurityApiSource('redhat', self.url)
Given snippet: <|code_start|> class TestStrideScore(unittest.TestCase): def setUp(self): self.pattern = r'^(\d)(\d)(\d)(\d)(\d)(\d)$' <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest from elem.score import Score from elem.score import InvalidExample and context: # Path: elem/score/score.py # class Score(object): # def __init__(self, name, pattern, example=None): # self.name = name # self.pattern = pattern # self.regex = re.compile(pattern) # self.example = example # if self.example and not self.is_valid(self.example): # raise InvalidExample(self.name, self.pattern, self.example) # # def is_valid(self, score_string): # if not isinstance(score_string, str): # score_string = str(score_string) # matches = re.search(self.regex, score_string) # if not matches: # return False # return True # # def __str__(self): # return "{0},{1},{2}".format(self.name, self.pattern, self.example or '') # # def __iter__(self): # score_dict = dict() # score_dict[self.name] = dict(pattern=self.pattern, example=self.example or '') # return iter(score_dict) # # Path: elem/score/score.py # class InvalidExample(Exception): # def __init__(self, name, pattern, example): # message = "For score {0}, example {1} does not match pattern {2}.".format(name, example, pattern) # super(InvalidExample, self).__init__(message) which might include code, classes, or functions. Output only the next line.
self.stride = Score('stride', self.pattern)
Predict the next line for this snippet: <|code_start|> class TestStrideScore(unittest.TestCase): def setUp(self): self.pattern = r'^(\d)(\d)(\d)(\d)(\d)(\d)$' self.stride = Score('stride', self.pattern) def test_name(self): self.assertEqual('stride', self.stride.name) def test_valid(self): self.assertTrue(self.stride.is_valid(123456)) self.assertTrue(self.stride.is_valid("000000")) def test_invalid(self): self.assertFalse(self.stride.is_valid('1234567')) self.assertFalse(self.stride.is_valid('ABCDEF')) self.assertFalse(self.stride.is_valid('')) self.assertFalse(self.stride.is_valid('2017-10-27')) def test_example(self): <|code_end|> with the help of current file imports: import unittest from elem.score import Score from elem.score import InvalidExample and context from other files: # Path: elem/score/score.py # class Score(object): # def __init__(self, name, pattern, example=None): # self.name = name # self.pattern = pattern # self.regex = re.compile(pattern) # self.example = example # if self.example and not self.is_valid(self.example): # raise InvalidExample(self.name, self.pattern, self.example) # # def is_valid(self, score_string): # if not isinstance(score_string, str): # score_string = str(score_string) # matches = re.search(self.regex, score_string) # if not matches: # return False # return True # # def __str__(self): # return "{0},{1},{2}".format(self.name, self.pattern, self.example or '') # # def __iter__(self): # score_dict = dict() # score_dict[self.name] = dict(pattern=self.pattern, example=self.example or '') # return iter(score_dict) # # Path: elem/score/score.py # class InvalidExample(Exception): # def __init__(self, name, pattern, example): # message = "For score {0}, example {1} does not match pattern {2}.".format(name, example, pattern) # super(InvalidExample, self).__init__(message) , which may contain function names, class names, or code. Output only the next line.
with self.assertRaises(InvalidExample) as error:
Here is a snippet: <|code_start|># Authors: Serge "Sans Paille" Guelton # License: MIT # grab imports imports = 'import numpy as np' exports = '#pythran export pairwise_python_nested_for_loops(float[][])' modname = 'pairwise_pythran' # grab the source from the original function <|code_end|> . Write the next line using the current file imports: from pairwise import pairwise_python from pythran import compile_pythrancode from inspect import getsource import re import imp and context from other files: # Path: pairwise/pairwise_python.py # def pairwise_python_nested_for_loops(data): # def pairwise_python_inner_numpy(data): # def pairwise_python_broadcast_numpy(data): # def pairwise_python_numpy_dot(data): , which may include functions, classes, or code. Output only the next line.
source = getsource(pairwise_python.pairwise_python_nested_for_loops)
Based on the snippet: <|code_start|> # grab imports imports = 'import numpy as np' exports = ''' #pythran export growcut_python(float[][][], float[][][], float[][][], int) ''' modname = 'growcut_pythran' # grab the source from the original functions sources = map(getsource, <|code_end|> , predict the immediate next line with the help of imports: from growcut import growcut_python from pythran import compile_pythrancode from inspect import getsource import imp and context (classes, functions, sometimes code) from other files: # Path: growcut/growcut_python.py # def growcut_python(image, state, state_next, window_radius): # changes = 0 # sqrt_3 = np.sqrt(3.0) # # height = image.shape[0] # width = image.shape[1] # # for j in xrange(width): # for i in xrange(height): # # winning_colony = state[i, j, 0] # defense_strength = state[i, j, 1] # # for jj in xrange(window_floor(j, window_radius), # window_ceil(j + 1, width, window_radius)): # for ii in xrange(window_floor(i, window_radius), # window_ceil(i + 1, height, window_radius)): # if ii != i or jj != j: # d = image[i, j, 0] - image[ii, jj, 0] # s = d * d # for k in range(1, 3): # d = image[i, j, k] - image[ii, jj, k] # s += d * d # gval = 1.0 - np.sqrt(s) / sqrt_3 # # attack_strength = gval * state[ii, jj, 1] # # if attack_strength > defense_strength: # defense_strength = attack_strength # winning_colony = state[ii, jj, 0] # changes += 1 # # state_next[i, j, 0] = winning_colony # state_next[i, j, 1] = defense_strength # # return changes . Output only the next line.
(growcut_python.window_floor,
Given the code snippet: <|code_start|># Authors: Olivier Grisel # License: MIT def pairwise_parakeet_comprehensions(data): return np.array([[np.sqrt(np.sum((a-b)**2)) for b in data] for a in data]) benchmarks = ( ("pairwise_parakeet_nested_for_loops", <|code_end|> , generate the next line using the imports in this file: from pairwise import pairwise_python from parakeet import jit import numpy as np and context (functions, classes, or occasionally code) from other files: # Path: pairwise/pairwise_python.py # def pairwise_python_nested_for_loops(data): # def pairwise_python_inner_numpy(data): # def pairwise_python_broadcast_numpy(data): # def pairwise_python_numpy_dot(data): . Output only the next line.
jit(pairwise_python.pairwise_python_nested_for_loops)),
Given the code snippet: <|code_start|># Authors: Serge Guelton # License: MIT # grab imports imports = 'import numpy' exports = ''' #pythran export rosen_der_numpy(float []) ''' modname = 'rosen_der_pythran' # grab the source from the original functions sources = map(getsource, <|code_end|> , generate the next line using the imports in this file: from rosen_der import rosen_der_python from pythran import compile_pythrancode from inspect import getsource import imp and context (functions, classes, or occasionally code) from other files: # Path: rosen_der/rosen_der_python.py # def rosen_der_python(x): # n = x.shape[0] # der = numpy.zeros_like(x) # # for i in range(1, n - 1): # der[i] = (+ 200 * (x[i] - x[i - 1] ** 2) # - 400 * (x[i + 1] # - x[i] ** 2) * x[i] # - 2 * (1 - x[i])) # der[0] = -400 * x[0] * (x[1] - x[0] ** 2) - 2 * (1 - x[0]) # der[-1] = 200 * (x[-1] - x[-2] ** 2) # return der . Output only the next line.
(rosen_der_python.rosen_der_numpy,)
Given the code snippet: <|code_start|># Authors: Yuancheng Peng # License: MIT # grab imports imports = ''' import numpy as np from math import * ''' exports = ''' #pythran export arc_distance_python_nested_for_loops(float [][], float [][]) ''' modname = 'arc_distance_pythran' # grab the source from original functions <|code_end|> , generate the next line using the imports in this file: from arc_distance import arc_distance_python from pythran import compile_pythrancode from inspect import getsource import re import imp and context (functions, classes, or occasionally code) from other files: # Path: arc_distance/arc_distance_python.py # def arc_distance_python_nested_for_loops(a, b): # def arc_distance_numpy_tile(a, b): # def arc_distance_numpy_broadcast(a, b): . Output only the next line.
funs = (arc_distance_python.arc_distance_python_nested_for_loops,)
Next line prediction: <|code_start|> # grab imports imports = 'import numpy as np' exports = ''' #pythran export julia_python_for_loops(float, float, int, float, float, float) ''' modname = 'julia_pythran' # grab the source from the original functions sources = map(getsource, <|code_end|> . Use current file imports: (from julia import julia_python from pythran import compile_pythrancode from inspect import getsource import re, imp) and context including class names, function names, or small code snippets from other files: # Path: julia/julia_python.py # def kernel(zr, zi, cr, ci, lim, cutoff): # def julia_python_for_loops(cr, ci, N, bound=1.5, lim=1000., cutoff=1e6): # def julia_python_numpy(cr, ci, N, bound=1.5, lim=4., cutoff=1e6): # X, Y = np.ogrid[-bound:bound:N*1j, -bound:bound:N*1j] . Output only the next line.
(julia_python.julia_python_for_loops,
Given snippet: <|code_start|># Authors: Alex Rubinsteyn # License: MIT @jit def arc_distance_parakeet_comprehensions(a, b): """ Calculates the pairwise arc distance between all points in vector a and b. Uses nested list comprehensions, which are efficiently parallelized by Parakeet. """ def arc_dist(ai, bj): theta1 = ai[0] phi1 = ai[1] theta2 = bj[0] phi2 = bj[1] d_theta = theta2 - theta1 d_phi = phi2 - phi1 temp = (np.sin(d_theta / 2) ** 2) + \ (np.cos(theta1) * np.cos(theta2) * np.sin(d_phi / 2) ** 2) return 2 * np.arctan2(np.sqrt(temp), np.sqrt(1 - temp)) return np.array([[arc_dist(ai, bj) for bj in b] for ai in a]) benchmarks = (("arc_distance_parakeet_for_loops", <|code_end|> , continue by predicting the next line. Consider current file imports: from arc_distance import arc_distance_python as adp from parakeet import jit import numpy as np and context: # Path: arc_distance/arc_distance_python.py # def arc_distance_python_nested_for_loops(a, b): # def arc_distance_numpy_tile(a, b): # def arc_distance_numpy_broadcast(a, b): which might include code, classes, or functions. Output only the next line.
jit(adp.arc_distance_python_nested_for_loops)),
Using the snippet: <|code_start|># See the License for the specific language governing permissions and # limitations under the License. """Tests for fedjax.datasets.downloads. Can only be run locally because of network access. """ FLAGS = flags.FLAGS class DownloadsTest(absltest.TestCase): SOURCE = 'https://storage.googleapis.com/tff-datasets-public/shakespeare.sqlite.lzma' HEXDIGEST = 'd3d11fceb9e105439ac6f4d52af6efafed5a2a1e1eb24c5bd2dd54ced242f5c4' NUM_BYTES = 1329828 def setUp(self): super().setUp() # This will be set in actual tests. self._cache_dir = None def tearDown(self): super().tearDown() if self._cache_dir is not None: shutil.rmtree(self._cache_dir) def _with_cache_dir(self, cache_dir, expected_path): # First access, being copied. <|code_end|> , determine the next line of code. You have imports: import os import os.path import shutil import sqlite3 from absl import flags from absl.testing import absltest from fedjax.datasets import downloads and context (class names, function names, or code) available: # Path: fedjax/datasets/downloads.py # def progress(n: int) -> Iterator[int]: # def maybe_download(url: str, # cache_dir: Optional[str] = None, # progress_: Callable[[int], Iterator[int]] = progress) -> str: # def format_duration(seconds: float) -> str: # def log(*args, **kwargs): # def default_cache_dir() -> str: # def maybe_lzma_decompress(path) -> str: # def validate_file(path: str, expected_num_bytes: int, expected_hexdigest: str): . Output only the next line.
path = downloads.maybe_download(self.SOURCE, cache_dir)
Given the following code snippet before the placeholder: <|code_start|># Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """Tests for fedjax.datasets.stackoverflow. This file only tests preprocessing functions. """ class StackoverflowTest(absltest.TestCase): def test_preprocess_client(self): npt.assert_equal( <|code_end|> , predict the next line using imports from the current file: from absl.testing import absltest from fedjax.datasets import stackoverflow import numpy as np import numpy.testing as npt and context including class names, function names, and sometimes code from other files: # Path: fedjax/datasets/stackoverflow.py # SPLITS = ('train', 'held_out', 'test') # PAD = 0 # BOS = 1 # EOS = 2 # def cite(): # def load_split(split: str, # mode: str = 'sqlite', # cache_dir: Optional[str] = None) -> federated_data.FederatedData: # def load_data( # mode: str = 'sqlite', # cache_dir: Optional[str] = None # ) -> Tuple[federated_data.FederatedData, federated_data.FederatedData, # def preprocess_client( # client_id: federated_data.ClientId, # examples: client_datasets.Examples) -> client_datasets.Examples: # def default_vocab(default_vocab_size) -> List[str]: # def __init__(self, # vocab: Optional[List[str]] = None, # default_vocab_size: Optional[int] = 10000, # num_oov_buckets: int = 1): # def create_token_to_ids_fn(self, max_length: int): # def token_to_ids(tokens): # def as_preprocess_batch( # self, max_length: int # ) -> Callable[[client_datasets.Examples], client_datasets.Examples]: # def preprocess_batch( # examples: client_datasets.Examples) -> client_datasets.Examples: # class StackoverflowTokenizer: . Output only the next line.
stackoverflow.preprocess_client(
Given the code snippet: <|code_start|># Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """Tests for fedjax.core.client_datasets.""" # pylint: disable=g-long-lambda class ExamplesTest(absltest.TestCase): def test_num_examples(self): with self.subTest('consistent rows'): self.assertEqual( <|code_end|> , generate the next line using the imports in this file: import itertools import numpy as np import numpy.testing as npt from absl.testing import absltest from fedjax.core import client_datasets and context (functions, classes, or occasionally code) from other files: # Path: fedjax/core/client_datasets.py # class BatchPreprocessor: # class PaddedBatchHParams: # class ShuffleRepeatBatchHParams: # class BatchHParams: # class ClientDataset: # class PaddedBatchView: # class ShuffleRepeatBatchView: # class BatchView: # def __init__(self, fns: Iterable[Callable[[Examples], Examples]] = ()): # def __call__(self, examples: Examples) -> Examples: # def append(self, fn: Callable[[Examples], Examples]) -> 'BatchPreprocessor': # def __str__(self) -> str: # def __repr__(self) -> str: # def __init__(self, # raw_examples: Examples, # preprocessor: BatchPreprocessor = NoOpBatchPreprocessor): # def __len__(self) -> int: # def __getitem__(self, index: slice) -> 'ClientDataset': # def all_examples(self) -> Examples: # def padded_batch(self, # hparams: Optional[PaddedBatchHParams] = None, # **kwargs) -> Iterable[Examples]: # def shuffle_repeat_batch(self, # hparams: Optional[ShuffleRepeatBatchHParams] = None, # **kwargs) -> Iterable[Examples]: # def batch(self, # hparams: Optional[BatchHParams] = None, # **kwargs) -> Iterable[Examples]: # def __init__(self, client_dataset: ClientDataset, # hparams: PaddedBatchHParams): # def __iter__(self) -> Iterator[Examples]: # def _pick_final_batch_size(data_size: int, batch_size: int, # num_batch_size_buckets: int) -> int: # def __init__(self, client_dataset: ClientDataset, # hparams: ShuffleRepeatBatchHParams): # def __iter__(self) -> Iterator[Examples]: # def __init__(self, client_dataset: ClientDataset, hparams: BatchHParams): # def __iter__(self) -> Iterator[Examples]: # def padded_batch_client_datasets(datasets: Iterable[ClientDataset], # hparams: Optional[PaddedBatchHParams] = None, # **kwargs) -> Iterator[Examples]: # def buffered_shuffle(source: Iterable[Any], buffer_size: int, # rng: np.random.RandomState) -> Iterator[Any]: # def buffered_shuffle_batch_client_datasets( # datasets: Iterable[ClientDataset], batch_size: int, buffer_size: int, # rng: np.random.RandomState) -> Iterator[Examples]: # def gen_items(): # def assert_consistent_rows(examples: Examples): # def num_examples(examples: Examples, validate: bool = True) -> int: # def slice_examples(examples: Examples, index: slice) -> Examples: # def concat_examples(many_examples: Iterable[Examples]) -> Examples: # def attach_mask(examples: Examples, mask: np.ndarray) -> Examples: # def pad_examples(examples: Examples, size: int) -> Examples: # EXAMPLE_MASK_KEY = '__mask__' . Output only the next line.
client_datasets.num_examples({'pixels': np.zeros([10, 20, 30])}), 10)
Given the following code snippet before the placeholder: <|code_start|> Grads = Params @dataclasses.dataclass class Optimizer: """Wraps different optimizer libraries in a common interface. Works with `optax <https://github.com/deepmind/optax>`_. The expected usage of Optimizer is as follows:: # One step of SGD. params = {'w': jnp.array([1, 1, 1])} grads = {'w': jnp.array([2, 3, 4])} optimizer = fedjax.optimizers.sgd(learning_rate=0.1) opt_state = optimizer.init(params) opt_state, params = optimizer.apply(grads, opt_state, params) print(params) # {'w': DeviceArray([0.8, 0.7, 0.6], dtype=float32)} Attributes: init: Initializes (possibly empty) PyTree of statistics (optimizer state) given the input model parameters. apply: Transforms and applies the input gradients to update the optimizer state and model parameters. """ <|code_end|> , predict the next line using imports from the current file: from typing import Callable, List, Optional, Tuple, Union from fedjax.core import dataclasses from fedjax.core.typing import OptState from fedjax.core.typing import Params import haiku as hk import jax import optax and context including class names, function names, and sometimes code from other files: # Path: fedjax/core/dataclasses.py # def dataclass(clz: type): # def replace(self, **updates): # def iterate_clz(x): # def clz_from_iterable(meta, data): # # Path: fedjax/core/typing.py # # Path: fedjax/core/typing.py . Output only the next line.
init: Callable[[Params], OptState]
Using the snippet: <|code_start|># Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """Tests for fedjax.datasets.shakespeare. This file only tests preprocessing functions. """ class ShakespeareTest(absltest.TestCase): def test_preprocess_client(self): <|code_end|> , determine the next line of code. You have imports: from absl.testing import absltest from fedjax.datasets import shakespeare import numpy as np import numpy.testing as npt and context (class names, function names, or code) available: # Path: fedjax/datasets/shakespeare.py # SPLITS = ('train', 'test') # TABLE, VOCAB_SIZE = _build_look_up_table( # b'dhlptx@DHLPTX $(,048cgkoswCGKOSW[_#\'/37;?bfjnrvzBFJNRVZ"&*.26:\naeimquyAEIMQUY]!%)-159\r', # num_reserved=3) # OOV = VOCAB_SIZE - 1 # PAD = 0 # BOS = 1 # EOS = 2 # def cite(): # def load_split(split: str, # mode: str = 'sqlite', # cache_dir: Optional[str] = None) -> federated_data.FederatedData: # def load_data( # sequence_length: int = 80, # mode: str = 'sqlite', # cache_dir: Optional[str] = None # ) -> Tuple[federated_data.FederatedData, federated_data.FederatedData]: # def _build_look_up_table(vocab: bytes, # num_reserved: int) -> Tuple[np.ndarray, int]: # def preprocess_client(client_id: federated_data.ClientId, # examples: client_datasets.Examples, # sequence_length: int) -> client_datasets.Examples: . Output only the next line.
examples = shakespeare.preprocess_client(
Using the snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """FederatedData interface for providing access to a federated dataset.""" # A client id is simply some binary bytes. ClientId = bytes class ClientPreprocessor: """A chain of preprocessing functions on all examples of a client dataset. This is very similar to :class:`fedjax.BatchPreprocessor`, with the main difference being that ClientPreprocessor also takes ``client_id`` as input. See the discussion in :class:`fedjax.BatchPreprocessor` regarding when to use which. """ def __init__(self, <|code_end|> , determine the next line of code. You have imports: import abc import numpy as np from typing import Any, Callable, Iterable, Iterator, Optional, Tuple from fedjax.core import client_datasets and context (class names, function names, or code) available: # Path: fedjax/core/client_datasets.py # class BatchPreprocessor: # class PaddedBatchHParams: # class ShuffleRepeatBatchHParams: # class BatchHParams: # class ClientDataset: # class PaddedBatchView: # class ShuffleRepeatBatchView: # class BatchView: # def __init__(self, fns: Iterable[Callable[[Examples], Examples]] = ()): # def __call__(self, examples: Examples) -> Examples: # def append(self, fn: Callable[[Examples], Examples]) -> 'BatchPreprocessor': # def __str__(self) -> str: # def __repr__(self) -> str: # def __init__(self, # raw_examples: Examples, # preprocessor: BatchPreprocessor = NoOpBatchPreprocessor): # def __len__(self) -> int: # def __getitem__(self, index: slice) -> 'ClientDataset': # def all_examples(self) -> Examples: # def padded_batch(self, # hparams: Optional[PaddedBatchHParams] = None, # **kwargs) -> Iterable[Examples]: # def shuffle_repeat_batch(self, # hparams: Optional[ShuffleRepeatBatchHParams] = None, # **kwargs) -> Iterable[Examples]: # def batch(self, # hparams: Optional[BatchHParams] = None, # **kwargs) -> Iterable[Examples]: # def __init__(self, client_dataset: ClientDataset, # hparams: PaddedBatchHParams): # def __iter__(self) -> Iterator[Examples]: # def _pick_final_batch_size(data_size: int, batch_size: int, # num_batch_size_buckets: int) -> int: # def __init__(self, client_dataset: ClientDataset, # hparams: ShuffleRepeatBatchHParams): # def __iter__(self) -> Iterator[Examples]: # def __init__(self, client_dataset: ClientDataset, hparams: BatchHParams): # def __iter__(self) -> Iterator[Examples]: # def padded_batch_client_datasets(datasets: Iterable[ClientDataset], # hparams: Optional[PaddedBatchHParams] = None, # **kwargs) -> Iterator[Examples]: # def buffered_shuffle(source: Iterable[Any], buffer_size: int, # rng: np.random.RandomState) -> Iterator[Any]: # def buffered_shuffle_batch_client_datasets( # datasets: Iterable[ClientDataset], batch_size: int, buffer_size: int, # rng: np.random.RandomState) -> Iterator[Examples]: # def gen_items(): # def assert_consistent_rows(examples: Examples): # def num_examples(examples: Examples, validate: bool = True) -> int: # def slice_examples(examples: Examples, index: slice) -> Examples: # def concat_examples(many_examples: Iterable[Examples]) -> Examples: # def attach_mask(examples: Examples, mask: np.ndarray) -> Examples: # def pad_examples(examples: Examples, size: int) -> Examples: # EXAMPLE_MASK_KEY = '__mask__' . Output only the next line.
fns: Iterable[Callable[[ClientId, client_datasets.Examples],
Based on the snippet: <|code_start|> # pylint: disable=cell-var-from-loop def main(_): for mode in ['train', 'eval']: for preprocess in [False, True]: assert (bench_client_dataset(preprocess, mode) == bench_tf_dataset(preprocess, mode)) print( f'ClientDataset\tmode={mode}\tpreprocess={preprocess}\t', timeit.timeit( lambda: bench_client_dataset(preprocess, mode), number=100)) print( f'TF Dataset\tmode={mode}\tpreprocess={preprocess}\t', timeit.timeit(lambda: bench_tf_dataset(preprocess, mode), number=100)) FAKE_MNIST = { 'pixels': np.random.uniform(size=(1000, 28, 28)), 'label': np.random.randint(10, size=(1000,)) } def f(x): return {**x, 'binary_label': x['label'] % 2} def bench_client_dataset(preprocess, mode, batch_size=128, num_steps=100): """Benchmarks ClientDataset.""" <|code_end|> , predict the immediate next line with the help of imports: import timeit import numpy as np from absl import app from fedjax.core import client_datasets from fedjax.core import util and context (classes, functions, sometimes code) from other files: # Path: fedjax/core/client_datasets.py # class BatchPreprocessor: # class PaddedBatchHParams: # class ShuffleRepeatBatchHParams: # class BatchHParams: # class ClientDataset: # class PaddedBatchView: # class ShuffleRepeatBatchView: # class BatchView: # def __init__(self, fns: Iterable[Callable[[Examples], Examples]] = ()): # def __call__(self, examples: Examples) -> Examples: # def append(self, fn: Callable[[Examples], Examples]) -> 'BatchPreprocessor': # def __str__(self) -> str: # def __repr__(self) -> str: # def __init__(self, # raw_examples: Examples, # preprocessor: BatchPreprocessor = NoOpBatchPreprocessor): # def __len__(self) -> int: # def __getitem__(self, index: slice) -> 'ClientDataset': # def all_examples(self) -> Examples: # def padded_batch(self, # hparams: Optional[PaddedBatchHParams] = None, # **kwargs) -> Iterable[Examples]: # def shuffle_repeat_batch(self, # hparams: Optional[ShuffleRepeatBatchHParams] = None, # **kwargs) -> Iterable[Examples]: # def batch(self, # hparams: Optional[BatchHParams] = None, # **kwargs) -> Iterable[Examples]: # def __init__(self, client_dataset: ClientDataset, # hparams: PaddedBatchHParams): # def __iter__(self) -> Iterator[Examples]: # def _pick_final_batch_size(data_size: int, batch_size: int, # num_batch_size_buckets: int) -> int: # def __init__(self, client_dataset: ClientDataset, # hparams: ShuffleRepeatBatchHParams): # def __iter__(self) -> Iterator[Examples]: # def __init__(self, client_dataset: ClientDataset, hparams: BatchHParams): # def __iter__(self) -> Iterator[Examples]: # def padded_batch_client_datasets(datasets: Iterable[ClientDataset], # hparams: Optional[PaddedBatchHParams] = None, # **kwargs) -> Iterator[Examples]: # def buffered_shuffle(source: Iterable[Any], buffer_size: int, # rng: np.random.RandomState) -> Iterator[Any]: # def buffered_shuffle_batch_client_datasets( # datasets: Iterable[ClientDataset], batch_size: int, buffer_size: int, # rng: np.random.RandomState) -> Iterator[Examples]: # def gen_items(): # def assert_consistent_rows(examples: Examples): # def num_examples(examples: Examples, validate: bool = True) -> int: # def slice_examples(examples: Examples, index: slice) -> Examples: # def concat_examples(many_examples: Iterable[Examples]) -> Examples: # def attach_mask(examples: Examples, mask: np.ndarray) -> Examples: # def pad_examples(examples: Examples, size: int) -> Examples: # EXAMPLE_MASK_KEY = '__mask__' # # Path: fedjax/core/util.py # def safe_div(a, b): # def __getattr__(self, _): # def import_tf(): # class FakeTensorFlowModule: . Output only the next line.
preprocessor = client_datasets.NoOpBatchPreprocessor
Given the following code snippet before the placeholder: <|code_start|># Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """Microbenchmarks for batch iteration speed of ClientDataset. Benchmark results on a Xeon E5-1650 v3 on 2021/04/27: ClientDataset mode=train preprocess=False 0.8456923319026828 TF Dataset mode=train preprocess=False 5.315499668009579 ClientDataset mode=train preprocess=True 0.9447170910425484 TF Dataset mode=train preprocess=True 5.322665546089411 ClientDataset mode=eval preprocess=False 0.015498528024181724 TF Dataset mode=eval preprocess=False 0.8721390531864017 ClientDataset mode=eval preprocess=True 0.021079374011605978 TF Dataset mode=eval preprocess=True 1.9080286680255085 """ <|code_end|> , predict the next line using imports from the current file: import timeit import numpy as np from absl import app from fedjax.core import client_datasets from fedjax.core import util and context including class names, function names, and sometimes code from other files: # Path: fedjax/core/client_datasets.py # class BatchPreprocessor: # class PaddedBatchHParams: # class ShuffleRepeatBatchHParams: # class BatchHParams: # class ClientDataset: # class PaddedBatchView: # class ShuffleRepeatBatchView: # class BatchView: # def __init__(self, fns: Iterable[Callable[[Examples], Examples]] = ()): # def __call__(self, examples: Examples) -> Examples: # def append(self, fn: Callable[[Examples], Examples]) -> 'BatchPreprocessor': # def __str__(self) -> str: # def __repr__(self) -> str: # def __init__(self, # raw_examples: Examples, # preprocessor: BatchPreprocessor = NoOpBatchPreprocessor): # def __len__(self) -> int: # def __getitem__(self, index: slice) -> 'ClientDataset': # def all_examples(self) -> Examples: # def padded_batch(self, # hparams: Optional[PaddedBatchHParams] = None, # **kwargs) -> Iterable[Examples]: # def shuffle_repeat_batch(self, # hparams: Optional[ShuffleRepeatBatchHParams] = None, # **kwargs) -> Iterable[Examples]: # def batch(self, # hparams: Optional[BatchHParams] = None, # **kwargs) -> Iterable[Examples]: # def __init__(self, client_dataset: ClientDataset, # hparams: PaddedBatchHParams): # def __iter__(self) -> Iterator[Examples]: # def _pick_final_batch_size(data_size: int, batch_size: int, # num_batch_size_buckets: int) -> int: # def __init__(self, client_dataset: ClientDataset, # hparams: ShuffleRepeatBatchHParams): # def __iter__(self) -> Iterator[Examples]: # def __init__(self, client_dataset: ClientDataset, hparams: BatchHParams): # def __iter__(self) -> Iterator[Examples]: # def padded_batch_client_datasets(datasets: Iterable[ClientDataset], # hparams: Optional[PaddedBatchHParams] = None, # **kwargs) -> Iterator[Examples]: # def buffered_shuffle(source: Iterable[Any], buffer_size: int, # rng: np.random.RandomState) -> Iterator[Any]: # def buffered_shuffle_batch_client_datasets( # datasets: Iterable[ClientDataset], batch_size: int, buffer_size: int, # rng: np.random.RandomState) -> Iterator[Examples]: # def gen_items(): # def assert_consistent_rows(examples: Examples): # def num_examples(examples: Examples, validate: bool = True) -> int: # def slice_examples(examples: Examples, index: slice) -> Examples: # def concat_examples(many_examples: Iterable[Examples]) -> Examples: # def attach_mask(examples: Examples, mask: np.ndarray) -> Examples: # def pad_examples(examples: Examples, size: int) -> Examples: # EXAMPLE_MASK_KEY = '__mask__' # # Path: fedjax/core/util.py # def safe_div(a, b): # def __getattr__(self, _): # def import_tf(): # class FakeTensorFlowModule: . Output only the next line.
tf = util.import_tf()
Here is a snippet: <|code_start|># you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """Tests for fedjax.core.regularizers.""" class RegularizersTest(absltest.TestCase): def test_l2_regularizer(self): params = { 'linear0': { 'w': jnp.array([1., 2., 3.]) }, 'linear1': { 'w': jnp.array([4., 5., 6.]), 'b': jnp.array([1., 1., 1.]) } } with self.subTest('weight'): <|code_end|> . Write the next line using the current file imports: from absl.testing import absltest from fedjax.core import regularizers import jax import jax.numpy as jnp and context from other files: # Path: fedjax/core/regularizers.py # def _l2_regularize(params: Params, weight: float, # center_params: Optional[Params], # params_weights: Optional[Params]) -> float: # def l2_regularizer( # weight: float, # center_params: Optional[Params] = None, # params_weights: Optional[Params] = None) -> Callable[[Params], float]: # def func(params): , which may include functions, classes, or code. Output only the next line.
regularizer = regularizers.l2_regularizer(weight=0.2)
Based on the snippet: <|code_start|> hadamards = dict((d, hadamard_matrix(d, x.dtype)) for d in set(shape)) # einsum on each dimension. for i, d in enumerate(shape): y_dims = ''.join(str(j) for j in range(num_dims)) h_dims = f'{i}{num_dims + 1}' out_dims = y_dims.replace(str(i), str(num_dims + 1), 1) operands = f'{y_dims},{h_dims}->{out_dims}' y = jnp.einsum(operands, y, hadamards[d], precision=precision) return y.flatten() def hadamard_matrix(n: int, dtype: jnp.dtype) -> jnp.ndarray: """Generates the Hadamard matrix. Because there are JAX dtypes not supported in numpy, the equivalent function in scipy can't be used directly. Args: n: Number of rows/columns of the Hadamard matrix. Must be a power of 2. dtype: Output dtype. Returns: The Hadamard matrix of the given size and type. """ return jnp.array(scipy.linalg.hadamard(n), dtype) @jax.jit def structured_rotation(x: jnp.ndarray, <|code_end|> , predict the immediate next line with the help of imports: import math import jax import jax.numpy as jnp import scipy from typing import Tuple, Union from fedjax.core.typing import PRNGKey, Params and context (classes, functions, sometimes code) from other files: # Path: fedjax/core/typing.py . Output only the next line.
rng: PRNGKey) -> Tuple[jnp.ndarray, jnp.ndarray]:
Given the code snippet: <|code_start|> x_flat = jnp.reshape(x, [-1]) d = 2**math.ceil(math.log2(x_flat.size)) w = jnp.pad(x_flat, (0, d - x.size)) rademacher = jax.random.rademacher(rng, w.shape) return walsh_hadamard_transform(w * rademacher) / jnp.sqrt(d), jnp.array( x.shape) def inverse_structured_rotation(x: jnp.ndarray, rng: PRNGKey, original_shape: jnp.ndarray) -> jnp.ndarray: """Computes (HD)^(-1)(x)/sqrt(d). Here where H is the walsh Hadamard matrix, d is the dimensionlity of x, and D is a random Rademacher matrix. Args: x: rotated array, which needs to be unrotated. rng: PRNGKey used for rotation. original_shape: desired shape of the output. Returns: Output of (HD)^(-1)(x)/sqrt(d) with appropriate shape. """ rademacher = jax.random.rademacher(rng, x.shape) w = walsh_hadamard_transform(x) * rademacher / jnp.sqrt(x.size) original_size = jnp.prod(original_shape) y_flat = w.take(jnp.arange(original_size)) return jnp.reshape(y_flat, original_shape) <|code_end|> , generate the next line using the imports in this file: import math import jax import jax.numpy as jnp import scipy from typing import Tuple, Union from fedjax.core.typing import PRNGKey, Params and context (functions, classes, or occasionally code) from other files: # Path: fedjax/core/typing.py . Output only the next line.
def structured_rotation_pytree(params: Params,
Using the snippet: <|code_start|># Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """Tests for util.""" jax.config.update('jax_debug_nans', True) class UtilsTest(absltest.TestCase): def test_safe_div(self): # Safe division by zero. npt.assert_array_equal( <|code_end|> , determine the next line of code. You have imports: from absl.testing import absltest from fedjax.core import util import jax import jax.numpy as jnp import numpy.testing as npt and context (class names, function names, or code) available: # Path: fedjax/core/util.py # def safe_div(a, b): # def __getattr__(self, _): # def import_tf(): # class FakeTensorFlowModule: . Output only the next line.
util.safe_div(jnp.array([1, 2, 3]), jnp.array([0, 1, 2])), [0, 2, 1.5])
Given snippet: <|code_start|># Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """Tests for fedjax.core.serialization.""" class SerializationTest(absltest.TestCase): def test_dict(self): original = { 'int32': np.arange(4, dtype=np.int32).reshape([2, 2]), 'float64': -np.arange(4, dtype=np.float64).reshape([1, 4]), 'bytes': np.array([b'a', b'bc', b'def'], dtype=np.object).reshape([3, 1]), } <|code_end|> , continue by predicting the next line. Consider current file imports: from absl.testing import absltest from fedjax.core import serialization import numpy as np import numpy.testing as npt and context: # Path: fedjax/core/serialization.py # def save_state(state, path): # def load_state(path): # def _ndarray_to_bytes(arr): # def _dtype_from_name(name): # def _ndarray_from_bytes(data): # def _bytes_ndarray_to_bytes(x): # def _object_ndarray_from_bytes(data): # def _msgpack_ext_pack(x): # def _msgpack_ext_unpack(code, data): # def msgpack_serialize(pytree): # def msgpack_deserialize(encoded_pytree): # class _MsgpackExtType(enum.IntEnum): which might include code, classes, or functions. Output only the next line.
output = serialization.msgpack_deserialize(
Based on the snippet: <|code_start|> """ @abc.abstractmethod def merge(self, other: 'Stat') -> 'Stat': """Merges two Stat objects into a new Stat with merged statistics. Args: other: Another Stat object of the same type. Returns: A new Stat object of the same type with merged statistics. """ @abc.abstractmethod def reduce(self, axis: Optional[int] = 0) -> 'Stat': """Reduces a higher rank statistic along a given ``axis``. See the class docstring for details. Args: axis: An integer axis index, or ``None``. Returns: A new Stat object of the same type. """ def __str__(self) -> str: return f'{repr(self)} => {self.result()}' <|code_end|> , predict the immediate next line with the help of imports: import abc import functools import jax import jax.numpy as jnp from typing import Optional, Tuple from fedjax.core import dataclasses from fedjax.core import util from fedjax.core.typing import BatchExample from fedjax.core.typing import BatchPrediction from fedjax.core.typing import SingleExample from fedjax.core.typing import SinglePrediction and context (classes, functions, sometimes code) from other files: # Path: fedjax/core/dataclasses.py # def dataclass(clz: type): # def replace(self, **updates): # def iterate_clz(x): # def clz_from_iterable(meta, data): # # Path: fedjax/core/util.py # def safe_div(a, b): # def __getattr__(self, _): # def import_tf(): # class FakeTensorFlowModule: # # Path: fedjax/core/typing.py # # Path: fedjax/core/typing.py # # Path: fedjax/core/typing.py # # Path: fedjax/core/typing.py . Output only the next line.
@dataclasses.dataclass
Here is a snippet: <|code_start|> weight: The sum of weights. """ accum: jnp.ndarray weight: jnp.ndarray @classmethod def new(cls, accum, weight) -> 'MeanStat': """Creates a sanitized MeanStat. The domain of a weighted mean statistic is: .. math:: \{(0, 0)\} ∪ \{(a, b) | a >= 0, b > 0\} new() sanitizes values outside the domain into the identity (zeros). Args: accum: A value convertible to ``jnp.ndarray``. weight: A value convertible to ``jnp.ndarray``. Returns: The sanitized MeanStat. """ weight = jnp.maximum(0, jnp.array(weight, copy=False)) accum = jnp.where(weight == 0, 0, jnp.array(accum, copy=False)) return cls(accum, weight) def result(self) -> jnp.ndarray: <|code_end|> . Write the next line using the current file imports: import abc import functools import jax import jax.numpy as jnp from typing import Optional, Tuple from fedjax.core import dataclasses from fedjax.core import util from fedjax.core.typing import BatchExample from fedjax.core.typing import BatchPrediction from fedjax.core.typing import SingleExample from fedjax.core.typing import SinglePrediction and context from other files: # Path: fedjax/core/dataclasses.py # def dataclass(clz: type): # def replace(self, **updates): # def iterate_clz(x): # def clz_from_iterable(meta, data): # # Path: fedjax/core/util.py # def safe_div(a, b): # def __getattr__(self, _): # def import_tf(): # class FakeTensorFlowModule: # # Path: fedjax/core/typing.py # # Path: fedjax/core/typing.py # # Path: fedjax/core/typing.py # # Path: fedjax/core/typing.py , which may include functions, classes, or code. Output only the next line.
return util.safe_div(self.accum, self.weight)
Next line prediction: <|code_start|> Returns: Stat identity value. """ @abc.abstractmethod def evaluate_example(self, example: SingleExample, prediction: SinglePrediction) -> Stat: """Evaluates a single example. e.g. for accuracy: ``MeanStat.new(num_correct, num_total)`` Args: example: A single input example (e.g. one sentence for language). prediction: Output for ``example`` from :meth:`fedjax.core.models.Model.apply_for_eval`. Returns: Stat value. """ def apply_mask(mask: jnp.ndarray, a: jnp.ndarray, b: jnp.ndarray) -> jnp.ndarray: """Applies mask on the leading dimension.""" rank = max(len(a.shape), len(b.shape)) return jnp.where(jnp.expand_dims(mask, tuple(range(1, rank))), a, b) @functools.partial(jax.jit, static_argnums=0) def evaluate_batch(metric: Metric, <|code_end|> . Use current file imports: (import abc import functools import jax import jax.numpy as jnp from typing import Optional, Tuple from fedjax.core import dataclasses from fedjax.core import util from fedjax.core.typing import BatchExample from fedjax.core.typing import BatchPrediction from fedjax.core.typing import SingleExample from fedjax.core.typing import SinglePrediction) and context including class names, function names, or small code snippets from other files: # Path: fedjax/core/dataclasses.py # def dataclass(clz: type): # def replace(self, **updates): # def iterate_clz(x): # def clz_from_iterable(meta, data): # # Path: fedjax/core/util.py # def safe_div(a, b): # def __getattr__(self, _): # def import_tf(): # class FakeTensorFlowModule: # # Path: fedjax/core/typing.py # # Path: fedjax/core/typing.py # # Path: fedjax/core/typing.py # # Path: fedjax/core/typing.py . Output only the next line.
batch_example: BatchExample,
Here is a snippet: <|code_start|> Stat identity value. """ @abc.abstractmethod def evaluate_example(self, example: SingleExample, prediction: SinglePrediction) -> Stat: """Evaluates a single example. e.g. for accuracy: ``MeanStat.new(num_correct, num_total)`` Args: example: A single input example (e.g. one sentence for language). prediction: Output for ``example`` from :meth:`fedjax.core.models.Model.apply_for_eval`. Returns: Stat value. """ def apply_mask(mask: jnp.ndarray, a: jnp.ndarray, b: jnp.ndarray) -> jnp.ndarray: """Applies mask on the leading dimension.""" rank = max(len(a.shape), len(b.shape)) return jnp.where(jnp.expand_dims(mask, tuple(range(1, rank))), a, b) @functools.partial(jax.jit, static_argnums=0) def evaluate_batch(metric: Metric, batch_example: BatchExample, <|code_end|> . Write the next line using the current file imports: import abc import functools import jax import jax.numpy as jnp from typing import Optional, Tuple from fedjax.core import dataclasses from fedjax.core import util from fedjax.core.typing import BatchExample from fedjax.core.typing import BatchPrediction from fedjax.core.typing import SingleExample from fedjax.core.typing import SinglePrediction and context from other files: # Path: fedjax/core/dataclasses.py # def dataclass(clz: type): # def replace(self, **updates): # def iterate_clz(x): # def clz_from_iterable(meta, data): # # Path: fedjax/core/util.py # def safe_div(a, b): # def __getattr__(self, _): # def import_tf(): # class FakeTensorFlowModule: # # Path: fedjax/core/typing.py # # Path: fedjax/core/typing.py # # Path: fedjax/core/typing.py # # Path: fedjax/core/typing.py , which may include functions, classes, or code. Output only the next line.
batch_prediction: BatchPrediction,
Predict the next line after this snippet: <|code_start|> It defines two methods: - :meth:`~Metric.evaluate_example` evaluates a single example, and returns a :class:`Stat` object. - :meth:`~Metric.zero` returns the identity value for what :meth:`~Metric.evaluate_example` returns. Given a :class:`Metric` object ``m``, let - ``u = m.zero()`` - ``v = m.evaluate_example(...)`` We require that - ``type(u) == type(v)``. - ``u.merge(v) == v.merge(u) == v``. - Components of ``u`` has the same shape as the counter parts in ``v``. """ @abc.abstractmethod def zero(self) -> Stat: """Returns a Stat such that merging with it is an identity operation. e.g. for accuracy: ``MeanStat.new(0., 0.)`` Returns: Stat identity value. """ @abc.abstractmethod <|code_end|> using the current file's imports: import abc import functools import jax import jax.numpy as jnp from typing import Optional, Tuple from fedjax.core import dataclasses from fedjax.core import util from fedjax.core.typing import BatchExample from fedjax.core.typing import BatchPrediction from fedjax.core.typing import SingleExample from fedjax.core.typing import SinglePrediction and any relevant context from other files: # Path: fedjax/core/dataclasses.py # def dataclass(clz: type): # def replace(self, **updates): # def iterate_clz(x): # def clz_from_iterable(meta, data): # # Path: fedjax/core/util.py # def safe_div(a, b): # def __getattr__(self, _): # def import_tf(): # class FakeTensorFlowModule: # # Path: fedjax/core/typing.py # # Path: fedjax/core/typing.py # # Path: fedjax/core/typing.py # # Path: fedjax/core/typing.py . Output only the next line.
def evaluate_example(self, example: SingleExample,
Given the following code snippet before the placeholder: <|code_start|> - :meth:`~Metric.evaluate_example` evaluates a single example, and returns a :class:`Stat` object. - :meth:`~Metric.zero` returns the identity value for what :meth:`~Metric.evaluate_example` returns. Given a :class:`Metric` object ``m``, let - ``u = m.zero()`` - ``v = m.evaluate_example(...)`` We require that - ``type(u) == type(v)``. - ``u.merge(v) == v.merge(u) == v``. - Components of ``u`` has the same shape as the counter parts in ``v``. """ @abc.abstractmethod def zero(self) -> Stat: """Returns a Stat such that merging with it is an identity operation. e.g. for accuracy: ``MeanStat.new(0., 0.)`` Returns: Stat identity value. """ @abc.abstractmethod def evaluate_example(self, example: SingleExample, <|code_end|> , predict the next line using imports from the current file: import abc import functools import jax import jax.numpy as jnp from typing import Optional, Tuple from fedjax.core import dataclasses from fedjax.core import util from fedjax.core.typing import BatchExample from fedjax.core.typing import BatchPrediction from fedjax.core.typing import SingleExample from fedjax.core.typing import SinglePrediction and context including class names, function names, and sometimes code from other files: # Path: fedjax/core/dataclasses.py # def dataclass(clz: type): # def replace(self, **updates): # def iterate_clz(x): # def clz_from_iterable(meta, data): # # Path: fedjax/core/util.py # def safe_div(a, b): # def __getattr__(self, _): # def import_tf(): # class FakeTensorFlowModule: # # Path: fedjax/core/typing.py # # Path: fedjax/core/typing.py # # Path: fedjax/core/typing.py # # Path: fedjax/core/typing.py . Output only the next line.
prediction: SinglePrediction) -> Stat:
Predict the next line for this snippet: <|code_start|># Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """Tests for fedjax.models.shakespeare.""" class ShakespeareModelTest(absltest.TestCase): def test_create_lstm_model(self): model = shakespeare.create_lstm_model() params = model.init(jax.random.PRNGKey(0)) batch = { 'x': jnp.ones((5, 3), dtype=jnp.int32), 'y': jnp.ones((5, 3), dtype=jnp.int32) } <|code_end|> with the help of current file imports: from typing import Hashable from absl.testing import absltest from fedjax.core import tree_util from fedjax.models import shakespeare import jax import jax.numpy as jnp and context from other files: # Path: fedjax/core/tree_util.py # def tree_weight(pytree: PyTree, weight: float) -> PyTree: # def tree_inverse_weight(pytree: PyTree, weight: float) -> PyTree: # def tree_zeros_like(pytree: PyTree) -> PyTree: # def tree_add(left: PyTree, right: PyTree) -> PyTree: # def tree_sum(pytrees: Iterable[PyTree]) -> PyTree: # def tree_mean(pytrees_and_weights: Iterable[Tuple[PyTree, float]]) -> PyTree: # def tree_size(pytree: PyTree) -> int: # def tree_l2_squared(pytree: PyTree) -> float: # def tree_l2_norm(pytree: PyTree) -> float: # def tree_clip_by_global_norm(pytree: PyTree, max_norm: float) -> PyTree: # # Path: fedjax/models/shakespeare.py # def create_lstm_model(vocab_size: int = 86, # embed_size: int = 8, # lstm_hidden_size: int = 256, # lstm_num_layers: int = 2) -> models.Model: # def forward_pass(batch): # def train_loss(batch, preds): , which may contain function names, class names, or code. Output only the next line.
self.assertEqual(tree_util.tree_size(params), 820522)
Given the following code snippet before the placeholder: <|code_start|> 'input_string': 'Thank God! If I had to hear one more story...\n', 'desired': 'thank god if i had to hear one more story', }, { 'testcase_name': 'test decimal', 'input_string': 'Pi is 3.14 and pi day is in 10 months.', 'desired': 'pi is <NUMERIC> and pi day is in <NUMERIC> months', }, { 'testcase_name': 'test dollar', 'input_string': 'I have 50,000.00 dollars in my account right now.\n', 'desired': 'i have <NUMERIC> dollars in my account right now', }, { 'testcase_name': 'test hyphen', 'input_string': 'This is a double--hyphen! And this is a single-one.', 'desired': 'this is a double hyphen and this is a single-one', }, { 'testcase_name': 'test ellipses', 'input_string': 'I..do...not......know.....\n', 'desired': 'i do not know', }, { 'testcase_name': 'test html tags', 'input_string': '<u>These are</u> underlining HTML and <b>bold</b> HTML tags.', 'desired': 'these are underlining html and bold html tags', }) def test_normalize_dialogue_string(self, input_string, desired): self.assertEqual( desired, <|code_end|> , predict the next line using imports from the current file: from absl.testing import absltest from absl.testing import parameterized from fedjax.datasets.scripts.cornell_movie_dialogs import data_to_sqlite and context including class names, function names, and sometimes code from other files: # Path: fedjax/datasets/scripts/cornell_movie_dialogs/data_to_sqlite.py # FLAGS = flags.FLAGS # def main(argv) -> None: # def normalize_dialogue_string(dialogue: str) -> str: . Output only the next line.
data_to_sqlite.normalize_dialogue_string(input_string))
Based on the snippet: <|code_start|> client_init=client_init, shared_input=shared_input, client_input=client_input) from e for batch in client_batches: try: state, step_result = client_step(state, batch) except Exception as e: raise ForEachClientError( e, stage='client_step', client_id=client_id, client_step=client_step, state=state, batch=batch) from e step_results.append(step_result) try: output = client_final(shared_input, state) except Exception as e: raise ForEachClientError( e, stage='client_final', client_id=client_id, client_final=client_final, shared_input=shared_input, state=state) from e yield client_id, output, step_results return run <|code_end|> , predict the immediate next line with the help of imports: import abc import contextlib import functools import threading import jax import jax.numpy as jnp from typing import Any, Callable, Iterable, Iterator, List, Optional, Sequence, Tuple, Union from fedjax.core import dataclasses from fedjax.core.typing import BatchExample from fedjax.core.typing import PyTree and context (classes, functions, sometimes code) from other files: # Path: fedjax/core/dataclasses.py # def dataclass(clz: type): # def replace(self, **updates): # def iterate_clz(x): # def clz_from_iterable(meta, data): # # Path: fedjax/core/typing.py # # Path: fedjax/core/typing.py . Output only the next line.
@dataclasses.dataclass
Continue the code snippet: <|code_start|>""" # Shared input that is passed to the client init that is shared across all # clients. For example, this could be the shared global model parameters that # are then used as the starting point for per client training. SharedInput = PyTree # Client specific input passed into client init that is different for each # client. For example, this could be the starting PRNG seed for training a given # client. Additionally, for stateful client federated algorithms (usually in the # cross-silo setting), this is how per client information will be passed along. ClientInput = PyTree # Intermittent client state passed as input and output for each client step. # This will typically contain model parameters and optimizer state that are # updated at each client step. ClientStepState = PyTree # Step results can be used to record any metrics over the course of running the # for_each_client loop. For example, it can be used to record train metrics for # each client like gradient norm. ClientStepResult = PyTree # Final output from the for_each_client loop. This is usually a subset of the # client step state. However, more meaningful transformations can be done like # model update clipping. ClientOutput = PyTree ClientInit = Callable[[SharedInput, ClientInput], ClientStepState] <|code_end|> . Use current file imports: import abc import contextlib import functools import threading import jax import jax.numpy as jnp from typing import Any, Callable, Iterable, Iterator, List, Optional, Sequence, Tuple, Union from fedjax.core import dataclasses from fedjax.core.typing import BatchExample from fedjax.core.typing import PyTree and context (classes, functions, or code) from other files: # Path: fedjax/core/dataclasses.py # def dataclass(clz: type): # def replace(self, **updates): # def iterate_clz(x): # def clz_from_iterable(meta, data): # # Path: fedjax/core/typing.py # # Path: fedjax/core/typing.py . Output only the next line.
ClientStep = Callable[[ClientStepState, BatchExample], Tuple[ClientStepState,
Predict the next line for this snippet: <|code_start|># Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """Transformations and utilities for specifying work for each client. Many of these utilities work with and require PyTrees as input and output. This is required when working with the underlying JAX transformations like `jax.pmap` and `jax.jit`. For more information on what PyTrees are, refer to https://jax.readthedocs.io/en/latest/pytrees.html. """ # Shared input that is passed to the client init that is shared across all # clients. For example, this could be the shared global model parameters that # are then used as the starting point for per client training. <|code_end|> with the help of current file imports: import abc import contextlib import functools import threading import jax import jax.numpy as jnp from typing import Any, Callable, Iterable, Iterator, List, Optional, Sequence, Tuple, Union from fedjax.core import dataclasses from fedjax.core.typing import BatchExample from fedjax.core.typing import PyTree and context from other files: # Path: fedjax/core/dataclasses.py # def dataclass(clz: type): # def replace(self, **updates): # def iterate_clz(x): # def clz_from_iterable(meta, data): # # Path: fedjax/core/typing.py # # Path: fedjax/core/typing.py , which may contain function names, class names, or code. Output only the next line.
SharedInput = PyTree
Using the snippet: <|code_start|> class StackOverflowModelTest(absltest.TestCase): def check_model(self, model): params = model.init(jax.random.PRNGKey(0)) batch = { 'x': jnp.ones((5, 3), dtype=jnp.int32), 'y': jnp.ones((5, 3), dtype=jnp.int32) } with self.subTest('apply_for_train'): preds = model.apply_for_train(params, batch) self.assertTupleEqual(preds.shape, (5, 3, 10000 + 4)) with self.subTest('apply_for_eval'): preds = model.apply_for_eval(params, batch) self.assertTupleEqual(preds.shape, (5, 3, 10000 + 4)) with self.subTest('train_loss'): preds = model.apply_for_train(params, batch) train_loss = model.train_loss(batch, preds) self.assertTupleEqual(train_loss.shape, (5,)) with self.subTest('hashable'): self.assertIsInstance(model, Hashable) def test_create_lstm_model(self): model = stackoverflow.create_lstm_model() params = model.init(jax.random.PRNGKey(0)) <|code_end|> , determine the next line of code. You have imports: from typing import Hashable from absl.testing import absltest from fedjax.core import tree_util from fedjax.models import stackoverflow import jax import jax.numpy as jnp import numpy.testing as npt and context (class names, function names, or code) available: # Path: fedjax/core/tree_util.py # def tree_weight(pytree: PyTree, weight: float) -> PyTree: # def tree_inverse_weight(pytree: PyTree, weight: float) -> PyTree: # def tree_zeros_like(pytree: PyTree) -> PyTree: # def tree_add(left: PyTree, right: PyTree) -> PyTree: # def tree_sum(pytrees: Iterable[PyTree]) -> PyTree: # def tree_mean(pytrees_and_weights: Iterable[Tuple[PyTree, float]]) -> PyTree: # def tree_size(pytree: PyTree) -> int: # def tree_l2_squared(pytree: PyTree) -> float: # def tree_l2_norm(pytree: PyTree) -> float: # def tree_clip_by_global_norm(pytree: PyTree, max_norm: float) -> PyTree: # # Path: fedjax/models/stackoverflow.py # def create_lstm_model(vocab_size: int = 10000, # embed_size: int = 96, # lstm_hidden_size: int = 670, # lstm_num_layers: int = 1, # share_input_output_embeddings: bool = False, # expected_length: Optional[float] = None) -> models.Model: # def forward_pass(batch): # def train_loss(batch, preds): . Output only the next line.
self.assertEqual(tree_util.tree_size(params), 4050748)
Continue the code snippet: <|code_start|># limitations under the License. """Tests for fedjax.models.stackoverflow.""" class StackOverflowModelTest(absltest.TestCase): def check_model(self, model): params = model.init(jax.random.PRNGKey(0)) batch = { 'x': jnp.ones((5, 3), dtype=jnp.int32), 'y': jnp.ones((5, 3), dtype=jnp.int32) } with self.subTest('apply_for_train'): preds = model.apply_for_train(params, batch) self.assertTupleEqual(preds.shape, (5, 3, 10000 + 4)) with self.subTest('apply_for_eval'): preds = model.apply_for_eval(params, batch) self.assertTupleEqual(preds.shape, (5, 3, 10000 + 4)) with self.subTest('train_loss'): preds = model.apply_for_train(params, batch) train_loss = model.train_loss(batch, preds) self.assertTupleEqual(train_loss.shape, (5,)) with self.subTest('hashable'): self.assertIsInstance(model, Hashable) def test_create_lstm_model(self): <|code_end|> . Use current file imports: from typing import Hashable from absl.testing import absltest from fedjax.core import tree_util from fedjax.models import stackoverflow import jax import jax.numpy as jnp import numpy.testing as npt and context (classes, functions, or code) from other files: # Path: fedjax/core/tree_util.py # def tree_weight(pytree: PyTree, weight: float) -> PyTree: # def tree_inverse_weight(pytree: PyTree, weight: float) -> PyTree: # def tree_zeros_like(pytree: PyTree) -> PyTree: # def tree_add(left: PyTree, right: PyTree) -> PyTree: # def tree_sum(pytrees: Iterable[PyTree]) -> PyTree: # def tree_mean(pytrees_and_weights: Iterable[Tuple[PyTree, float]]) -> PyTree: # def tree_size(pytree: PyTree) -> int: # def tree_l2_squared(pytree: PyTree) -> float: # def tree_l2_norm(pytree: PyTree) -> float: # def tree_clip_by_global_norm(pytree: PyTree, max_norm: float) -> PyTree: # # Path: fedjax/models/stackoverflow.py # def create_lstm_model(vocab_size: int = 10000, # embed_size: int = 96, # lstm_hidden_size: int = 670, # lstm_num_layers: int = 1, # share_input_output_embeddings: bool = False, # expected_length: Optional[float] = None) -> models.Model: # def forward_pass(batch): # def train_loss(batch, preds): . Output only the next line.
model = stackoverflow.create_lstm_model()
Here is a snippet: <|code_start|># Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """Tests for fedjax.aggregators.aggregator.""" class AggregatorTest(absltest.TestCase): def test_mean_aggregator(self): delta_params_and_weights = [('a', { 'w': jnp.array([1., 2., 3.]) }, 2.), ('b', { 'w': jnp.array([2., 4., 6.]) }, 4.), ('c', { 'w': jnp.array([1., 3., 5.]) }, 2.)] <|code_end|> . Write the next line using the current file imports: from absl.testing import absltest from fedjax.aggregators import aggregator import jax.numpy as jnp import numpy.testing as npt and context from other files: # Path: fedjax/aggregators/aggregator.py # class Aggregator: # class MeanAggregatorState: # def mean_aggregator() -> Aggregator: # def init(): # def apply(clients_params_and_weights, state): # def extract_params_and_weight(clients_params_and_weight): , which may include functions, classes, or code. Output only the next line.
mean_aggregator = aggregator.mean_aggregator()
Continue the code snippet: <|code_start|># Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """Tests for fedjax.core.tree_util.""" class TreeUtilTest(absltest.TestCase): def test_tree_weight(self): pytree = { 'x': jnp.array([[[4, 5]], [[1, 1]]]), 'y': jnp.array([[3], [1]]), } weight = 2.0 <|code_end|> . Use current file imports: from absl.testing import absltest from fedjax.core import tree_util import jax.numpy as jnp import numpy.testing as npt and context (classes, functions, or code) from other files: # Path: fedjax/core/tree_util.py # def tree_weight(pytree: PyTree, weight: float) -> PyTree: # def tree_inverse_weight(pytree: PyTree, weight: float) -> PyTree: # def tree_zeros_like(pytree: PyTree) -> PyTree: # def tree_add(left: PyTree, right: PyTree) -> PyTree: # def tree_sum(pytrees: Iterable[PyTree]) -> PyTree: # def tree_mean(pytrees_and_weights: Iterable[Tuple[PyTree, float]]) -> PyTree: # def tree_size(pytree: PyTree) -> int: # def tree_l2_squared(pytree: PyTree) -> float: # def tree_l2_norm(pytree: PyTree) -> float: # def tree_clip_by_global_norm(pytree: PyTree, max_norm: float) -> PyTree: . Output only the next line.
weight_pytree = tree_util.tree_weight(pytree, weight)
Here is a 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. # # Derived from https://github.com/google/flax/blob/master/flax/serialization.py # # Copyright 2021 The Flax Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """Simple serialization scheme based on msgpack. We support serializing a dict and list of ndarrays holding numeric types, and bytes (note tuples cannot be serialized since msgpack does not distinguish tuples from lists during deserialization). """ <|code_end|> . Write the next line using the current file imports: import enum import pickle import jax import msgpack import numpy as np from absl import logging from fedjax.core import util and context from other files: # Path: fedjax/core/util.py # def safe_div(a, b): # def __getattr__(self, _): # def import_tf(): # class FakeTensorFlowModule: , which may include functions, classes, or code. Output only the next line.
tf = util.import_tf()
Continue the code snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """Tests for fedjax.core.optimizers.""" class OptimizersTest(absltest.TestCase): def test_ignore_grads_haiku(self): params = hk.data_structures.to_immutable_dict({ 'linear_1': { 'w': jnp.array([1., 1., 1.]) }, 'linear_2': { 'w': jnp.array([2., 2., 2.]), 'b': jnp.array([3., 3., 3.]) } }) grads = jax.tree_util.tree_map(lambda _: 0.5, params) <|code_end|> . Use current file imports: from absl.testing import absltest from fedjax.core import optimizers import flax import haiku as hk import jax import jax.numpy as jnp import numpy.testing as npt and context (classes, functions, or code) from other files: # Path: fedjax/core/optimizers.py # class Optimizer: # def create_optimizer_from_optax(opt: optax.GradientTransformation) -> Optimizer: # def apply(grads, opt_state, params): # def ignore_grads_haiku(optimizer: Optimizer, # non_trainable_names: List[Tuple[str, str]]) -> Optimizer: # def non_trainable_to_none(module_name, name, value): # def init(params): # def apply(grads, opt_state, params): # def adagrad(learning_rate: ScalarOrSchedule, # initial_accumulator_value: float = 0.1, # eps: float = 1e-6) -> Optimizer: # def adam(learning_rate: ScalarOrSchedule, # b1: float = 0.9, # b2: float = 0.999, # eps: float = 1e-8, # eps_root: float = 0.0) -> Optimizer: # def rmsprop(learning_rate: ScalarOrSchedule, # decay: float = 0.9, # eps: float = 1e-8, # initial_scale: float = 0., # centered: bool = False, # momentum: Optional[float] = None, # nesterov: bool = False) -> Optimizer: # def sgd(learning_rate: ScalarOrSchedule, # momentum: Optional[float] = None, # nesterov: bool = False) -> Optimizer: . Output only the next line.
ignore_optimizer = optimizers.ignore_grads_haiku(
Given snippet: <|code_start|># # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """Tests for fedjax.training.checkpoint.""" class CheckpointTest(absltest.TestCase): def setUp(self): super().setUp() self._root_dir = self.create_tempdir() def _write_file(self, basename): path = os.path.join(self._root_dir, basename) with open(path, 'w') as f: f.write(basename) def test_save_checkpoint(self): <|code_end|> , continue by predicting the next line. Consider current file imports: import os import jax.numpy as jnp import numpy.testing as npt from absl.testing import absltest from fedjax.training import checkpoint and context: # Path: fedjax/training/checkpoint.py # _CHECKPOINT_PREFIX = 'checkpoint_' # def _get_checkpoint_paths(base_path: str) -> List[str]: # def sort_key(path): # def load_latest_checkpoint(root_dir: str) -> Optional[Tuple[Any, int]]: # def save_checkpoint(root_dir: str, # state: Any, # round_num: int = 0, # keep: int = 1): which might include code, classes, or functions. Output only the next line.
checkpoint.save_checkpoint(self._root_dir, {'w': jnp.ones(10)})
Predict the next line for this snippet: <|code_start|># Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """Tests for fedjax.datasets.emnist. This file only tests preprocessing functions. """ class EmnistTest(absltest.TestCase): def test_domain_id(self): with self.subTest('invalid'): with self.assertRaisesRegex(ValueError, 'Invalid client_id'): <|code_end|> with the help of current file imports: from absl.testing import absltest from fedjax.datasets import emnist import numpy as np import numpy.testing as npt and context from other files: # Path: fedjax/datasets/emnist.py # SPLITS = ('train', 'test') # def cite(): # def load_split(split: str, # only_digits: bool = False, # mode: str = 'sqlite', # cache_dir: Optional[str] = None) -> federated_data.FederatedData: # def domain_id(client_id: federated_data.ClientId) -> int: # def preprocess_client( # client_id: federated_data.ClientId, # examples: client_datasets.Examples) -> client_datasets.Examples: # def preprocess_batch( # examples: client_datasets.Examples) -> client_datasets.Examples: # def preprocess_split( # fd: federated_data.FederatedData) -> federated_data.FederatedData: # def load_data( # only_digits: bool = False, # mode: str = 'sqlite', # cache_dir: Optional[str] = None # ) -> Tuple[federated_data.FederatedData, federated_data.FederatedData]: , which may contain function names, class names, or code. Output only the next line.
emnist.domain_id(b'not_emnist')
Here is a snippet: <|code_start|>"""Tests for fedjax.core.sqlite_federated_data.""" tf = util.import_tf() FLAGS = flags.FLAGS class SQLiteFederatedDataTest(absltest.TestCase): @classmethod def setUpClass(cls): super().setUpClass() path = os.path.join(FLAGS.test_tmpdir, 'test_sqlite_federated_data.sqlite') # Create database file. First make sure the database file is empty. with open(path, 'w'): pass connection = sqlite3.connect(path) with connection: connection.execute(""" CREATE TABLE federated_data ( client_id BLOB NOT NULL PRIMARY KEY, data BLOB NOT NULL, num_examples INTEGER NOT NULL );""") for i in range(100): client_id = f'{i:04x}'.encode('ascii') features = {'x': np.arange(i + 1)} <|code_end|> . Write the next line using the current file imports: import itertools import os.path import zlib import numpy as np import numpy.testing as npt import sqlite3 from absl import flags from absl.testing import absltest from fedjax.core import serialization from fedjax.core import sqlite_federated_data from fedjax.core import util and context from other files: # Path: fedjax/core/serialization.py # def save_state(state, path): # def load_state(path): # def _ndarray_to_bytes(arr): # def _dtype_from_name(name): # def _ndarray_from_bytes(data): # def _bytes_ndarray_to_bytes(x): # def _object_ndarray_from_bytes(data): # def _msgpack_ext_pack(x): # def _msgpack_ext_unpack(code, data): # def msgpack_serialize(pytree): # def msgpack_deserialize(encoded_pytree): # class _MsgpackExtType(enum.IntEnum): # # Path: fedjax/core/sqlite_federated_data.py # def decompress_and_deserialize(data: bytes): # def new( # path: str, # parse_examples: Callable[ # [bytes], client_datasets.Examples] = decompress_and_deserialize # ) -> 'SQLiteFederatedData': # def __init__(self, # connection: sqlite3.Connection, # parse_examples: Callable[[bytes], client_datasets.Examples], # start: Optional[federated_data.ClientId] = None, # stop: Optional[federated_data.ClientId] = None, # preprocess_client: federated_data # .ClientPreprocessor = federated_data.NoOpClientPreprocessor, # preprocess_batch: client_datasets # .BatchPreprocessor = client_datasets.NoOpBatchPreprocessor): # def slice( # self, # start: Optional[federated_data.ClientId] = None, # stop: Optional[federated_data.ClientId] = None) -> 'SQLiteFederatedData': # def preprocess_client( # self, fn: Callable[[federated_data.ClientId, client_datasets.Examples], # client_datasets.Examples] # ) -> 'SQLiteFederatedData': # def preprocess_batch( # self, fn: Callable[[client_datasets.Examples], client_datasets.Examples] # ) -> 'SQLiteFederatedData': # def _range_where(self) -> str: # def num_clients(self) -> int: # def client_ids(self) -> Iterator[federated_data.ClientId]: # def client_sizes(self) -> Iterator[Tuple[federated_data.ClientId, int]]: # def client_size(self, client_id: federated_data.ClientId) -> int: # def clients( # self # ) -> Iterator[Tuple[federated_data.ClientId, client_datasets.ClientDataset]]: # def _read_clients(self): # def shuffled_clients( # self, # buffer_size: int, # seed: Optional[int] = None # ) -> Iterator[Tuple[federated_data.ClientId, client_datasets.ClientDataset]]: # def get_clients( # self, client_ids: Iterable[federated_data.ClientId] # ) -> Iterator[Tuple[federated_data.ClientId, client_datasets.ClientDataset]]: # def get_client( # self, # client_id: federated_data.ClientId) -> client_datasets.ClientDataset: # def _client_dataset(self, client_id: federated_data.ClientId, # data: bytes) -> client_datasets.ClientDataset: # def __init__(self, path: str): # def __enter__(self): # def __exit__(self, exc_type, exc_value, exc_traceback): # def add_many(self, # client_ids_examples: Iterable[Tuple[bytes, # client_datasets.Examples]]): # def prepare_parameters(ce): # def __init__(self, path: str, # parse_examples: Callable[[List[bytes]], # client_datasets.Examples], # split_name: str): # def __del__(self): # def __iter__( # self # ) -> Iterator[Tuple[federated_data.ClientId, client_datasets.ClientDataset]]: # def __next__( # self) -> Tuple[federated_data.ClientId, client_datasets.ClientDataset]: # class SQLiteFederatedData(federated_data.FederatedData): # class SQLiteFederatedDataBuilder(federated_data.FederatedDataBuilder): # class TFFSQLiteClientsIterator: # # Path: fedjax/core/util.py # def safe_div(a, b): # def __getattr__(self, _): # def import_tf(): # class FakeTensorFlowModule: , which may include functions, classes, or code. Output only the next line.
data = zlib.compress(serialization.msgpack_serialize(features))
Using the snippet: <|code_start|>FLAGS = flags.FLAGS class SQLiteFederatedDataTest(absltest.TestCase): @classmethod def setUpClass(cls): super().setUpClass() path = os.path.join(FLAGS.test_tmpdir, 'test_sqlite_federated_data.sqlite') # Create database file. First make sure the database file is empty. with open(path, 'w'): pass connection = sqlite3.connect(path) with connection: connection.execute(""" CREATE TABLE federated_data ( client_id BLOB NOT NULL PRIMARY KEY, data BLOB NOT NULL, num_examples INTEGER NOT NULL );""") for i in range(100): client_id = f'{i:04x}'.encode('ascii') features = {'x': np.arange(i + 1)} data = zlib.compress(serialization.msgpack_serialize(features)) num_examples = i + 1 connection.execute('INSERT INTO federated_data VALUES (?, ?, ?);', [client_id, data, num_examples]) connection.close() <|code_end|> , determine the next line of code. You have imports: import itertools import os.path import zlib import numpy as np import numpy.testing as npt import sqlite3 from absl import flags from absl.testing import absltest from fedjax.core import serialization from fedjax.core import sqlite_federated_data from fedjax.core import util and context (class names, function names, or code) available: # Path: fedjax/core/serialization.py # def save_state(state, path): # def load_state(path): # def _ndarray_to_bytes(arr): # def _dtype_from_name(name): # def _ndarray_from_bytes(data): # def _bytes_ndarray_to_bytes(x): # def _object_ndarray_from_bytes(data): # def _msgpack_ext_pack(x): # def _msgpack_ext_unpack(code, data): # def msgpack_serialize(pytree): # def msgpack_deserialize(encoded_pytree): # class _MsgpackExtType(enum.IntEnum): # # Path: fedjax/core/sqlite_federated_data.py # def decompress_and_deserialize(data: bytes): # def new( # path: str, # parse_examples: Callable[ # [bytes], client_datasets.Examples] = decompress_and_deserialize # ) -> 'SQLiteFederatedData': # def __init__(self, # connection: sqlite3.Connection, # parse_examples: Callable[[bytes], client_datasets.Examples], # start: Optional[federated_data.ClientId] = None, # stop: Optional[federated_data.ClientId] = None, # preprocess_client: federated_data # .ClientPreprocessor = federated_data.NoOpClientPreprocessor, # preprocess_batch: client_datasets # .BatchPreprocessor = client_datasets.NoOpBatchPreprocessor): # def slice( # self, # start: Optional[federated_data.ClientId] = None, # stop: Optional[federated_data.ClientId] = None) -> 'SQLiteFederatedData': # def preprocess_client( # self, fn: Callable[[federated_data.ClientId, client_datasets.Examples], # client_datasets.Examples] # ) -> 'SQLiteFederatedData': # def preprocess_batch( # self, fn: Callable[[client_datasets.Examples], client_datasets.Examples] # ) -> 'SQLiteFederatedData': # def _range_where(self) -> str: # def num_clients(self) -> int: # def client_ids(self) -> Iterator[federated_data.ClientId]: # def client_sizes(self) -> Iterator[Tuple[federated_data.ClientId, int]]: # def client_size(self, client_id: federated_data.ClientId) -> int: # def clients( # self # ) -> Iterator[Tuple[federated_data.ClientId, client_datasets.ClientDataset]]: # def _read_clients(self): # def shuffled_clients( # self, # buffer_size: int, # seed: Optional[int] = None # ) -> Iterator[Tuple[federated_data.ClientId, client_datasets.ClientDataset]]: # def get_clients( # self, client_ids: Iterable[federated_data.ClientId] # ) -> Iterator[Tuple[federated_data.ClientId, client_datasets.ClientDataset]]: # def get_client( # self, # client_id: federated_data.ClientId) -> client_datasets.ClientDataset: # def _client_dataset(self, client_id: federated_data.ClientId, # data: bytes) -> client_datasets.ClientDataset: # def __init__(self, path: str): # def __enter__(self): # def __exit__(self, exc_type, exc_value, exc_traceback): # def add_many(self, # client_ids_examples: Iterable[Tuple[bytes, # client_datasets.Examples]]): # def prepare_parameters(ce): # def __init__(self, path: str, # parse_examples: Callable[[List[bytes]], # client_datasets.Examples], # split_name: str): # def __del__(self): # def __iter__( # self # ) -> Iterator[Tuple[federated_data.ClientId, client_datasets.ClientDataset]]: # def __next__( # self) -> Tuple[federated_data.ClientId, client_datasets.ClientDataset]: # class SQLiteFederatedData(federated_data.FederatedData): # class SQLiteFederatedDataBuilder(federated_data.FederatedDataBuilder): # class TFFSQLiteClientsIterator: # # Path: fedjax/core/util.py # def safe_div(a, b): # def __getattr__(self, _): # def import_tf(): # class FakeTensorFlowModule: . Output only the next line.
cls.FEDERATED_DATA = sqlite_federated_data.SQLiteFederatedData.new(path)
Given snippet: <|code_start|>"""Methods for checkpointing.""" tf = util.import_tf() _CHECKPOINT_PREFIX = 'checkpoint_' def _get_checkpoint_paths(base_path: str) -> List[str]: """Returns all checkpoint paths present.""" pattern = base_path + r'[0-9]{8}$' checkpoint_paths = [] for path in tf.io.gfile.glob(base_path + '*'): if re.match(pattern, path): checkpoint_paths.append(path) def sort_key(path): return int(path.split(base_path)[-1]) return sorted(checkpoint_paths, key=sort_key) def load_latest_checkpoint(root_dir: str) -> Optional[Tuple[Any, int]]: """Loads latest checkpoint and round number.""" base_path = os.path.join(root_dir, _CHECKPOINT_PREFIX) all_checkpoint_paths = _get_checkpoint_paths(base_path) if all_checkpoint_paths: latest_checkpoint_path = all_checkpoint_paths[-1] latest_round_num = int(latest_checkpoint_path.split(base_path)[-1]) <|code_end|> , continue by predicting the next line. Consider current file imports: import os.path import re from typing import Any, List, Optional, Tuple from fedjax.core import serialization from fedjax.core import util and context: # Path: fedjax/core/serialization.py # def save_state(state, path): # def load_state(path): # def _ndarray_to_bytes(arr): # def _dtype_from_name(name): # def _ndarray_from_bytes(data): # def _bytes_ndarray_to_bytes(x): # def _object_ndarray_from_bytes(data): # def _msgpack_ext_pack(x): # def _msgpack_ext_unpack(code, data): # def msgpack_serialize(pytree): # def msgpack_deserialize(encoded_pytree): # class _MsgpackExtType(enum.IntEnum): # # Path: fedjax/core/util.py # def safe_div(a, b): # def __getattr__(self, _): # def import_tf(): # class FakeTensorFlowModule: which might include code, classes, or functions. Output only the next line.
latest_state = serialization.load_state(latest_checkpoint_path)
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.Let's use the full copyright notice """Test for data_to_sqlite normalization.""" class DataToSQLiteTest(parameterized.TestCase): @parameterized.named_parameters( { 'testcase_name': 'test url and username', 'input_string': 'Thank @user1 https://en.wikipedia.org more story...', 'desired': 'thank USERNAME URL more story', }, { 'testcase_name': 'test numerics', 'input_string': 'Pi 3.14, 10 months, 50,000.00 and 7-10.', 'desired': 'pi NUMERIC NUMERIC months NUMERIC and NUMERIC', }, { 'testcase_name': 'test hyphen', 'input_string': 'This is a double--hyphen! And this is a single-one.', 'desired': 'this is a double hyphen and this is a single-one', }, { 'testcase_name': 'test punctuation', 'input_string': 'I.do{not},know....that*', 'desired': 'i do not know that', }) def test_normalize_dialogue_string(self, input_string, desired): <|code_end|> using the current file's imports: from absl.testing import absltest from absl.testing import parameterized from fedjax.datasets.scripts.sent140 import data_to_sqlite and any relevant context from other files: # Path: fedjax/datasets/scripts/sent140/data_to_sqlite.py # FLAGS = flags.FLAGS # def main(argv) -> None: # def user_data_to_numpy(user_data: List[List[str]]) -> Dict[str, np.ndarray]: # def normalize_tweet(tweet: str) -> str: . Output only the next line.
self.assertEqual(desired, data_to_sqlite.normalize_tweet(input_string))
Predict the next line for this snippet: <|code_start|># 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. """Tests for fedjax.models.emnist.""" class EmnistModelTest(absltest.TestCase): def check_model(self, model): rng = jax.random.PRNGKey(0) params = model.init(rng) batch = {'x': jnp.ones((5, 28, 28, 1)), 'y': jnp.ones((5,))} with self.subTest('apply_for_train'): preds = model.apply_for_train(params, batch, rng) self.assertTupleEqual(preds.shape, (5, 62)) with self.subTest('apply_for_eval'): preds = model.apply_for_eval(params, batch) self.assertTupleEqual(preds.shape, (5, 62)) with self.subTest('train_loss'): preds = model.apply_for_train(params, batch, rng) train_loss = model.train_loss(batch, preds) self.assertTupleEqual(train_loss.shape, (5,)) def test_create_conv_model(self): model = emnist.create_conv_model(only_digits=False) params = model.init(jax.random.PRNGKey(0)) <|code_end|> with the help of current file imports: from absl.testing import absltest from fedjax.core import tree_util from fedjax.models import emnist import jax import jax.numpy as jnp and context from other files: # Path: fedjax/core/tree_util.py # def tree_weight(pytree: PyTree, weight: float) -> PyTree: # def tree_inverse_weight(pytree: PyTree, weight: float) -> PyTree: # def tree_zeros_like(pytree: PyTree) -> PyTree: # def tree_add(left: PyTree, right: PyTree) -> PyTree: # def tree_sum(pytrees: Iterable[PyTree]) -> PyTree: # def tree_mean(pytrees_and_weights: Iterable[Tuple[PyTree, float]]) -> PyTree: # def tree_size(pytree: PyTree) -> int: # def tree_l2_squared(pytree: PyTree) -> float: # def tree_l2_norm(pytree: PyTree) -> float: # def tree_clip_by_global_norm(pytree: PyTree, max_norm: float) -> PyTree: # # Path: fedjax/models/emnist.py # class Dropout(hk.Module): # class ConvDropoutModule(hk.Module): # def __init__(self, rate: float = 0.5): # def __call__(self, x: jnp.ndarray, is_train: bool): # def __init__(self, num_classes): # def __call__(self, x: jnp.ndarray, is_train: bool): # def create_conv_model(only_digits: bool = False) -> models.Model: # def forward_pass(batch, is_train=True): # def create_dense_model(only_digits: bool = False, # hidden_units: int = 200) -> models.Model: # def forward_pass(batch): # def create_logistic_model(only_digits: bool = False) -> models.Model: # def forward_pass(batch): # def create_stax_dense_model(only_digits: bool = False, # hidden_units: int = 200) -> models.Model: # _HAIKU_SAMPLE_BATCH = { # 'x': np.zeros((1, 28, 28, 1), dtype=np.float32), # 'y': np.zeros(1, dtype=np.float32) # } # _STAX_SAMPLE_SHAPE = (-1, 28, 28, 1) # _TRAIN_LOSS = lambda b, p: metrics.unreduced_cross_entropy_loss(b['y'], p) # _EVAL_METRICS = { # 'loss': metrics.CrossEntropyLoss(), # 'accuracy': metrics.Accuracy() # } , which may contain function names, class names, or code. Output only the next line.
self.assertEqual(tree_util.tree_size(params), 1206590)
Continue the code 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. """Tests for fedjax.models.emnist.""" class EmnistModelTest(absltest.TestCase): def check_model(self, model): rng = jax.random.PRNGKey(0) params = model.init(rng) batch = {'x': jnp.ones((5, 28, 28, 1)), 'y': jnp.ones((5,))} with self.subTest('apply_for_train'): preds = model.apply_for_train(params, batch, rng) self.assertTupleEqual(preds.shape, (5, 62)) with self.subTest('apply_for_eval'): preds = model.apply_for_eval(params, batch) self.assertTupleEqual(preds.shape, (5, 62)) with self.subTest('train_loss'): preds = model.apply_for_train(params, batch, rng) train_loss = model.train_loss(batch, preds) self.assertTupleEqual(train_loss.shape, (5,)) def test_create_conv_model(self): <|code_end|> . Use current file imports: from absl.testing import absltest from fedjax.core import tree_util from fedjax.models import emnist import jax import jax.numpy as jnp and context (classes, functions, or code) from other files: # Path: fedjax/core/tree_util.py # def tree_weight(pytree: PyTree, weight: float) -> PyTree: # def tree_inverse_weight(pytree: PyTree, weight: float) -> PyTree: # def tree_zeros_like(pytree: PyTree) -> PyTree: # def tree_add(left: PyTree, right: PyTree) -> PyTree: # def tree_sum(pytrees: Iterable[PyTree]) -> PyTree: # def tree_mean(pytrees_and_weights: Iterable[Tuple[PyTree, float]]) -> PyTree: # def tree_size(pytree: PyTree) -> int: # def tree_l2_squared(pytree: PyTree) -> float: # def tree_l2_norm(pytree: PyTree) -> float: # def tree_clip_by_global_norm(pytree: PyTree, max_norm: float) -> PyTree: # # Path: fedjax/models/emnist.py # class Dropout(hk.Module): # class ConvDropoutModule(hk.Module): # def __init__(self, rate: float = 0.5): # def __call__(self, x: jnp.ndarray, is_train: bool): # def __init__(self, num_classes): # def __call__(self, x: jnp.ndarray, is_train: bool): # def create_conv_model(only_digits: bool = False) -> models.Model: # def forward_pass(batch, is_train=True): # def create_dense_model(only_digits: bool = False, # hidden_units: int = 200) -> models.Model: # def forward_pass(batch): # def create_logistic_model(only_digits: bool = False) -> models.Model: # def forward_pass(batch): # def create_stax_dense_model(only_digits: bool = False, # hidden_units: int = 200) -> models.Model: # _HAIKU_SAMPLE_BATCH = { # 'x': np.zeros((1, 28, 28, 1), dtype=np.float32), # 'y': np.zeros(1, dtype=np.float32) # } # _STAX_SAMPLE_SHAPE = (-1, 28, 28, 1) # _TRAIN_LOSS = lambda b, p: metrics.unreduced_cross_entropy_loss(b['y'], p) # _EVAL_METRICS = { # 'loss': metrics.CrossEntropyLoss(), # 'accuracy': metrics.Accuracy() # } . Output only the next line.
model = emnist.create_conv_model(only_digits=False)
Continue the code snippet: <|code_start|># Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """Tests for fedjax.aggregators.compression.""" class CompressionTest(absltest.TestCase): def test_num_leaves(self): params = {'w': jnp.array([1., 2., 3.]), 'b': jnp.array([1.])} <|code_end|> . Use current file imports: from absl.testing import absltest from fedjax.aggregators import compression import jax import jax.numpy as jnp import numpy.testing as npt and context (classes, functions, or code) from other files: # Path: fedjax/aggregators/compression.py # class CompressionState: # def binary_stochastic_quantize(v: jnp.ndarray, # rng: PRNGKey, # v_min: Optional[float] = None, # v_max: Optional[float] = None) -> jnp.ndarray: # def uniform_stochastic_quantize(v: jnp.ndarray, # num_levels: int, # rng: PRNGKey, # v_min: Optional[float] = None, # v_max: Optional[float] = None) -> jnp.ndarray: # def uniform_stochastic_quantize_pytree(params: Params, num_levels: int, # rng: PRNGKey) -> Params: # def num_leaves(pytree): # def _entropy(v, uniq): # def _hist_bits(v, uniq): # def arithmetic_encoding_num_bits(v: jnp.ndarray) -> int: # def uniform_stochastic_quantizer( # num_levels: int, # rng: PRNGKey, # encode_algorithm: Optional[str] = None) -> aggregator.Aggregator: # def init(): # def apply( # clients_params_and_weights: Iterable[Tuple[ClientId, Params, float]], # aggregator_state: CompressionState) -> Tuple[Params, CompressionState]: # def quantize_params_and_weight(client_params_and_weight, rng): # def arithmetic_encoding_num_bits_pytree(params, weights): # def rotated_uniform_stochastic_quantizer(num_levels: int, # rng: PRNGKey) -> aggregator.Aggregator: # def init(): # def apply( # clients_params_and_weights: Iterable[Tuple[ClientId, Params, float]], # aggregator_state: CompressionState) -> Tuple[Params, CompressionState]: # def quantize_params_and_weight(client_params_and_weight, rng): # def drive_pytree(params: Params) -> Params: # def structured_drive_quantizer(rng: PRNGKey) -> aggregator.Aggregator: # def init(): # def apply( # clients_params_and_weights: Iterable[Tuple[ClientId, Params, float]], # aggregator_state: CompressionState) -> Tuple[Params, CompressionState]: # def quantize_params_and_weight(client_id, params, weight): # def terngrad_quantize(v: jnp.ndarray, rng: PRNGKey) -> jnp.ndarray: # def terngrad_quantize_pytree(params: Params, rng: PRNGKey) -> Params: # def terngrad_quantizer(rng: PRNGKey) -> aggregator.Aggregator: # def init(): # def apply( # clients_params_and_weights: Iterable[Tuple[ClientId, Params, float]], # aggregator_state: CompressionState) -> Tuple[Params, CompressionState]: # def quantize_params_and_weight(client_params_and_weight, rng): . Output only the next line.
self.assertEqual(compression.num_leaves(params), 2)
Based on the snippet: <|code_start|> return str(self) # A common default preprocessor that does nothing. NoOpBatchPreprocessor = BatchPreprocessor() # A special feature name for padded batches. EXAMPLE_MASK_KEY = '__mask__' # We group hyperparams to batching functions so that, # # 1. They can be easily passed around as a single object, instead of a list of # arguments. # 2. The list of argument is only defined, documented, and assigned default # values once (in the hyperparams class). # # This setup is more convenient for library code where the caller specifies such # a hyperparams object, but less so for users directly calling the actual # batching function (e.g. compare `padded_batch(batch_size=3)` vs # `padded_batch(PaddedBatchHParams(batch_size=3))`. Therefore, all our batching # functions support two ways of invocation: # - They can be passed in a hyperparams object. # - They can also be passed in a list of keyword arguments, which will be used # to construct the hyperparams object. # # See ClientDataset.padded_batch() for an example. <|code_end|> , predict the immediate next line with the help of imports: import collections import itertools import numpy as np from typing import Any, Callable, Iterable, Iterator, Mapping, Optional from fedjax.core import dataclasses and context (classes, functions, sometimes code) from other files: # Path: fedjax/core/dataclasses.py # def dataclass(clz: type): # def replace(self, **updates): # def iterate_clz(x): # def clz_from_iterable(meta, data): . Output only the next line.
@dataclasses.dataclass
Predict the next line for this snippet: <|code_start|># Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """Tests for walsh_hadamard.""" class WalshHadamardTest(absltest.TestCase): def test_walsh_hadamard_transform(self): # TODO(wuke): Change bfloat16_3x to high once the PyPI JAX release catches # up. for precision in ['fastest', 'bfloat16_3x', 'highest']: for seed in range(5): n = 2**10 x = jnp.array(jax.random.normal(jax.random.PRNGKey(seed), shape=[n])) expect = jnp.dot( <|code_end|> with the help of current file imports: from absl.testing import absltest from fedjax.aggregators import walsh_hadamard import jax import jax.numpy as jnp import numpy.testing as npt and context from other files: # Path: fedjax/aggregators/walsh_hadamard.py # def walsh_hadamard_transform( # x: jnp.ndarray, # small_n: int = 2**7, # precision: Union[jax.lax.Precision, str] = 'highest') -> jnp.ndarray: # def hadamard_matrix(n: int, dtype: jnp.dtype) -> jnp.ndarray: # def structured_rotation(x: jnp.ndarray, # rng: PRNGKey) -> Tuple[jnp.ndarray, jnp.ndarray]: # def inverse_structured_rotation(x: jnp.ndarray, rng: PRNGKey, # original_shape: jnp.ndarray) -> jnp.ndarray: # def structured_rotation_pytree(params: Params, # rng: PRNGKey) -> Tuple[Params, Params]: # def inverse_structured_rotation_pytree(params: Params, rng: PRNGKey, # shapes: Params) -> Params: , which may contain function names, class names, or code. Output only the next line.
walsh_hadamard.hadamard_matrix(n, x.dtype), x, precision=precision)
Based on the snippet: <|code_start|># Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """Tests for fedjax.datasets.cifar100. This file only tests preprocessing functions. """ class Cifar100Test(absltest.TestCase): def test_preprocess_client(self): image = np.random.randint(256, size=[4, 32, 32, 3]).astype(np.uint8) coarse_label = np.random.randint(20, size=[4]).astype(np.int64) label = np.random.randint(100, size=[4]).astype(np.int64) npt.assert_equal( <|code_end|> , predict the immediate next line with the help of imports: from absl.testing import absltest from fedjax.datasets import cifar100 import numpy as np import numpy.testing as npt and context (classes, functions, sometimes code) from other files: # Path: fedjax/datasets/cifar100.py # SPLITS = ('train', 'test') # _TFF_SQLITE_COMPRESSED_HEXDIGEST = '23d3916c9caa33395737ee560cc7cb77bbd05fc7b73647ee7be3a7e764172939' # _TFF_SQLITE_COMPRESSED_NUM_BYTES = 153019920 # _FEDJAX_SQLITE_HEXDIGEST = { # 'train': 'a4dc2f4ac4c9b6e7bd5234a1b568389384c00c903dcd34001c3cf50a4a81c713', # 'test': '74416c6ee8f41b1086f0e0e3c5289ac6df5a641100df48e8b583411a55de891f' # } # _FEDJAX_SQLITE_NUM_BYTES = {'train': 140521472, 'test': 28135424} # CIFAR100_PIXELS_MEAN = np.array([0.4914, 0.4822, 0.4465], dtype=np.float32) # CIFAR100_PIXELS_INVERSE_STDDEV = ( # 1 / np.array([0.2023, 0.1994, 0.2010], dtype=np.float32)) # def cite(): # def _parse_tf_examples(vs: List[bytes]) -> client_datasets.Examples: # def load_split(split: str, # mode: str = 'sqlite', # cache_dir: Optional[str] = None) -> federated_data.FederatedData: # def load_data( # mode: str = 'sqlite', # cache_dir: Optional[str] = None # ) -> Tuple[federated_data.FederatedData, federated_data.FederatedData]: # def preprocess_client( # client_id: federated_data.ClientId, # examples: client_datasets.Examples) -> client_datasets.Examples: # def preprocess_image(image: np.ndarray, is_train: bool) -> np.ndarray: # def preprocess_batch(examples: client_datasets.Examples, # is_train: bool) -> client_datasets.Examples: . Output only the next line.
cifar100.preprocess_client(None, {
Next line prediction: <|code_start|># Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """Utilities for working with tree-like container data structures. In JAX, the term pytree refers to a tree-like structure built out of container-like Python objects. For more details, see https://jax.readthedocs.io/en/latest/pytrees.html. """ @jax.jit <|code_end|> . Use current file imports: (from typing import Iterable, Tuple from fedjax.core.typing import PyTree import jax import jax.numpy as jnp) and context including class names, function names, or small code snippets from other files: # Path: fedjax/core/typing.py . Output only the next line.
def tree_weight(pytree: PyTree, weight: float) -> PyTree:
Continue the code snippet: <|code_start|># Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """Tests for fedjax.models.toy_regression.""" class ToyRegressionModelTest(absltest.TestCase): def test_create_regression_model(self): model = toy_regression.create_regression_model() params = model.init(jax.random.PRNGKey(0)) batch = {'x': jnp.ones((5, 1)), 'y': jnp.ones((5,))} <|code_end|> . Use current file imports: from absl.testing import absltest from fedjax.core import tree_util from fedjax.models import toy_regression import jax import jax.numpy as jnp and context (classes, functions, or code) from other files: # Path: fedjax/core/tree_util.py # def tree_weight(pytree: PyTree, weight: float) -> PyTree: # def tree_inverse_weight(pytree: PyTree, weight: float) -> PyTree: # def tree_zeros_like(pytree: PyTree) -> PyTree: # def tree_add(left: PyTree, right: PyTree) -> PyTree: # def tree_sum(pytrees: Iterable[PyTree]) -> PyTree: # def tree_mean(pytrees_and_weights: Iterable[Tuple[PyTree, float]]) -> PyTree: # def tree_size(pytree: PyTree) -> int: # def tree_l2_squared(pytree: PyTree) -> float: # def tree_l2_norm(pytree: PyTree) -> float: # def tree_clip_by_global_norm(pytree: PyTree, max_norm: float) -> PyTree: # # Path: fedjax/models/toy_regression.py # def create_regression_model() -> models.Model: # def forward_pass(batch): # def train_loss(batch, preds): . Output only the next line.
self.assertEqual(tree_util.tree_size(params), 1)
Given snippet: <|code_start|> THRESHOLD = getattr(settings, "THRESHOLD", 3) class SlugLookupRedirectView(RedirectView): permanent = False def get_redirect_url(self, **kwargs): slug = kwargs.get('slug', '') project = kwargs.get('project', '') if slug == '': return reverse('home') redirect_url = '' <|code_end|> , continue by predicting the next line. Consider current file imports: from django.core.urlresolvers import reverse from django.conf import settings from django.http import HttpResponseRedirect from django.views.generic import RedirectView, TemplateView, FormView from analytics.models import Visit from .api import RedisProject, RedisRedirect from .forms import SlugForm and context: # Path: src/hydra/api.py # class RedisProject(object): # """ # A model layer representing a Project in Redis. # # It has an index of all existing projects, and then contains metadata about # projects including their existence, and a whitelist of URLs that you can # link to from them. # # Generally you create an instance by passing in a name, and a possible # whitelist. If you only pass in the name, the whitelist is populated from # the data store. # # The main methods you will call on an instance are save, delete, and exists. # There is a classmethod called all_projects that will return all projects. # # """ # index_slug = "hydra:v1:projects" # # def __init__(self, name=None, whitelist=None, *args, **kwargs): # super(RedisProject, self).__init__(*args, **kwargs) # self.name = name # if whitelist: # self.whitelist = whitelist # else: # # We need to populate the whitelist here, # # so when we return the object, it will serialize with them # self.whitelist = self.get_whitelist() # # @classmethod # def all_projects(cls): # """ # Return all projects. Classmethod because it doesn't need any data on # the instance. # """ # ret_val = r.sort(cls.index_slug) # return ret_val # # @property # def redis_slug(self): # return "hydra:v1:projects:%s" % (self.name) # # def save_whitelist(self): # for redirect_url in self.whitelist: # r.sadd("%s:whitelist" % self.redis_slug, redirect_url) # # def save_project(self): # r.hset(self.redis_slug, "exists", "true") # r.sadd(self.index_slug, self.name) # # def save(self): # self.save_whitelist() # self.save_project() # # def delete(self): # r.delete(self.redis_slug) # r.delete("%s:whitelist" % self.redis_slug) # r.srem(self.index_slug, self.name) # # def exists(self): # return r.hget(self.redis_slug, "exists") == "true" # # def get_whitelist(self): # return r.smembers("%s:whitelist" % self.redis_slug) # # class RedisRedirect(object): # """ # A Redis Model for a Redirect # # This contains the basic information about how a projects redirects will # work. # # The set of (project, slug) is unique, and each contains a set of URLs that # might possibly be correct. We store these in a sorted set so that we can # keep score of clicks in the data model in Redis. # """ # # def __init__(self, slug=None, project=None, urls=None, *args, **kwargs): # super(RedisRedirect, self).__init__(*args, **kwargs) # self.project = project # self.slug = slug # if urls: # self.urls = urls # else: # self.urls = self.get_urls() # # @property # def index_slug(self): # return "hydra:v1:projects:%s:slugs" % (self.project) # # @property # def redis_slug(self): # return "%s:%s" % (self.index_slug, self.slug) # # def all_slugs(self): # return r.sort(self.index_slug) # # def save_redirect(self): # r.sadd(self.index_slug, self.slug) # # def save_urls(self): # for obj in self.urls: # if hasattr(obj, 'get'): # if obj.get('score', None): # r.zadd(self.redis_slug, int(obj['score']), obj['url']) # else: # r.zincrby(self.redis_slug, self.urls[0], 1) # # def save(self): # proj = RedisProject(name=self.project) # proj.save() # self.save_redirect() # self.save_urls() # return True # # def delete(self): # r.delete(self.redis_slug) # r.srem(self.index_slug, self.slug) # # def incr(self, url): # self.save_redirect() # r.zincrby(self.redis_slug, url, 1) # # def url_exists(self, url): # for url_obj in self.get_urls(): # if url == url_obj['url']: # return True # return False # # def exists(self): # return r.zcard(self.redis_slug) # # def get_urls(self): # urls = r.zrevrange(self.redis_slug, 0, -1, withscores=True) # ret_val = [] # for obj in urls: # redirect_url, score = obj # ret_val.append({ # 'score': score, # 'url': redirect_url # }) # return ret_val # # Path: src/hydra/forms.py # class SlugForm(forms.Form): # project = forms.CharField(max_length=255) # slug = forms.CharField(max_length=255) # url = forms.URLField() # # def clean_url(self): # url = self.cleaned_data['url'] # project = self.cleaned_data['project'] # valid, msg = in_whitelist(project, url) # if not valid: # raise forms.ValidationError(msg) # return url which might include code, classes, or functions. Output only the next line.
proj_obj = RedisRedirect(slug=slug, project=project)
Predict the next line for this snippet: <|code_start|> class SlugForm(forms.Form): project = forms.CharField(max_length=255) slug = forms.CharField(max_length=255) url = forms.URLField() def clean_url(self): url = self.cleaned_data['url'] project = self.cleaned_data['project'] <|code_end|> with the help of current file imports: from django import forms from .utils import in_whitelist and context from other files: # Path: src/hydra/utils.py # def in_whitelist(project, url): # parsed_url = urlparse(url) # if parsed_url.scheme == '': # return False, 'url must be absolute' # project = RedisProject(project) # results = [parsed_url.netloc.endswith('.%s' % domain) # for domain in project.whitelist] # results.append(parsed_url.netloc in project.whitelist) # if not any(results): # return False, '%s is not on a domain in the whitelist.' % url # return True, '' , which may contain function names, class names, or code. Output only the next line.
valid, msg = in_whitelist(project, url)
Next line prediction: <|code_start|> r = redis.StrictRedis.from_url(settings.REDIS_URL) def safe_save(project, slug, url): """ Save things to Redis, but check if they exist first """ <|code_end|> . Use current file imports: (import redis import operator from urlparse import urlparse from django.conf import settings from sphinx.ext import intersphinx from .api import RedisRedirect, RedisProject) and context including class names, function names, or small code snippets from other files: # Path: src/hydra/api.py # class RedisRedirect(object): # """ # A Redis Model for a Redirect # # This contains the basic information about how a projects redirects will # work. # # The set of (project, slug) is unique, and each contains a set of URLs that # might possibly be correct. We store these in a sorted set so that we can # keep score of clicks in the data model in Redis. # """ # # def __init__(self, slug=None, project=None, urls=None, *args, **kwargs): # super(RedisRedirect, self).__init__(*args, **kwargs) # self.project = project # self.slug = slug # if urls: # self.urls = urls # else: # self.urls = self.get_urls() # # @property # def index_slug(self): # return "hydra:v1:projects:%s:slugs" % (self.project) # # @property # def redis_slug(self): # return "%s:%s" % (self.index_slug, self.slug) # # def all_slugs(self): # return r.sort(self.index_slug) # # def save_redirect(self): # r.sadd(self.index_slug, self.slug) # # def save_urls(self): # for obj in self.urls: # if hasattr(obj, 'get'): # if obj.get('score', None): # r.zadd(self.redis_slug, int(obj['score']), obj['url']) # else: # r.zincrby(self.redis_slug, self.urls[0], 1) # # def save(self): # proj = RedisProject(name=self.project) # proj.save() # self.save_redirect() # self.save_urls() # return True # # def delete(self): # r.delete(self.redis_slug) # r.srem(self.index_slug, self.slug) # # def incr(self, url): # self.save_redirect() # r.zincrby(self.redis_slug, url, 1) # # def url_exists(self, url): # for url_obj in self.get_urls(): # if url == url_obj['url']: # return True # return False # # def exists(self): # return r.zcard(self.redis_slug) # # def get_urls(self): # urls = r.zrevrange(self.redis_slug, 0, -1, withscores=True) # ret_val = [] # for obj in urls: # redirect_url, score = obj # ret_val.append({ # 'score': score, # 'url': redirect_url # }) # return ret_val # # class RedisProject(object): # """ # A model layer representing a Project in Redis. # # It has an index of all existing projects, and then contains metadata about # projects including their existence, and a whitelist of URLs that you can # link to from them. # # Generally you create an instance by passing in a name, and a possible # whitelist. If you only pass in the name, the whitelist is populated from # the data store. # # The main methods you will call on an instance are save, delete, and exists. # There is a classmethod called all_projects that will return all projects. # # """ # index_slug = "hydra:v1:projects" # # def __init__(self, name=None, whitelist=None, *args, **kwargs): # super(RedisProject, self).__init__(*args, **kwargs) # self.name = name # if whitelist: # self.whitelist = whitelist # else: # # We need to populate the whitelist here, # # so when we return the object, it will serialize with them # self.whitelist = self.get_whitelist() # # @classmethod # def all_projects(cls): # """ # Return all projects. Classmethod because it doesn't need any data on # the instance. # """ # ret_val = r.sort(cls.index_slug) # return ret_val # # @property # def redis_slug(self): # return "hydra:v1:projects:%s" % (self.name) # # def save_whitelist(self): # for redirect_url in self.whitelist: # r.sadd("%s:whitelist" % self.redis_slug, redirect_url) # # def save_project(self): # r.hset(self.redis_slug, "exists", "true") # r.sadd(self.index_slug, self.name) # # def save(self): # self.save_whitelist() # self.save_project() # # def delete(self): # r.delete(self.redis_slug) # r.delete("%s:whitelist" % self.redis_slug) # r.srem(self.index_slug, self.name) # # def exists(self): # return r.hget(self.redis_slug, "exists") == "true" # # def get_whitelist(self): # return r.smembers("%s:whitelist" % self.redis_slug) . Output only the next line.
obj = RedisRedirect(project=project, slug=slug)
Based on the snippet: <|code_start|> sensitive_dataset_present = sensitive_group_dataset is not None nonsensitive_dataset_present = nonsensitive_group_dataset is not None # Case where min_diff_dataset is set and the others are not. set_to_use_min_diff_dataset = ( min_diff_dataset_present and not (sensitive_dataset_present or nonsensitive_dataset_present)) # Case where sensitive_group_dataset and nonsensitive_group_dataset are both # set and min_diff_dataset is not. set_to_construct_min_diff_dataset = ((sensitive_dataset_present and nonsensitive_dataset_present) and not min_diff_dataset_present) if not (set_to_use_min_diff_dataset or set_to_construct_min_diff_dataset): raise ValueError( "Invalid arguments: You must either pass in only the `min_diff_dataset`" " (and leave `sensitive_group_dataset` and `nonsensitive_group_dataset`" " as None) or set both `sensitive_group_dataset` and " "`nonsensitive_group_dataset` (and leave `min_diff_dataset` as None), " "given: \n" "\n`sensitive_group_dataset`: {}" "\n`nonsensitive_group_dataset`: {}" "\n`min_diff_dataset`: {}".format(sensitive_group_dataset, nonsensitive_group_dataset, min_diff_dataset)) # First construct the min_diff_dataset if need be. if set_to_construct_min_diff_dataset: min_diff_dataset = build_min_diff_dataset(sensitive_group_dataset, nonsensitive_group_dataset) else: # validate min_diff_dataset since it was passed in. <|code_end|> , predict the immediate next line with the help of imports: import collections import tensorflow as tf from tensorflow_model_remediation.min_diff.keras.utils import structure_utils and context (classes, functions, sometimes code) from other files: # Path: tensorflow_model_remediation/min_diff/keras/utils/structure_utils.py # def _flatten_min_diff_structure(struct, run_validation=False): # def _pack_min_diff_sequence_as(struct, flat_sequence): # def _assert_same_min_diff_structure(struct1, struct2): # def _err_msg(specifics_template, use_dict_keys=False): # def _is_min_diff_element(element, element_type=None): # def validate_min_diff_structure(struct, # struct_name="struct", # element_type=None): . Output only the next line.
structure_utils.validate_min_diff_structure(
Given snippet: <|code_start|> # pyformat: disable """Laplacian kernel class. Arguments: kernel_length: Length (sometimes also called 'width') of the kernel. Defaults to `0.1`. This parameter essentially describes how far apart points can be and still affect each other. The choice for kernel length should be influenced by the average distance of inputs. The smaller the distance, the smaller the kernel length likely needs to be for best performance. In general, a good first guess is the standard deviation of your predictions. Note: A kernel length that is too large will result in losing most of the kernel's non-linearity making it much less effective. A kernel length that is too small will make the kernel highly sensitive to input noise potentially leading to unstable results. **kwargs: Named parameters that will be passed directly to the base class' `__init__` function. See [paper](https://arxiv.org/abs/1910.11779) for reference on how it can be used in MinDiff. """ # pyformat: enable def __init__(self, kernel_length: complex = 0.1, **kwargs): super(LaplacianKernel, self).__init__(**kwargs) self.kernel_length = kernel_length <|code_end|> , continue by predicting the next line. Consider current file imports: import tensorflow as tf from tensorflow_model_remediation.common import types from tensorflow_model_remediation.min_diff.losses.kernels import base_kernel and context: # Path: tensorflow_model_remediation/common/types.py # # Path: tensorflow_model_remediation/min_diff/losses/kernels/base_kernel.py # class MinDiffKernel(abc.ABC): # def __init__(self, tile_input: bool = True): # def __call__(self, # x: types.TensorType, # y: Optional[types.TensorType] = None) -> types.TensorType: # def call(self, x: types.TensorType, y: types.TensorType): # def get_config(self): # def from_config(cls, config): which might include code, classes, or functions. Output only the next line.
def call(self, x: types.TensorType, y: types.TensorType) -> types.TensorType:
Continue the code snippet: <|code_start|># coding=utf-8 # Copyright 2022 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """Test base_kernel module.""" class MinDiffKernelTest(tf.test.TestCase): def testAbstract(self): with self.assertRaisesRegex(TypeError, 'instantiate abstract class MinDiffKernel'): <|code_end|> . Use current file imports: import tensorflow as tf from tensorflow_model_remediation.min_diff.losses.kernels import base_kernel and context (classes, functions, or code) from other files: # Path: tensorflow_model_remediation/min_diff/losses/kernels/base_kernel.py # class MinDiffKernel(abc.ABC): # def __init__(self, tile_input: bool = True): # def __call__(self, # x: types.TensorType, # y: Optional[types.TensorType] = None) -> types.TensorType: # def call(self, x: types.TensorType, y: types.TensorType): # def get_config(self): # def from_config(cls, config): . Output only the next line.
base_kernel.MinDiffKernel()
Continue the code snippet: <|code_start|> self.assertIsInstance(kernel, gaussian_kernel.GaussianKernel) kernel = utils._get_kernel('gauss_kernel') self.assertIsInstance(kernel, gaussian_kernel.GaussianKernel) kernel = utils._get_kernel('gaussian') self.assertIsInstance(kernel, gaussian_kernel.GaussianKernel) kernel = utils._get_kernel('gaussian_kernel') self.assertIsInstance(kernel, gaussian_kernel.GaussianKernel) kernel_length = 3 kernel = utils._get_kernel(gaussian_kernel.GaussianKernel(kernel_length)) self.assertIsInstance(kernel, gaussian_kernel.GaussianKernel) self.assertEqual(kernel.kernel_length, kernel_length) def testForLaplacianKernel(self): kernel = utils._get_kernel('laplace') self.assertIsInstance(kernel, laplacian_kernel.LaplacianKernel) kernel = utils._get_kernel('laplace_Kernel') self.assertIsInstance(kernel, laplacian_kernel.LaplacianKernel) kernel = utils._get_kernel('laplacian') self.assertIsInstance(kernel, laplacian_kernel.LaplacianKernel) kernel = utils._get_kernel('laplacian_kernel') self.assertIsInstance(kernel, laplacian_kernel.LaplacianKernel) kernel = utils._get_kernel(laplacian_kernel.LaplacianKernel()) self.assertIsInstance(kernel, laplacian_kernel.LaplacianKernel) kernel_length = 3 kernel = utils._get_kernel(laplacian_kernel.LaplacianKernel(kernel_length)) self.assertIsInstance(kernel, laplacian_kernel.LaplacianKernel) self.assertEqual(kernel.kernel_length, kernel_length) def testForCustomKernel(self): <|code_end|> . Use current file imports: import tensorflow as tf from tensorflow_model_remediation.min_diff.losses.kernels import base_kernel from tensorflow_model_remediation.min_diff.losses.kernels import gaussian_kernel from tensorflow_model_remediation.min_diff.losses.kernels import kernel_utils as utils from tensorflow_model_remediation.min_diff.losses.kernels import laplacian_kernel and context (classes, functions, or code) from other files: # Path: tensorflow_model_remediation/min_diff/losses/kernels/base_kernel.py # class MinDiffKernel(abc.ABC): # def __init__(self, tile_input: bool = True): # def __call__(self, # x: types.TensorType, # y: Optional[types.TensorType] = None) -> types.TensorType: # def call(self, x: types.TensorType, y: types.TensorType): # def get_config(self): # def from_config(cls, config): # # Path: tensorflow_model_remediation/min_diff/losses/kernels/gaussian_kernel.py # class GaussianKernel(base_kernel.MinDiffKernel): # def __init__(self, kernel_length: complex = 0.1, **kwargs): # def call(self, x: types.TensorType, y: types.TensorType) -> types.TensorType: # def get_config(self): # # Path: tensorflow_model_remediation/min_diff/losses/kernels/kernel_utils.py # _STRING_TO_KERNEL_DICT = {} # def _register_kernel_names(kernel_class, names): # def _get_kernel(kernel: Union[base_kernel.MinDiffKernel, str], # kernel_var_name: str = 'kernel'): # # Path: tensorflow_model_remediation/min_diff/losses/kernels/laplacian_kernel.py # _EPSILON = 1.0e-8 # class LaplacianKernel(base_kernel.MinDiffKernel): # def __init__(self, kernel_length: complex = 0.1, **kwargs): # def call(self, x: types.TensorType, y: types.TensorType) -> types.TensorType: # def get_config(self): . Output only the next line.
class CustomKernel(base_kernel.MinDiffKernel):
Predict the next line for this snippet: <|code_start|># coding=utf-8 # Copyright 2022 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. """Test kernel_utils module.""" class GetMinDiffKernelTest(tf.test.TestCase): def testAcceptsNone(self): kernel = utils._get_kernel(None) self.assertIsNone(kernel) def testForGaussianKernel(self): kernel = utils._get_kernel('gauss') <|code_end|> with the help of current file imports: import tensorflow as tf from tensorflow_model_remediation.min_diff.losses.kernels import base_kernel from tensorflow_model_remediation.min_diff.losses.kernels import gaussian_kernel from tensorflow_model_remediation.min_diff.losses.kernels import kernel_utils as utils from tensorflow_model_remediation.min_diff.losses.kernels import laplacian_kernel and context from other files: # Path: tensorflow_model_remediation/min_diff/losses/kernels/base_kernel.py # class MinDiffKernel(abc.ABC): # def __init__(self, tile_input: bool = True): # def __call__(self, # x: types.TensorType, # y: Optional[types.TensorType] = None) -> types.TensorType: # def call(self, x: types.TensorType, y: types.TensorType): # def get_config(self): # def from_config(cls, config): # # Path: tensorflow_model_remediation/min_diff/losses/kernels/gaussian_kernel.py # class GaussianKernel(base_kernel.MinDiffKernel): # def __init__(self, kernel_length: complex = 0.1, **kwargs): # def call(self, x: types.TensorType, y: types.TensorType) -> types.TensorType: # def get_config(self): # # Path: tensorflow_model_remediation/min_diff/losses/kernels/kernel_utils.py # _STRING_TO_KERNEL_DICT = {} # def _register_kernel_names(kernel_class, names): # def _get_kernel(kernel: Union[base_kernel.MinDiffKernel, str], # kernel_var_name: str = 'kernel'): # # Path: tensorflow_model_remediation/min_diff/losses/kernels/laplacian_kernel.py # _EPSILON = 1.0e-8 # class LaplacianKernel(base_kernel.MinDiffKernel): # def __init__(self, kernel_length: complex = 0.1, **kwargs): # def call(self, x: types.TensorType, y: types.TensorType) -> types.TensorType: # def get_config(self): , which may contain function names, class names, or code. Output only the next line.
self.assertIsInstance(kernel, gaussian_kernel.GaussianKernel)
Given snippet: <|code_start|> """Test kernel_utils module.""" class GetMinDiffKernelTest(tf.test.TestCase): def testAcceptsNone(self): kernel = utils._get_kernel(None) self.assertIsNone(kernel) def testForGaussianKernel(self): kernel = utils._get_kernel('gauss') self.assertIsInstance(kernel, gaussian_kernel.GaussianKernel) kernel = utils._get_kernel('GauSs') # Strangely capitalized. self.assertIsInstance(kernel, gaussian_kernel.GaussianKernel) kernel = utils._get_kernel('gauss_kernel') self.assertIsInstance(kernel, gaussian_kernel.GaussianKernel) kernel = utils._get_kernel('gaussian') self.assertIsInstance(kernel, gaussian_kernel.GaussianKernel) kernel = utils._get_kernel('gaussian_kernel') self.assertIsInstance(kernel, gaussian_kernel.GaussianKernel) kernel_length = 3 kernel = utils._get_kernel(gaussian_kernel.GaussianKernel(kernel_length)) self.assertIsInstance(kernel, gaussian_kernel.GaussianKernel) self.assertEqual(kernel.kernel_length, kernel_length) def testForLaplacianKernel(self): kernel = utils._get_kernel('laplace') <|code_end|> , continue by predicting the next line. Consider current file imports: import tensorflow as tf from tensorflow_model_remediation.min_diff.losses.kernels import base_kernel from tensorflow_model_remediation.min_diff.losses.kernels import gaussian_kernel from tensorflow_model_remediation.min_diff.losses.kernels import kernel_utils as utils from tensorflow_model_remediation.min_diff.losses.kernels import laplacian_kernel and context: # Path: tensorflow_model_remediation/min_diff/losses/kernels/base_kernel.py # class MinDiffKernel(abc.ABC): # def __init__(self, tile_input: bool = True): # def __call__(self, # x: types.TensorType, # y: Optional[types.TensorType] = None) -> types.TensorType: # def call(self, x: types.TensorType, y: types.TensorType): # def get_config(self): # def from_config(cls, config): # # Path: tensorflow_model_remediation/min_diff/losses/kernels/gaussian_kernel.py # class GaussianKernel(base_kernel.MinDiffKernel): # def __init__(self, kernel_length: complex = 0.1, **kwargs): # def call(self, x: types.TensorType, y: types.TensorType) -> types.TensorType: # def get_config(self): # # Path: tensorflow_model_remediation/min_diff/losses/kernels/kernel_utils.py # _STRING_TO_KERNEL_DICT = {} # def _register_kernel_names(kernel_class, names): # def _get_kernel(kernel: Union[base_kernel.MinDiffKernel, str], # kernel_var_name: str = 'kernel'): # # Path: tensorflow_model_remediation/min_diff/losses/kernels/laplacian_kernel.py # _EPSILON = 1.0e-8 # class LaplacianKernel(base_kernel.MinDiffKernel): # def __init__(self, kernel_length: complex = 0.1, **kwargs): # def call(self, x: types.TensorType, y: types.TensorType) -> types.TensorType: # def get_config(self): which might include code, classes, or functions. Output only the next line.
self.assertIsInstance(kernel, laplacian_kernel.LaplacianKernel)
Here is a snippet: <|code_start|> with tf.GradientTape() as tape: tape.watch(variables) predictions = variables * 3 # arbitrary linear operation. loss_value = loss_fn(membership, predictions, sample_weights) gradients = tape.gradient(loss_value, variables) # Assert that gradient computations are non trivial and do not change based # on loss implementation. expected_gradients = [[-0.40014654], [-0.7467264], [0.39164954], [0.10974818], [0.08942482]] self.assertAllClose(expected_gradients, gradients) def testLaplacianGradientsAllZeroWeights(self): loss_fn = mmd_lib.MMDLoss("laplace", predictions_transform=tf.sigmoid) variables = tf.constant([[0.1], [0.3], [0.5], [0.7], [0.9]]) membership = tf.constant([[1.0], [0.0], [1.0], [0.0], [1.0]]) sample_weights = tf.constant([[0.0], [0.0], [0.0], [0.0], [0.0]]) with tf.GradientTape() as tape: tape.watch(variables) predictions = variables * 3 # arbitrary linear operation. loss_value = loss_fn(membership, predictions, sample_weights) gradients = tape.gradient(loss_value, variables) # Gradients should all be 0 for weights that are all 0. expected_gradients = [[0.0], [0.0], [0.0], [0.0], [0.0]] self.assertAllClose(expected_gradients, gradients) def testRaisesExpectedErrors(self): <|code_end|> . Write the next line using the current file imports: import tensorflow as tf from tensorflow_model_remediation.min_diff.losses import mmd_loss as mmd_lib from tensorflow_model_remediation.min_diff.losses.kernels import gaussian_kernel from tensorflow_model_remediation.min_diff.losses.kernels import laplacian_kernel and context from other files: # Path: tensorflow_model_remediation/min_diff/losses/mmd_loss.py # class MMDLoss(base_loss.MinDiffLoss): # def __init__(self, # kernel="gaussian", # predictions_transform=None, # name: Optional[str] = None, # enable_summary_histogram: Optional[bool] = True): # def _preprocess(self, # membership: types.TensorType, # predictions: types.TensorType, # sample_weight: Optional[types.TensorType] = None): # def _calculate_mean(self, predictions_kernel: types.TensorType, # normed_weights: types.TensorType, # pos_mask: types.TensorType, neg_mask): # def call(self, # membership: types.TensorType, # predictions: types.TensorType, # sample_weight: Optional[types.TensorType] = None): # def from_config(cls, config): # # Path: tensorflow_model_remediation/min_diff/losses/kernels/gaussian_kernel.py # class GaussianKernel(base_kernel.MinDiffKernel): # def __init__(self, kernel_length: complex = 0.1, **kwargs): # def call(self, x: types.TensorType, y: types.TensorType) -> types.TensorType: # def get_config(self): # # Path: tensorflow_model_remediation/min_diff/losses/kernels/laplacian_kernel.py # _EPSILON = 1.0e-8 # class LaplacianKernel(base_kernel.MinDiffKernel): # def __init__(self, kernel_length: complex = 0.1, **kwargs): # def call(self, x: types.TensorType, y: types.TensorType) -> types.TensorType: # def get_config(self): , which may include functions, classes, or code. Output only the next line.
kernel = gaussian_kernel.GaussianKernel()
Given the code snippet: <|code_start|> mmd_lib.MMDLoss(4) with self.assertRaisesRegex( TypeError, "predictions_kernel.*must be.*MinDiffKernel.*string.*lambda"): mmd_lib.MMDLoss(bad_kernel) def testSerialization(self): loss = mmd_lib.MMDLoss() serialized_loss = tf.keras.utils.serialize_keras_object(loss) deserialized_loss = tf.keras.utils.deserialize_keras_object(serialized_loss) self.assertIsInstance(deserialized_loss, mmd_lib.MMDLoss) self.assertIsNone(deserialized_loss.predictions_transform) self.assertIsInstance(deserialized_loss.predictions_kernel, gaussian_kernel.GaussianKernel) self.assertEqual(deserialized_loss.name, loss.name) def testSerializationWithTransformAndKernel(self): predictions_fn = lambda x: x * 5.1 # Arbitrary operation. loss = mmd_lib.MMDLoss( predictions_transform=predictions_fn, kernel="laplacian") serialized_loss = tf.keras.utils.serialize_keras_object(loss) deserialized_loss = tf.keras.utils.deserialize_keras_object(serialized_loss) self.assertIsInstance(deserialized_loss, mmd_lib.MMDLoss) val = 7 # Arbitrary value. self.assertEqual( deserialized_loss.predictions_transform(val), predictions_fn(val)) self.assertIsInstance(deserialized_loss.predictions_kernel, <|code_end|> , generate the next line using the imports in this file: import tensorflow as tf from tensorflow_model_remediation.min_diff.losses import mmd_loss as mmd_lib from tensorflow_model_remediation.min_diff.losses.kernels import gaussian_kernel from tensorflow_model_remediation.min_diff.losses.kernels import laplacian_kernel and context (functions, classes, or occasionally code) from other files: # Path: tensorflow_model_remediation/min_diff/losses/mmd_loss.py # class MMDLoss(base_loss.MinDiffLoss): # def __init__(self, # kernel="gaussian", # predictions_transform=None, # name: Optional[str] = None, # enable_summary_histogram: Optional[bool] = True): # def _preprocess(self, # membership: types.TensorType, # predictions: types.TensorType, # sample_weight: Optional[types.TensorType] = None): # def _calculate_mean(self, predictions_kernel: types.TensorType, # normed_weights: types.TensorType, # pos_mask: types.TensorType, neg_mask): # def call(self, # membership: types.TensorType, # predictions: types.TensorType, # sample_weight: Optional[types.TensorType] = None): # def from_config(cls, config): # # Path: tensorflow_model_remediation/min_diff/losses/kernels/gaussian_kernel.py # class GaussianKernel(base_kernel.MinDiffKernel): # def __init__(self, kernel_length: complex = 0.1, **kwargs): # def call(self, x: types.TensorType, y: types.TensorType) -> types.TensorType: # def get_config(self): # # Path: tensorflow_model_remediation/min_diff/losses/kernels/laplacian_kernel.py # _EPSILON = 1.0e-8 # class LaplacianKernel(base_kernel.MinDiffKernel): # def __init__(self, kernel_length: complex = 0.1, **kwargs): # def call(self, x: types.TensorType, y: types.TensorType) -> types.TensorType: # def get_config(self): . Output only the next line.
laplacian_kernel.LaplacianKernel)