Prompt:
Implement the Python class `OnnxFromTfGraph` described below.

Class description:
Functor that loads a TensorFlow graph and converts it to ONNX using the tf2onnx converter.

Method signatures and docstrings:
- def __init__(self, graph, opset=None, optimize=None): Converts a TensorFlow model into ONNX. Args: graph (Union[Tuple[tf.Graph, Sequence[str]], Callable() -> Tuple[tf.Graph, Sequence[str]]]): A tuple containing a TensorFlow graph and output names or a callable that returns one. opset (int): The ONNX opset to use during conversion. optimize (bool): Whether to use tf2onnx's graph optimization pass.
- def call_impl(self): Returns: onnx.ModelProto: The ONNX model.

Implement the Python class `OnnxFromTfGraph` described below.

Class description:
Functor that loads a TensorFlow graph and converts it to ONNX using the tf2onnx converter.

Method signatures and docstrings:
- def __init__(self, graph, opset=None, optimize=None): Converts a TensorFlow model into ONNX. Args: graph (Union[Tuple[tf.Graph, Sequence[str]], Callable() -> Tuple[tf.Graph, Sequence[str]]]): A tuple containing a TensorFlow graph and output names or a callable that returns one. opset (int): The ONNX opset to use during conversion. optimize (bool): Whether to use tf2onnx's graph optimization pass.
- def call_impl(self): Returns: onnx.ModelProto: The ONNX model.

<|skeleton|>
class OnnxFromTfGraph:
    """Functor that loads a TensorFlow graph and converts it to ONNX using the tf2onnx converter."""

    def __init__(self, graph, opset=None, optimize=None):
        """Converts a TensorFlow model into ONNX. Args: graph (Union[Tuple[tf.Graph, Sequence[str]], Callable() -> Tuple[tf.Graph, Sequence[str]]]): A tuple containing a TensorFlow graph and output names or a callable that returns one. opset (int): The ONNX opset to use during conversion. optimize (bool): Whether to use tf2onnx's graph optimization pass."""
        <|body_0|>

    def call_impl(self):
        """Returns: onnx.ModelProto: The ONNX model."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self._graph = graph
        self.opset = util.default(opset, 11)
        self.optimize = util.default(optimize, True)
<|end_body_0|>

<|body_start_1|>
        (graph, output_names), _ = util.invoke_if_callable(self._graph)
        input_names = list(tf_util.get_input_metadata(graph).keys())
        graphdef = graph.as_graph_def()
        if self.optimize:
            graphdef = tf2onnx.tfonnx.tf_optimize(input_names, output_names, graph.as_graph_def())
        with tf.Graph().as_default() as graph, tf.compat.v1.Session(graph=graph) as sess:
            tf.import_graph_def(graphdef, name='')
            onnx_graph = tf2onnx.tfonnx.process_tf_graph(graph, input_names=input_names, output_names=output_names, opset=self.opset)
            if self.optimize:
                onnx_graph = tf2onnx.optimizer.optimize_graph(onnx_graph)
            return onnx_graph.make_model('model')
<|end_body_1|>

Solution:
class OnnxFromTfGraph:
    """Functor that loads a TensorFlow graph and converts it to ONNX using the tf2onnx converter."""

    def __init__(self, graph, opset=None, optimize=None):
        """Converts a TensorFlow model into ONNX. Args: graph (Union[Tuple[tf.Graph, Sequence[str]], Callable() -> Tuple[tf.Graph, Sequence[str]]]): A tuple containing a TensorFlow graph and output names or a callable that returns one. opset (int): The ONNX opset to use during conversion. optimize (bool): Whether to use tf2onnx's graph optimization pass."""
        self._graph = graph
        self.opset = util.default(opset, 11)
        self.optimize = util.default(optimize, True)

    def call_impl(self):
        """Returns: onnx.ModelProto: The ONNX model."""
        (graph, output_names), _ = util.invoke_if_callable(self._graph)
        input_names = list(tf_util.get_input_metadata(graph).keys())
        graphdef = graph.as_graph_def()
        if self.optimize:
            graphdef = tf2onnx.tfonnx.tf_optimize(input_names, output_names, graph.as_graph_def())
        with tf.Graph().as_default() as graph, tf.compat.v1.Session(graph=graph) as sess:
            tf.import_graph_def(graphdef, name='')
            onnx_graph = tf2onnx.tfonnx.process_tf_graph(graph, input_names=input_names, output_names=output_names, opset=self.opset)
            if self.optimize:
                onnx_graph = tf2onnx.optimizer.optimize_graph(onnx_graph)
            return onnx_graph.make_model('model')


Prompt:
Implement the Python class `Preprocessor` described below.

Class description:
Implement the Preprocessor class.

Method signatures and docstrings:
- def __init__(self, scale=None, bias=None, rgb=None): Create a preprocessing object to handle image transformations required for network to run scale : float Scale factor applied to image after conversion to float bias : 3-element np.array Bias applied to image after scaling rgb : bool Set to true to convert 3 channel data to RGB (from BGR)
- def __call__(self, image, requiredWidth, requiredHeight): Run the required preprocessing steps on an input image image : np.ndarray containing the image data

Implement the Python class `Preprocessor` described below.

Class description:
Implement the Preprocessor class.

Method signatures and docstrings:
- def __init__(self, scale=None, bias=None, rgb=None): Create a preprocessing object to handle image transformations required for network to run scale : float Scale factor applied to image after conversion to float bias : 3-element np.array Bias applied to image after scaling rgb : bool Set to true to convert 3 channel data to RGB (from BGR)
- def __call__(self, image, requiredWidth, requiredHeight): Run the required preprocessing steps on an input image image : np.ndarray containing the image data

<|skeleton|>
class Preprocessor:

    def __init__(self, scale=None, bias=None, rgb=None):
        """Create a preprocessing object to handle image transformations required for network to run scale : float Scale factor applied to image after conversion to float bias : 3-element np.array Bias applied to image after scaling rgb : bool Set to true to convert 3 channel data to RGB (from BGR)"""
        <|body_0|>

    def __call__(self, image, requiredWidth, requiredHeight):
        """Run the required preprocessing steps on an input image image : np.ndarray containing the image data"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.scale = scale
        self.bias = bias
        self.rgb = rgb
<|end_body_0|>

<|body_start_1|>
        if image.shape[0] != requiredHeight or image.shape[1] != requiredWidth:
            image = cv2.resize(image, (requiredWidth, requiredHeight))
        if self.rgb:
            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        image = image.astype(np.float32)
        if self.scale is not None:
            image *= self.scale
        if self.bias is not None:
            image += self.bias
        return image
<|end_body_1|>

Solution:
class Preprocessor:
    def __init__(self, scale=None, bias=None, rgb=None):
        """Create a preprocessing object to handle image transformations required for network to run scale : float Scale factor applied to image after conversion to float bias : 3-element np.array Bias applied to image after scaling rgb : bool Set to true to convert 3 channel data to RGB (from BGR)"""
        self.scale = scale
        self.bias = bias
        self.rgb = rgb

    def __call__(self, image, requiredWidth, requiredHeight):
        """Run the required preprocessing steps on an input image image : np.ndarray containing the image data"""
        if image.shape[0] != requiredHeight or image.shape[1] != requiredWidth:
            image = cv2.resize(image, (requiredWidth, requiredHeight))
        if self.rgb:
            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        image = image.astype(np.float32)
        if self.scale is not None:
            image *= self.scale
        if self.bias is not None:
            image += self.bias
        return image


Prompt:
Implement the Python class `LAMBOptimizer_v2` described below.

Class description:
LAMB (Layer-wise Adaptive Moments optimizer for Batch training).

Method signatures and docstrings:
- def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, include_in_weight_decay=['r_s_bias', 'r_r_bias', 'r_w_bias'], exclude_from_layer_adaptation=None, name='LAMBOptimizer'): Constructs a LAMBOptimizer.
- def apply_gradients(self, grads_and_vars, global_step=None, name=None, learning_rate=None): See base class.
- def _do_use_weight_decay(self, param_name): Whether to use L2 weight decay for `param_name`.
- def _do_layer_adaptation(self, param_name): Whether to do layer-wise learning rate adaptation for `param_name`.
- def _get_variable_name(self, param_name): Get the variable name from the tensor name.

Implement the Python class `LAMBOptimizer_v2` described below.

Class description:
LAMB (Layer-wise Adaptive Moments optimizer for Batch training).

Method signatures and docstrings:
- def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, include_in_weight_decay=['r_s_bias', 'r_r_bias', 'r_w_bias'], exclude_from_layer_adaptation=None, name='LAMBOptimizer'): Constructs a LAMBOptimizer.
- def apply_gradients(self, grads_and_vars, global_step=None, name=None, learning_rate=None): See base class.
- def _do_use_weight_decay(self, param_name): Whether to use L2 weight decay for `param_name`.
- def _do_layer_adaptation(self, param_name): Whether to do layer-wise learning rate adaptation for `param_name`.
- def _get_variable_name(self, param_name): Get the variable name from the tensor name.

<|skeleton|>
class LAMBOptimizer_v2:
    """LAMB (Layer-wise Adaptive Moments optimizer for Batch training)."""

    def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, include_in_weight_decay=['r_s_bias', 'r_r_bias', 'r_w_bias'], exclude_from_layer_adaptation=None, name='LAMBOptimizer'):
        """Constructs a LAMBOptimizer."""
        <|body_0|>

    def apply_gradients(self, grads_and_vars, global_step=None, name=None, learning_rate=None):
        """See base class."""
        <|body_1|>

    def _do_use_weight_decay(self, param_name):
        """Whether to use L2 weight decay for `param_name`."""
        <|body_2|>

    def _do_layer_adaptation(self, param_name):
        """Whether to do layer-wise learning rate adaptation for `param_name`."""
        <|body_3|>

    def _get_variable_name(self, param_name):
        """Get the variable name from the tensor name."""
        <|body_4|>

<|end_skeleton|>

<|body_start_0|>
        super(LAMBOptimizer_v2, self).__init__(False, name)
        self.learning_rate = learning_rate
        self.weight_decay_rate = weight_decay_rate
        self.beta_1 = beta_1
        self.beta_2 = beta_2
        self.epsilon = epsilon
        self.exclude_from_weight_decay = exclude_from_weight_decay
        self.include_in_weight_decay = include_in_weight_decay
        if exclude_from_layer_adaptation:
            self.exclude_from_layer_adaptation = exclude_from_layer_adaptation
        else:
            self.exclude_from_layer_adaptation = exclude_from_weight_decay
<|end_body_0|>

<|body_start_1|>
        assignments = []
        if learning_rate is None:
            learning_rate = self.learning_rate
            tf.logging.info('***** use default learning rate ***** ', learning_rate)
        else:
            tf.logging.info('***** use provided learning rate ***** ', learning_rate)
        for grad, param in grads_and_vars:
            if grad is None or param is None:
                continue
            param_name = self._get_variable_name(param.name)
            tf.logging.info('***** apply gradients parameter name ***** %s', param_name)
            tf.logging.info('***** param: %s learning rate: %s ***** ', param_name, str(learning_rate))
            m = tf.get_variable(name=param_name + '/adam_m', shape=param.shape.as_list(), dtype=tf.float32, trainable=False, initializer=tf.zeros_initializer())
            v = tf.get_variable(name=param_name + '/adam_v', shape=param.shape.as_list(), dtype=tf.float32, trainable=False, initializer=tf.zeros_initializer())
            next_m = tf.multiply(self.beta_1, m) + tf.multiply(1.0 - self.beta_1, grad)
            next_v = tf.multiply(self.beta_2, v) + tf.multiply(1.0 - self.beta_2, tf.square(grad))
            update = next_m / (tf.sqrt(next_v) + self.epsilon)
            if self._do_use_weight_decay(param_name):
                update += self.weight_decay_rate * param
            ratio = 1.0
            if self._do_layer_adaptation(param_name):
                w_norm = linalg_ops.norm(param, ord=2)
                g_norm = linalg_ops.norm(update, ord=2)
                ratio = array_ops.where(math_ops.greater(w_norm, 0), array_ops.where(math_ops.greater(g_norm, 0), w_norm / g_norm, 1.0), 1.0)
            update_with_lr = ratio * learning_rate * update
            next_param = param - update_with_lr
            assignments.extend([param.assign(next_param), m.assign(next_m), v.assign(next_v)])
        return tf.group(*assignments, name=name)
<|end_body_1|>

<|body_start_2|>
        if not self.weight_decay_rate:
            return False
        if self.include_in_weight_decay:
            for r in self.include_in_weight_decay:
                if re.search(r, param_name) is not None:
                    tf.logging.info('Include %s in weight decay', param_name)
                    return True
        if self.exclude_from_weight_decay:
            for r in self.exclude_from_weight_decay:
                if re.search(r, param_name) is not None:
                    tf.logging.info('Adam WD excludes %s', param_name)
                    return False
        return True
<|end_body_2|>

<|body_start_3|>
        if self.exclude_from_layer_adaptation:
            for r in self.exclude_from_layer_adaptation:
                if re.search(r, param_name) is not None:
                    return False
        return True
<|end_body_3|>

<|body_start_4|>
        m = re.match('^(.*):\\d+$', param_name)
        if m is not None:
            param_name = m.group(1)
        return param_name
<|end_body_4|>

Solution:
class LAMBOptimizer_v2:
    """LAMB (Layer-wise Adaptive Moments optimizer for Batch training)."""

    def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, include_in_weight_decay=['r_s_bias', 'r_r_bias', 'r_w_bias'], exclude_from_layer_adaptation=None, name='LAMBOptimizer'):
        """Constructs a LAMBOptimizer."""
        super(LAMBOptimizer_v2, self).__init__(False, name)
        self.learning_rate = learning_rate
        self.weight_decay_rate = weight_decay_rate
        self.beta_1 = beta_1
        self.beta_2 = beta_2
        self.epsilon = epsilon
        self.exclude_from_weight_decay = exclude_from_weight_decay
        self.include_in_weight_decay = include_in_weight_decay
        if exclude_from_layer_adaptation:
            self.exclude_from_layer_adaptation = exclude_from_layer_adaptation
        else:
            self.exclude_from_layer_adaptation = exclude_from_weight_decay

    def apply_gradients(self, grads_and_vars, global_step=None, name=None, learning_rate=None):
        """See base class."""
        assignments = []
        if learning_rate is None:
            learning_rate = self.learning_rate
            tf.logging.info('***** use default learning rate ***** ', learning_rate)
        else:
            tf.logging.info('***** use provided learning rate ***** ', learning_rate)
        for grad, param in grads_and_vars:
            if grad is None or param is None:
                continue
            param_name = self._get_variable_name(param.name)
            tf.logging.info('***** apply gradients parameter name ***** %s', param_name)
            tf.logging.info('***** param: %s learning rate: %s ***** ', param_name, str(learning_rate))
            m = tf.get_variable(name=param_name + '/adam_m', shape=param.shape.as_list(), dtype=tf.float32, trainable=False, initializer=tf.zeros_initializer())
            v = tf.get_variable(name=param_name + '/adam_v', shape=param.shape.as_list(), dtype=tf.float32, trainable=False, initializer=tf.zeros_initializer())
            next_m = tf.multiply(self.beta_1, m) + tf.multiply(1.0 - self.beta_1, grad)
            next_v = tf.multiply(self.beta_2, v) + tf.multiply(1.0 - self.beta_2, tf.square(grad))
            update = next_m / (tf.sqrt(next_v) + self.epsilon)
            if self._do_use_weight_decay(param_name):
                update += self.weight_decay_rate * param
            ratio = 1.0
            if self._do_layer_adaptation(param_name):
                w_norm = linalg_ops.norm(param, ord=2)
                g_norm = linalg_ops.norm(update, ord=2)
                ratio = array_ops.where(math_ops.greater(w_norm, 0), array_ops.where(math_ops.greater(g_norm, 0), w_norm / g_norm, 1.0), 1.0)
            update_with_lr = ratio * learning_rate * update
            next_param = param - update_with_lr
            assignments.extend([param.assign(next_param), m.assign(next_m), v.assign(next_v)])
        return tf.group(*assignments, name=name)

    def _do_use_weight_decay(self, param_name):
        """Whether to use L2 weight decay for `param_name`."""
        if not self.weight_decay_rate:
            return False
        if self.include_in_weight_decay:
            for r in self.include_in_weight_decay:
                if re.search(r, param_name) is not None:
                    tf.logging.info('Include %s in weight decay', param_name)
                    return True
        if self.exclude_from_weight_decay:
            for r in self.exclude_from_weight_decay:
                if re.search(r, param_name) is not None:
                    tf.logging.info('Adam WD excludes %s', param_name)
                    return False
        return True

    def _do_layer_adaptation(self, param_name):
        """Whether to do layer-wise learning rate adaptation for `param_name`."""
        if self.exclude_from_layer_adaptation:
            for r in self.exclude_from_layer_adaptation:
                if re.search(r, param_name) is not None:
                    return False
        return True

    def _get_variable_name(self, param_name):
        """Get the variable name from the tensor name."""
        m = re.match('^(.*):\\d+$', param_name)
        if m is not None:
            param_name = m.group(1)
        return param_name


predict

Prompt:
Implement the Python class `MoE_list` described below.

Class description:
This class contains a list of MoE models and deals with them easily. This might be useful for multidimensional regression where each target dimension is fitted separately by a MoE model. All models must have same input space dimensionality; they shall have same gating function model but might have different experts number. It takes care also of boring part of saving model to file.

Method signatures and docstrings:
- def __init__(self, K, folder=None, D=1, N_exp_list=10): Initialise class. If folder is given, model is loaded from folder. Otherwise a softmax gating function model is built with the required dimensionality and number of experts. Input: K number of MoE models in MoE_list folder folder at which the model should be loaded from. (If None, nothing is loaded) The following not required if folder is None: D dimensionality of input space N_exp_list list holding the number of expert to use for each model (if int all N_exp are the same)
- def load(self, folder, load_function=None): Load models from file. Folder must contain files of the following type: exp_# gat_# where # is in {0,..,K-1} Each model is the built from files given. Input: folder path to folder in which model is stored load_function function that shall be used to load the gating model. (if None default softmax is used)
- def save(self, folder): Saves all the models to the same folder. Files are: exp_# gat_# where # is in {0,..,K-1}. Input: folder name of the folder to save files to
- def fit(self, X_train, y_train, args_list=None): Fit for the k-th model the regression X -> y[k] k = 0,1,.. K. Each fit can have its own arguments [N_iter=None, threshold = 1e-2, args= [], verbose = False] Input: X_train (N,D) training data y_train (N,K) training targets args_list [] list of tuples of arguments to be given to each call of function MoE_model.fit Each tuple must be of form (N_iter, threshold, args, verbose) If only one tuple is given, it is used for each fitting procedure
- def models(self, k_list=None): Returns the MoE model(s). Input: k_list [] index(indices) of the model to be returned (if None all models are returned) Output: models [] list of models to be returned
- def predict(self, X): Makes predictions for all the models. Input: X (N,D) points to make predictions at Ouput: y (N,K) prediction for each MoE model

Implement the Python class `MoE_list` described below.

Class description:
This class contains a list of MoE models and deals with them easily. This might be useful for multidimensional regression where each target dimension is fitted separately by a MoE model. All models must have same input space dimensionality; they shall have same gating function model but might have different experts number. It takes care also of boring part of saving model to file.

Method signatures and docstrings:
- def __init__(self, K, folder=None, D=1, N_exp_list=10): Initialise class. If folder is given, model is loaded from folder. Otherwise a softmax gating function model is built with the required dimensionality and number of experts. Input: K number of MoE models in MoE_list folder folder at which the model should be loaded from. (If None, nothing is loaded) The following not required if folder is None: D dimensionality of input space N_exp_list list holding the number of expert to use for each model (if int all N_exp are the same)
- def load(self, folder, load_function=None): Load models from file. Folder must contain files of the following type: exp_# gat_# where # is in {0,..,K-1} Each model is the built from files given. Input: folder path to folder in which model is stored load_function function that shall be used to load the gating model. (if None default softmax is used)
- def save(self, folder): Saves all the models to the same folder. Files are: exp_# gat_# where # is in {0,..,K-1}. Input: folder name of the folder to save files to
- def fit(self, X_train, y_train, args_list=None): Fit for the k-th model the regression X -> y[k] k = 0,1,.. K. Each fit can have its own arguments [N_iter=None, threshold = 1e-2, args= [], verbose = False] Input: X_train (N,D) training data y_train (N,K) training targets args_list [] list of tuples of arguments to be given to each call of function MoE_model.fit Each tuple must be of form (N_iter, threshold, args, verbose) If only one tuple is given, it is used for each fitting procedure
- def models(self, k_list=None): Returns the MoE model(s). Input: k_list [] index(indices) of the model to be returned (if None all models are returned) Output: models [] list of models to be returned
- def predict(self, X): Makes predictions for all the models. Input: X (N,D) points to make predictions at Ouput: y (N,K) prediction for each MoE model

<|skeleton|>
class MoE_list:
    """This class contains a list of MoE models and deals with them easily. This might be useful for multidimensional regression where each target dimension is fitted separately by a MoE model. All models must have same input space dimensionality; they shall have same gating function model but might have different experts number. It takes care also of boring part of saving model to file."""

    def __init__(self, K, folder=None, D=1, N_exp_list=10):
        """Initialise class. If folder is given, model is loaded from folder. Otherwise a softmax gating function model is built with the required dimensionality and number of experts. Input: K number of MoE models in MoE_list folder folder at which the model should be loaded from. (If None, nothing is loaded) The following not required if folder is None: D dimensionality of input space N_exp_list list holding the number of expert to use for each model (if int all N_exp are the same)"""
        <|body_0|>

    def load(self, folder, load_function=None):
        """Load models from file. Folder must contain files of the following type: exp_# gat_# where # is in {0,..,K-1} Each model is the built from files given. Input: folder path to folder in which model is stored load_function function that shall be used to load the gating model. (if None default softmax is used)"""
        <|body_1|>

    def save(self, folder):
        """Saves all the models to the same folder. Files are: exp_# gat_# where # is in {0,..,K-1}. Input: folder name of the folder to save files to"""
        <|body_2|>

    def fit(self, X_train, y_train, args_list=None):
        """Fit for the k-th model the regression X -> y[k] k = 0,1,.. K. Each fit can have its own arguments [N_iter=None, threshold = 1e-2, args= [], verbose = False] Input: X_train (N,D) training data y_train (N,K) training targets args_list [] list of tuples of arguments to be given to each call of function MoE_model.fit Each tuple must be of form (N_iter, threshold, args, verbose) If only one tuple is given, it is used for each fitting procedure"""
        <|body_3|>

    def models(self, k_list=None):
        """Returns the MoE model(s). Input: k_list [] index(indices) of the model to be returned (if None all models are returned) Output: models [] list of models to be returned"""
        <|body_4|>

    def predict(self, X):
        """Makes predictions for all the models. Input: X (N,D) points to make predictions at Ouput: y (N,K) prediction for each MoE model"""
        <|body_5|>

<|end_skeleton|>

<|body_start_0|>
        self.K = K
        if folder is not None:
            self.MoE_list = [None for k in range(K)]
            self.load(folder)
        else:
            if type(N_exp_list) is int:
                N_exp_list = [N_exp_list for k in range(self.K)]
            if len(N_exp_list) != self.K:
                raise TypeError("Lenght of number of expters list doesn't match number of models!")
            self.D = D
            for k in range(self.K):
                self.MoE_list.append(MoE_model(self.D, N_exp_list[k]))
        return
<|end_body_0|>

<|body_start_1|>
        file_list = os.listdir(folder)
        D_list = []
        for k in range(self.K):
            if 'gat_' + str(k) not in file_list or 'exp_' + str(k) not in file_list:
                raise RuntimeError("Couldn't find proper files for MoE model " + str(k))
            self.MoE_list[k] = MoE_model(self.D, 1)
            self.MoE_list[k].load(folder + 'exp_' + str(k), folder + 'gat_' + str(k), load_function=load_function)
            D, N_exp = MoE_list[k].get_iperparams()
            D_list.append(D)
            self.N_exp_list[k] = N_exp
        assert len(set(D_list)) == 1
        self.D = D_list[0]
        return
<|end_body_1|>

<|body_start_2|>
        for k in range(self.K):
            self.MoE_list[k].save(folder + 'exp_' + str(k), folder + 'gat_' + str(k))
        return
<|end_body_2|>

<|body_start_3|>
        if type(arg_list) is tuple:
            arg_list = [arg_list for k in range(self.K)]
        assert y_train.shape[1] == self.K
        assert X_train.shape[0] == y_train.shape[0]
        assert X.shape[1] == self.D
        for k in range(self.K):
            print('Fitting component ', k)
            y_train = PCA_train_ph[:, k]
            MoE_models[k].fit(train_theta, y_train, *arg_list[k])
        return
<|end_body_3|>

<|body_start_4|>
        if k_list is None:
            k_list = range(self.K)
        return self.MoE_list[k]
<|end_body_4|>

<|body_start_5|>
        assert X.shape[1] == self.D
        y = np.zeros((X_test.shape[0], self.K))
        for k in range(self.K):
            y[:, k] = self.MoE_list[k].predict(X)
        return y
<|end_body_5|>

Solution:
class MoE_list:
    """This class contains a list of MoE models and deals with them easily. This might be useful for multidimensional regression where each target dimension is fitted separately by a MoE model. All models must have same input space dimensionality; they shall have same gating function model but might have different experts number. It takes care also of boring part of saving model to file."""

    def __init__(self, K, folder=None, D=1, N_exp_list=10):
        """Initialise class. If folder is given, model is loaded from folder. Otherwise a softmax gating function model is built with the required dimensionality and number of experts. Input: K number of MoE models in MoE_list folder folder at which the model should be loaded from. (If None, nothing is loaded) The following not required if folder is None: D dimensionality of input space N_exp_list list holding the number of expert to use for each model (if int all N_exp are the same)"""
        self.K = K
        if folder is not None:
            self.MoE_list = [None for k in range(K)]
            self.load(folder)
        else:
            if type(N_exp_list) is int:
                N_exp_list = [N_exp_list for k in range(self.K)]
            if len(N_exp_list) != self.K:
                raise TypeError("Lenght of number of expters list doesn't match number of models!")
            self.D = D
            for k in range(self.K):
                self.MoE_list.append(MoE_model(self.D, N_exp_list[k]))
        return

    def load(self, folder, load_function=None):
        """Load models from file. Folder must contain files of the following type: exp_# gat_# where # is in {0,..,K-1} Each model is the built from files given. Input: folder path to folder in which model is stored load_function function that shall be used to load the gating model. (if None default softmax is used)"""
        file_list = os.listdir(folder)
        D_list = []
        for k in range(self.K):
            if 'gat_' + str(k) not in file_list or 'exp_' + str(k) not in file_list:
                raise RuntimeError("Couldn't find proper files for MoE model " + str(k))
            self.MoE_list[k] = MoE_model(self.D, 1)
            self.MoE_list[k].load(folder + 'exp_' + str(k), folder + 'gat_' + str(k), load_function=load_function)
            D, N_exp = MoE_list[k].get_iperparams()
            D_list.append(D)
            self.N_exp_list[k] = N_exp
        assert len(set(D_list)) == 1
        self.D = D_list[0]
        return

    def save(self, folder):
        """Saves all the models to the same folder. Files are: exp_# gat_# where # is in {0,..,K-1}. Input: folder name of the folder to save files to"""
        for k in range(self.K):
            self.MoE_list[k].save(folder + 'exp_' + str(k), folder + 'gat_' + str(k))
        return

    def fit(self, X_train, y_train, args_list=None):
        """Fit for the k-th model the regression X -> y[k] k = 0,1,.. K. Each fit can have its own arguments [N_iter=None, threshold = 1e-2, args= [], verbose = False] Input: X_train (N,D) training data y_train (N,K) training targets args_list [] list of tuples of arguments to be given to each call of function MoE_model.fit Each tuple must be of form (N_iter, threshold, args, verbose) If only one tuple is given, it is used for each fitting procedure"""
        if type(arg_list) is tuple:
            arg_list = [arg_list for k in range(self.K)]
        assert y_train.shape[1] == self.K
        assert X_train.shape[0] == y_train.shape[0]
        assert X.shape[1] == self.D
        for k in range(self.K):
            print('Fitting component ', k)
            y_train = PCA_train_ph[:, k]
            MoE_models[k].fit(train_theta, y_train, *arg_list[k])
        return

    def models(self, k_list=None):
        """Returns the MoE model(s). Input: k_list [] index(indices) of the model to be returned (if None all models are returned) Output: models [] list of models to be returned"""
        if k_list is None:
            k_list = range(self.K)
        return self.MoE_list[k]

    def predict(self, X):
        """Makes predictions for all the models. Input: X (N,D) points to make predictions at Ouput: y (N,K) prediction for each MoE model"""
        assert X.shape[1] == self.D
        y = np.zeros((X_test.shape[0], self.K))
        for k in range(self.K):
            y[:, k] = self.MoE_list[k].predict(X)
        return y


simplify

Prompt:
Implement the Python class `PotentialModelBase` described below.

Class description:
Abstract base class for scalar potential models using (B, ε).

Method signatures and docstrings:
- def __init__(self): Constructor. Sets up the independent variables B, ε, and the deviatoric strain e = e(ε).
- def dφdq(self, qs, strip): Differentiate the potential ϕ w.r.t. given independent variables. self.indepvars.keys() contains all valid independent variables. If ϕ is a layer cake of SymPy applied functions, the chain rule is applied automatically. Parameters: qs: tuple of str Names of independent variables to differentiate with regard to. Use an empty tuple to skip differentiation and get just ϕ itself. strip: bool See return value for definitions of ``sym`` and ``expr``. If True, pass expr through ``symutil.strip_function_arguments()`` before returning it, replacing applied functions with bare symbols. If False, return expr as-is. sym is always keyify()'d to make it a definition key. Example: m = Model() m.dϕdq(("Bx",
- def dφdqs(self, jacobian=True, hessian=True): Return 1st and 2nd derivatives of ϕ w.r.t. all independent variables. Convenience function. This is essentially a loop over ``dϕdq()``, to differentiate self.ϕ symbolically. If ϕ is a layer cake of SymPy applied functions, it will be differentiated only formally (using the chain rule), without inserting any definitions. This is convenient, since by keeping the functional relations intact we avoid generating (possibly lengthy) common subexpressions. (stage2 takes care of actually calling the functions to obtain the necessary values at each step of evaluating the RHS.) Parameters: jacobian: bool Compute first derivatives. hessian: bool Compute second derivatives. Returns: dict(sy.Symbol -> sy.
- def simplify(self, expr): Simplify expr. Specifically geared to optimize expressions treated by this class.

Implement the Python class `PotentialModelBase` described below.

Class description:
Abstract base class for scalar potential models using (B, ε).

Method signatures and docstrings:
- def __init__(self): Constructor. Sets up the independent variables B, ε, and the deviatoric strain e = e(ε).
- def dφdq(self, qs, strip): Differentiate the potential ϕ w.r.t. given independent variables. self.indepvars.keys() contains all valid independent variables. If ϕ is a layer cake of SymPy applied functions, the chain rule is applied automatically. Parameters: qs: tuple of str Names of independent variables to differentiate with regard to. Use an empty tuple to skip differentiation and get just ϕ itself. strip: bool See return value for definitions of ``sym`` and ``expr``. If True, pass expr through ``symutil.strip_function_arguments()`` before returning it, replacing applied functions with bare symbols. If False, return expr as-is. sym is always keyify()'d to make it a definition key. Example: m = Model() m.dϕdq(("Bx",
- def dφdqs(self, jacobian=True, hessian=True): Return 1st and 2nd derivatives of ϕ w.r.t. all independent variables. Convenience function. This is essentially a loop over ``dϕdq()``, to differentiate self.ϕ symbolically. If ϕ is a layer cake of SymPy applied functions, it will be differentiated only formally (using the chain rule), without inserting any definitions. This is convenient, since by keeping the functional relations intact we avoid generating (possibly lengthy) common subexpressions. (stage2 takes care of actually calling the functions to obtain the necessary values at each step of evaluating the RHS.) Parameters: jacobian: bool Compute first derivatives. hessian: bool Compute second derivatives. Returns: dict(sy.Symbol -> sy.
- def simplify(self, expr): Simplify expr. Specifically geared to optimize expressions treated by this class.

<|skeleton|>
class PotentialModelBase:
    """Abstract base class for scalar potential models using (B, ε)."""

    def __init__(self):
        """Constructor. Sets up the independent variables B, ε, and the deviatoric strain e = e(ε)."""
        <|body_0|>

    def dφdq(self, qs, strip):
        """Differentiate the potential ϕ w.r.t. given independent variables. self.indepvars.keys() contains all valid independent variables. If ϕ is a layer cake of SymPy applied functions, the chain rule is applied automatically. Parameters: qs: tuple of str Names of independent variables to differentiate with regard to. Use an empty tuple to skip differentiation and get just ϕ itself. strip: bool See return value for definitions of ``sym`` and ``expr``. If True, pass expr through ``symutil.strip_function_arguments()`` before returning it, replacing applied functions with bare symbols. If False, return expr as-is. sym is always keyify()'d to make it a definition key. Example: m = Model() m.dϕdq(("Bx","""
        <|body_1|>

    def dφdqs(self, jacobian=True, hessian=True):
        """Return 1st and 2nd derivatives of ϕ w.r.t. all independent variables. Convenience function. This is essentially a loop over ``dϕdq()``, to differentiate self.ϕ symbolically. If ϕ is a layer cake of SymPy applied functions, it will be differentiated only formally (using the chain rule), without inserting any definitions. This is convenient, since by keeping the functional relations intact we avoid generating (possibly lengthy) common subexpressions. (stage2 takes care of actually calling the functions to obtain the necessary values at each step of evaluating the RHS.) Parameters: jacobian: bool Compute first derivatives. hessian: bool Compute second derivatives. Returns: dict(sy.Symbol -> sy."""
        <|body_2|>

    def simplify(self, expr):
        """Simplify expr. Specifically geared to optimize expressions treated by this class."""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        self.Bs = sy.symbols('Bx, By, Bz')
        self.εs = sy.symbols('εxx, εyy, εzz, εyz, εzx, εxy')
        self.indepvars = {s.name: s for s in self.Bs + self.εs}
        self.es = tuple((symutil.make_function(name, *self.εs) for name in ('exx', 'eyy', 'ezz', 'eyz', 'ezx', 'exy')))
<|end_body_0|>

<|body_start_1|>
        invalid_inputs = [q for q in qs if q not in self.indepvars]
        if len(invalid_inputs):
            raise ValueError('Variable(s) {invalid} not in self.indepvars'.format(invalid=', '.join(invalid_inputs)))
        sym = symutil.make_function('ϕ', *self.indepvars.values())
        expr = self.φ
        for varname in qs:
            q = self.indepvars[varname]
            sym = sy.diff(sym, q, evaluate=False)
            expr = sy.diff(expr, q)
        sym = self.keyify(sym)
        if len(qs):
            expr = symutil.apply_substitutions_in(expr)
        if strip:
            expr = symutil.strip_function_arguments(expr)
        assert sym != 0, 'BUG in dϕdq(): symbol for function name is 0'
        return (sym, expr)
<|end_body_1|>

<|body_start_2|>
        ivars = sorted(self.indepvars.keys())
        out = {}
        allqs = []
        if jacobian:
            allqs.extend(((var,) for var in ivars))
        if hessian:
            allqs.extend(combinations_with_replacement(ivars, 2))
        for i, qs in enumerate(allqs, start=1):
            print('model: {label} ({iteration:d}/{total:d}) forming expression for {name}'.format(label=self.label, iteration=i, total=len(allqs), name=util.name_derivative('ϕ', qs)))
            sym, expr = self.dφdq(qs, strip=False)
            out[sym] = expr
        return out
<|end_body_2|>

<|body_start_3|>
        expr = recursive_collect(sy.together(sy.expand(expr)))
        expr = recursive_collect(expr, syms=self.Bs)
        expr = symutil.collect_const_in(expr)
        return expr
<|end_body_3|>

Solution:
class PotentialModelBase:
    """Abstract base class for scalar potential models using (B, ε)."""

    def __init__(self):
        """Constructor. Sets up the independent variables B, ε, and the deviatoric strain e = e(ε)."""
        self.Bs = sy.symbols('Bx, By, Bz')
        self.εs = sy.symbols('εxx, εyy, εzz, εyz, εzx, εxy')
        self.indepvars = {s.name: s for s in self.Bs + self.εs}
        self.es = tuple((symutil.make_function(name, *self.εs) for name in ('exx', 'eyy', 'ezz', 'eyz', 'ezx', 'exy')))

    def dφdq(self, qs, strip):
        """Differentiate the potential ϕ w.r.t. given independent variables. self.indepvars.keys() contains all valid independent variables. If ϕ is a layer cake of SymPy applied functions, the chain rule is applied automatically. Parameters: qs: tuple of str Names of independent variables to differentiate with regard to. Use an empty tuple to skip differentiation and get just ϕ itself. strip: bool See return value for definitions of ``sym`` and ``expr``. If True, pass expr through ``symutil.strip_function_arguments()`` before returning it, replacing applied functions with bare symbols. If False, return expr as-is. sym is always keyify()'d to make it a definition key. Example: m = Model() m.dϕdq(("Bx","""
        invalid_inputs = [q for q in qs if q not in self.indepvars]
        if len(invalid_inputs):
            raise ValueError('Variable(s) {invalid} not in self.indepvars'.format(invalid=', '.join(invalid_inputs)))
        sym = symutil.make_function('ϕ', *self.indepvars.values())
        expr = self.φ
        for varname in qs:
            q = self.indepvars[varname]
            sym = sy.diff(sym, q, evaluate=False)
            expr = sy.diff(expr, q)
        sym = self.keyify(sym)
        if len(qs):
            expr = symutil.apply_substitutions_in(expr)
        if strip:
            expr = symutil.strip_function_arguments(expr)
        assert sym != 0, 'BUG in dϕdq(): symbol for function name is 0'
        return (sym, expr)

    def dφdqs(self, jacobian=True, hessian=True):
        """Return 1st and 2nd derivatives of ϕ w.r.t. all independent variables. Convenience function. This is essentially a loop over ``dϕdq()``, to differentiate self.ϕ symbolically. If ϕ is a layer cake of SymPy applied functions, it will be differentiated only formally (using the chain rule), without inserting any definitions. This is convenient, since by keeping the functional relations intact we avoid generating (possibly lengthy) common subexpressions. (stage2 takes care of actually calling the functions to obtain the necessary values at each step of evaluating the RHS.) Parameters: jacobian: bool Compute first derivatives. hessian: bool Compute second derivatives. Returns: dict(sy.Symbol -> sy."""
        ivars = sorted(self.indepvars.keys())
        out = {}
        allqs = []
        if jacobian:
            allqs.extend(((var,) for var in ivars))
        if hessian:
            allqs.extend(combinations_with_replacement(ivars, 2))
        for i, qs in enumerate(allqs, start=1):
            print('model: {label} ({iteration:d}/{total:d}) forming expression for {name}'.format(label=self.label, iteration=i, total=len(allqs), name=util.name_derivative('ϕ', qs)))
            sym, expr = self.dφdq(qs, strip=False)
            out[sym] = expr
        return out

    def simplify(self, expr):
        """Simplify expr. Specifically geared to optimize expressions treated by this class."""
        expr = recursive_collect(sy.together(sy.expand(expr)))
        expr = recursive_collect(expr, syms=self.Bs)
        expr = symutil.collect_const_in(expr)
        return expr


next

Prompt:
Implement the Python class `__DatasetWrapper` described below.

Class description:
A standard PyTorch definition of Dataset which defines the functions __len__ and __getitem__.

Method signatures and docstrings:
- def __init__(self, cv_iters): create df for features and labels remove samples that are not shared between the two tables
- def shuffle(self): categorize sample ID by label
- def next(self): rotate to the next cross validation process

Implement the Python class `__DatasetWrapper` described below.

Class description:
A standard PyTorch definition of Dataset which defines the functions __len__ and __getitem__.

Method signatures and docstrings:
- def __init__(self, cv_iters): create df for features and labels remove samples that are not shared between the two tables
- def shuffle(self): categorize sample ID by label
- def next(self): rotate to the next cross validation process

<|skeleton|>
class __DatasetWrapper:
    """A standard PyTorch definition of Dataset which defines the functions __len__ and __getitem__."""

    def __init__(self, cv_iters):
        """create df for features and labels remove samples that are not shared between the two tables"""
        <|body_0|>

    def shuffle(self):
        """categorize sample ID by label"""
        <|body_1|>

    def next(self):
        """rotate to the next cross validation process"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        assert cv_iters > 2, 'Cross validation folds must be more than 2 folds'
        self.cv_iters = cv_iters
        datapath = './Data'
        self.dataset = [[os.path.join(os.path.join(os.path.join(datapath, folder), label), image), int(label)] for folder in os.listdir(datapath) for label in os.listdir(os.path.join(datapath, folder)) for image in os.listdir(os.path.join(os.path.join(datapath, folder), label))]
        self.Ind = np.arange(len(self.dataset))
        self.shuffle()
<|end_body_0|>

<|body_start_1|>
        random.seed(231)
        random.shuffle(self.Ind)
        self.Ind = self.Ind[:int(len(self.Ind) / 5) * 5].reshape((self.cv_iters, -1))
        self.CVindex = 1
        self.Testindex = 0
<|end_body_1|>

<|body_start_2|>
        next_test = False
        if self.CVindex < self.cv_iters - 1:
            self.CVindex += 1
            if self.Testindex < self.cv_iters - 1:
                if self.Testindex == self.CVindex:
                    self.CVindex += 1
            elif self.Testindex == self.CVindex:
                self.CVindex = 0
                next_test = True
        else:
            self.CVindex = 0
            next_test = True
        if next_test:
            if self.Testindex < self.cv_iters - 1:
                self.Testindex += 1
            else:
                self.Testindex = 0
                self.CVindex = 1
<|end_body_2|>

Solution:
class __DatasetWrapper:
    """A standard PyTorch definition of Dataset which defines the functions __len__ and __getitem__."""

    def __init__(self, cv_iters):
        """create df for features and labels remove samples that are not shared between the two tables"""
        assert cv_iters > 2, 'Cross validation folds must be more than 2 folds'
        self.cv_iters = cv_iters
        datapath = './Data'
        self.dataset = [[os.path.join(os.path.join(os.path.join(datapath, folder), label), image), int(label)] for folder in os.listdir(datapath) for label in os.listdir(os.path.join(datapath, folder)) for image in os.listdir(os.path.join(os.path.join(datapath, folder), label))]
        self.Ind = np.arange(len(self.dataset))
        self.shuffle()

    def shuffle(self):
        """categorize sample ID by label"""
        random.seed(231)
        random.shuffle(self.Ind)
        self.Ind = self.Ind[:int(len(self.Ind) / 5) * 5].reshape((self.cv_iters, -1))
        self.CVindex = 1
        self.Testindex = 0

    def next(self):
        """rotate to the next cross validation process"""
        next_test = False
        if self.CVindex < self.cv_iters - 1:
            self.CVindex += 1
            if self.Testindex < self.cv_iters - 1:
                if self.Testindex == self.CVindex:
                    self.CVindex += 1
            elif self.Testindex == self.CVindex:
                self.CVindex = 0
                next_test = True
        else:
            self.CVindex = 0
            next_test = True
        if next_test:
            if self.Testindex < self.cv_iters - 1:
                self.Testindex += 1
            else:
                self.Testindex = 0
                self.CVindex = 1


delete

Prompt:
Implement the Python class `API_FollowUser` described below.

Class description:
Implement the API_FollowUser class.

Method signatures and docstrings:
- def post(self, user_id): start following user Parameters ---------- dst_user_id: int (required) Returns ---------- CODES: 200: OK 409: already subscribed BODY: empty
- def delete(self, user_id): stop following user Parameters ---------- dst_user_id: int (required) Returns ---------- CODES: 200: OK 404: current_user isn't subscribed on dst_user_id BODY: empty

Implement the Python class `API_FollowUser` described below.

Class description:
Implement the API_FollowUser class.

Method signatures and docstrings:
- def post(self, user_id): start following user Parameters ---------- dst_user_id: int (required) Returns ---------- CODES: 200: OK 409: already subscribed BODY: empty
- def delete(self, user_id): stop following user Parameters ---------- dst_user_id: int (required) Returns ---------- CODES: 200: OK 404: current_user isn't subscribed on dst_user_id BODY: empty

<|skeleton|>
class API_FollowUser:

    def post(self, user_id):
        """start following user Parameters ---------- dst_user_id: int (required) Returns ---------- CODES: 200: OK 409: already subscribed BODY: empty"""
        <|body_0|>

    def delete(self, user_id):
        """stop following user Parameters ---------- dst_user_id: int (required) Returns ---------- CODES: 200: OK 404: current_user isn't subscribed on dst_user_id BODY: empty"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        follow_user = self.db.query(FollowUser).filter_by(src_user_id=self.current_user).filter_by(dst_user_id=user_id).filter(FollowUser.is_current()).first()
        if follow_user:
            self.set_status(409)
        else:
            self.db.add(FollowUser(src_user_id=self.current_user, dst_user_id=user_id))
        self.db.commit()
        self.finish()
<|end_body_0|>

<|body_start_1|>
        follow_user = self.db.query(FollowUser).filter_by(src_user_id=self.current_user).filter_by(dst_user_id=user_id).filter(FollowUser.is_current()).first()
        if follow_user:
            follow_user.stop()
        else:
            self.set_status(404)
        self.db.commit()
        self.finish()
<|end_body_1|>

Solution:
class API_FollowUser:
    def post(self, user_id):
        """start following user Parameters ---------- dst_user_id: int (required) Returns ---------- CODES: 200: OK 409: already subscribed BODY: empty"""
        follow_user = self.db.query(FollowUser).filter_by(src_user_id=self.current_user).filter_by(dst_user_id=user_id).filter(FollowUser.is_current()).first()
        if follow_user:
            self.set_status(409)
        else:
            self.db.add(FollowUser(src_user_id=self.current_user, dst_user_id=user_id))
        self.db.commit()
        self.finish()

    def delete(self, user_id):
        """stop following user Parameters ---------- dst_user_id: int (required) Returns ---------- CODES: 200: OK 404: current_user isn't subscribed on dst_user_id BODY: empty"""
        follow_user = self.db.query(FollowUser).filter_by(src_user_id=self.current_user).filter_by(dst_user_id=user_id).filter(FollowUser.is_current()).first()
        if follow_user:
            follow_user.stop()
        else:
            self.set_status(404)
        self.db.commit()
        self.finish()


Prompt:
Implement the Python class `TaskManager` described below.

Class description:
Adding a method to get tasks currently owned by a user or group.

Method signatures and docstrings:
- def filter_active_by_owner(self, party, *args, **kwargs): Takes a User, Group, or GenericParty and returns a list of tasks that are currently owned by them.
- def can_be_seen_by_user(self, user, *args, **kwargs): Filters tasks that can be seen by a particular user. TODO: See if this can be optimized.

Implement the Python class `TaskManager` described below.

Class description:
Adding a method to get tasks currently owned by a user or group.

Method signatures and docstrings:
- def filter_active_by_owner(self, party, *args, **kwargs): Takes a User, Group, or GenericParty and returns a list of tasks that are currently owned by them.
- def can_be_seen_by_user(self, user, *args, **kwargs): Filters tasks that can be seen by a particular user. TODO: See if this can be optimized.

<|skeleton|>
class TaskManager:
    """Adding a method to get tasks currently owned by a user or group."""

    def filter_active_by_owner(self, party, *args, **kwargs):
        """Takes a User, Group, or GenericParty and returns a list of tasks that are currently owned by them."""
        <|body_0|>

    def can_be_seen_by_user(self, user, *args, **kwargs):
        """Filters tasks that can be seen by a particular user. TODO: See if this can be optimized."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if not party.__class__ == GenericParty:
            party = GenericParty.objects.get(party=party)
        all_owned_tasks = super(TaskManager, self).filter(ownership__party=party, completed=False).select_related('ownership')
        task_list = []
        for task in all_owned_tasks:
            ownership = task.ownership.filter(party=party).latest('created')
            if not ownership.disown:
                task_list.append(task)
        return task_list
<|end_body_0|>

<|body_start_1|>
        user_privileges = get_privileges_for_user(user)
        queryset = super(TaskManager, self).filter(access_requirements__prototype__privilege__in=user_privileges)
        return queryset
<|end_body_1|>

Solution:
class TaskManager:
    """Adding a method to get tasks currently owned by a user or group."""

    def filter_active_by_owner(self, party, *args, **kwargs):
        """Takes a User, Group, or GenericParty and returns a list of tasks that are currently owned by them."""
        if not party.__class__ == GenericParty:
            party = GenericParty.objects.get(party=party)
        all_owned_tasks = super(TaskManager, self).filter(ownership__party=party, completed=False).select_related('ownership')
        task_list = []
        for task in all_owned_tasks:
            ownership = task.ownership.filter(party=party).latest('created')
            if not ownership.disown:
                task_list.append(task)
        return task_list

    def can_be_seen_by_user(self, user, *args, **kwargs):
        """Filters tasks that can be seen by a particular user. TODO: See if this can be optimized."""
        user_privileges = get_privileges_for_user(user)
        queryset = super(TaskManager, self).filter(access_requirements__prototype__privilege__in=user_privileges)
        return queryset


forward

Prompt:
Implement the Python class `SimGNN` described below.

Class description:
SimGNN: A Neural Network Approach to Fast Graph Similarity Computation https://arxiv.org/abs/1808.05689

Method signatures and docstrings:
- def __init__(self, args, number_of_labels): :param args: Arguments object. :param number_of_labels: Number of node labels.
- def calculate_bottleneck_features(self): Deciding the shape of the bottleneck layer.
- def setup_layers(self): Creating the layers.
- def calculate_histogram(self, abstract_features_1, abstract_features_2): Calculate histogram from similarity matrix. :param abstract_features_1: Feature matrix for graph 1. :param abstract_features_2: Feature matrix for graph 2. :return hist: Histsogram of similarity scores.
- def convolutional_pass(self, edge_index, features): Making convolutional pass. :param edge_index: Edge indices. :param features: Feature matrix. :return features: Absstract feature matrix.
- def forward(self, data): Forward pass with graphs. :param data: Data dictiyonary. :return score: Similarity score.

Implement the Python class `SimGNN` described below.

Class description:
SimGNN: A Neural Network Approach to Fast Graph Similarity Computation https://arxiv.org/abs/1808.05689

Method signatures and docstrings:
- def __init__(self, args, number_of_labels): :param args: Arguments object. :param number_of_labels: Number of node labels.
- def calculate_bottleneck_features(self): Deciding the shape of the bottleneck layer.
- def setup_layers(self): Creating the layers.
- def calculate_histogram(self, abstract_features_1, abstract_features_2): Calculate histogram from similarity matrix. :param abstract_features_1: Feature matrix for graph 1. :param abstract_features_2: Feature matrix for graph 2. :return hist: Histsogram of similarity scores.
- def convolutional_pass(self, edge_index, features): Making convolutional pass. :param edge_index: Edge indices. :param features: Feature matrix. :return features: Absstract feature matrix.
- def forward(self, data): Forward pass with graphs. :param data: Data dictiyonary. :return score: Similarity score.

<|skeleton|>
class SimGNN:
    """SimGNN: A Neural Network Approach to Fast Graph Similarity Computation https://arxiv.org/abs/1808.05689"""

    def __init__(self, args, number_of_labels):
        """:param args: Arguments object. :param number_of_labels: Number of node labels."""
        <|body_0|>

    def calculate_bottleneck_features(self):
        """Deciding the shape of the bottleneck layer."""
        <|body_1|>

    def setup_layers(self):
        """Creating the layers."""
        <|body_2|>

    def calculate_histogram(self, abstract_features_1, abstract_features_2):
        """Calculate histogram from similarity matrix. :param abstract_features_1: Feature matrix for graph 1. :param abstract_features_2: Feature matrix for graph 2. :return hist: Histsogram of similarity scores."""
        <|body_3|>

    def convolutional_pass(self, edge_index, features):
        """Making convolutional pass. :param edge_index: Edge indices. :param features: Feature matrix. :return features: Absstract feature matrix."""
        <|body_4|>

    def forward(self, data):
        """Forward pass with graphs. :param data: Data dictiyonary. :return score: Similarity score."""
        <|body_5|>

<|end_skeleton|>

<|body_start_0|>
        super(SimGNN, self).__init__()
        self.args = args
        self.number_labels = number_of_labels
        self.setup_layers()
<|end_body_0|>

<|body_start_1|>
        if self.args.histogram == True:
            self.feature_count = self.args.tensor_neurons + self.args.bins
        else:
            self.feature_count = self.args.tensor_neurons
<|end_body_1|>

<|body_start_2|>
        self.calculate_bottleneck_features()
        self.convolution_1 = GCNConv(self.number_labels, self.args.filters_1)
        self.convolution_2 = GCNConv(self.args.filters_1, self.args.filters_2)
        self.convolution_3 = GCNConv(self.args.filters_2, self.args.filters_3)
        self.attention = AttentionModule(self.args)
        self.tensor_network = TenorNetworkModule(self.args)
        self.fully_connected_first = torch.nn.Linear(self.feature_count, self.args.bottle_neck_neurons)
        self.scoring_layer = torch.nn.Linear(self.args.bottle_neck_neurons, 1)
<|end_body_2|>

<|body_start_3|>
        scores = torch.mm(abstract_features_1, abstract_features_2).detach()
        scores = scores.view(-1, 1)
        hist = torch.histc(scores, bins=self.args.bins)
        hist = hist / torch.sum(hist)
        hist = hist.view(1, -1)
        return hist
<|end_body_3|>

<|body_start_4|>
        features = self.convolution_1(features, edge_index)
        features = torch.nn.functional.relu(features)
        features = torch.nn.functional.dropout(features, p=self.args.dropout, training=self.training)
        features = self.convolution_2(features, edge_index)
        features = torch.nn.functional.relu(features)
        features = torch.nn.functional.dropout(features, p=self.args.dropout, training=self.training)
        features = self.convolution_3(features, edge_index)
        return features
<|end_body_4|>

<|body_start_5|>
        edge_index_1 = data['edge_index_1']
        edge_index_2 = data['edge_index_2']
        features_1 = data['features_1']
        features_2 = data['features_2']
        abstract_features_1 = self.convolutional_pass(edge_index_1, features_1)
        abstract_features_2 = self.convolutional_pass(edge_index_2, features_2)
        if self.args.histogram == True:
            hist = self.calculate_histogram(abstract_features_1, torch.t(abstract_features_2))
        pooled_features_1 = self.attention(abstract_features_1)
        pooled_features_2 = self.attention(abstract_features_2)
        scores = self.tensor_network(pooled_features_1, pooled_features_2)
        scores = torch.t(scores)
        if self.args.histogram == True:
            scores = torch.cat((scores, hist), dim=1).view(1, -1)
        scores = torch.nn.functional.relu(self.fully_connected_first(scores))
        score = torch.sigmoid(self.scoring_layer(scores))
        return score
<|end_body_5|>

Solution:
class SimGNN:
    """SimGNN: A Neural Network Approach to Fast Graph Similarity Computation https://arxiv.org/abs/1808.05689"""

    def __init__(self, args, number_of_labels):
        """:param args: Arguments object. :param number_of_labels: Number of node labels."""
        super(SimGNN, self).__init__()
        self.args = args
        self.number_labels = number_of_labels
        self.setup_layers()

    def calculate_bottleneck_features(self):
        """Deciding the shape of the bottleneck layer."""
        if self.args.histogram == True:
            self.feature_count = self.args.tensor_neurons + self.args.bins
        else:
            self.feature_count = self.args.tensor_neurons

    def setup_layers(self):
        """Creating the layers."""
        self.calculate_bottleneck_features()
        self.convolution_1 = GCNConv(self.number_labels, self.args.filters_1)
        self.convolution_2 = GCNConv(self.args.filters_1, self.args.filters_2)
        self.convolution_3 = GCNConv(self.args.filters_2, self.args.filters_3)
        self.attention = AttentionModule(self.args)
        self.tensor_network = TenorNetworkModule(self.args)
        self.fully_connected_first = torch.nn.Linear(self.feature_count, self.args.bottle_neck_neurons)
        self.scoring_layer = torch.nn.Linear(self.args.bottle_neck_neurons, 1)

    def calculate_histogram(self, abstract_features_1, abstract_features_2):
        """Calculate histogram from similarity matrix. :param abstract_features_1: Feature matrix for graph 1. :param abstract_features_2: Feature matrix for graph 2. :return hist: Histsogram of similarity scores."""
        scores = torch.mm(abstract_features_1, abstract_features_2).detach()
        scores = scores.view(-1, 1)
        hist = torch.histc(scores, bins=self.args.bins)
        hist = hist / torch.sum(hist)
        hist = hist.view(1, -1)
        return hist

    def convolutional_pass(self, edge_index, features):
        """Making convolutional pass. :param edge_index: Edge indices. :param features: Feature matrix. :return features: Absstract feature matrix."""
        features = self.convolution_1(features, edge_index)
        features = torch.nn.functional.relu(features)
        features = torch.nn.functional.dropout(features, p=self.args.dropout, training=self.training)
        features = self.convolution_2(features, edge_index)
        features = torch.nn.functional.relu(features)
        features = torch.nn.functional.dropout(features, p=self.args.dropout, training=self.training)
        features = self.convolution_3(features, edge_index)
        return features

    def forward(self, data):
        """Forward pass with graphs. :param data: Data dictiyonary. :return score: Similarity score."""
        edge_index_1 = data['edge_index_1']
        edge_index_2 = data['edge_index_2']
        features_1 = data['features_1']
        features_2 = data['features_2']
        abstract_features_1 = self.convolutional_pass(edge_index_1, features_1)
        abstract_features_2 = self.convolutional_pass(edge_index_2, features_2)
        if self.args.histogram == True:
            hist = self.calculate_histogram(abstract_features_1, torch.t(abstract_features_2))
        pooled_features_1 = self.attention(abstract_features_1)
        pooled_features_2 = self.attention(abstract_features_2)
        scores = self.tensor_network(pooled_features_1, pooled_features_2)
        scores = torch.t(scores)
        if self.args.histogram == True:
            scores = torch.cat((scores, hist), dim=1).view(1, -1)
        scores = torch.nn.functional.relu(self.fully_connected_first(scores))
        score = torch.sigmoid(self.scoring_layer(scores))
        return score


Prompt:
Implement the Python class `DHTClient` described below.

Class description:
Get the latest data from the DHT sensor.

Method signatures and docstrings:
- def __init__(self, sensor, pin, name): Initialize the sensor.
- def update(self): Get the latest data the DHT sensor.

Implement the Python class `DHTClient` described below.

Class description:
Get the latest data from the DHT sensor.

Method signatures and docstrings:
- def __init__(self, sensor, pin, name): Initialize the sensor.
- def update(self): Get the latest data the DHT sensor.

<|skeleton|>
class DHTClient:
    """Get the latest data from the DHT sensor."""

    def __init__(self, sensor, pin, name):
        """Initialize the sensor."""
        <|body_0|>

    def update(self):
        """Get the latest data the DHT sensor."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.sensor = sensor
        self.pin = getattr(board, pin)
        self.data = {}
        self.name = name
<|end_body_0|>

<|body_start_1|>
        dht = self.sensor(self.pin)
        try:
            temperature = dht.temperature
            humidity = dht.humidity
        except RuntimeError:
            _LOGGER.debug('Unexpected value from DHT sensor: %s', self.name)
        except Exception:
            _LOGGER.exception('Error updating DHT sensor: %s', self.name)
        else:
            if temperature:
                self.data[SENSOR_TEMPERATURE] = temperature
            if humidity:
                self.data[SENSOR_HUMIDITY] = humidity
        finally:
            dht.exit()
<|end_body_1|>

Solution:
class DHTClient:
    """Get the latest data from the DHT sensor."""

    def __init__(self, sensor, pin, name):
        """Initialize the sensor."""
        self.sensor = sensor
        self.pin = getattr(board, pin)
        self.data = {}
        self.name = name

    def update(self):
        """Get the latest data the DHT sensor."""
        dht = self.sensor(self.pin)
        try:
            temperature = dht.temperature
            humidity = dht.humidity
        except RuntimeError:
            _LOGGER.debug('Unexpected value from DHT sensor: %s', self.name)
        except Exception:
            _LOGGER.exception('Error updating DHT sensor: %s', self.name)
        else:
            if temperature:
                self.data[SENSOR_TEMPERATURE] = temperature
            if humidity:
                self.data[SENSOR_HUMIDITY] = humidity
        finally:
            dht.exit()


Prompt:
Implement the Python class `BasePageElement` described below.

Class description:
Base page class that is initialized on every page object class.

Method signatures and docstrings:
- def __set__(self, obj, value): Sets the text to the value supplied
- def __get__(self, obj, owner): Gets the text of the specified object

Implement the Python class `BasePageElement` described below.

Class description:
Base page class that is initialized on every page object class.

Method signatures and docstrings:
- def __set__(self, obj, value): Sets the text to the value supplied
- def __get__(self, obj, owner): Gets the text of the specified object

<|skeleton|>
class BasePageElement:
    """Base page class that is initialized on every page object class."""

    def __set__(self, obj, value):
        """Sets the text to the value supplied"""
        <|body_0|>

    def __get__(self, obj, owner):
        """Gets the text of the specified object"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        driver = obj.driver
        if self.locator[0] != 'css selector':
            raise 'Using a locator other than css'
        WebDriverWait(driver, 100).until(lambda driver: driver.find_element_by_css_selector(self.locator[1]))
        driver.find_element_by_css_selector(self.locator[1]).send_keys(value)
<|end_body_0|>

<|body_start_1|>
        driver = obj.driver
        if self.locator[0] != 'css selector':
            raise 'Using a locator other than css'
        WebDriverWait(driver, 100).until(lambda driver: driver.find_element_by_css_selector(self.locator[1]))
        element = driver.find_element_by_css_selector(self.locator[1])
        return element.get_attribute('value')
<|end_body_1|>

Solution:
class BasePageElement:
    """Base page class that is initialized on every page object class."""

    def __set__(self, obj, value):
        """Sets the text to the value supplied"""
        driver = obj.driver
        if self.locator[0] != 'css selector':
            raise 'Using a locator other than css'
        WebDriverWait(driver, 100).until(lambda driver: driver.find_element_by_css_selector(self.locator[1]))
        driver.find_element_by_css_selector(self.locator[1]).send_keys(value)

    def __get__(self, obj, owner):
        """Gets the text of the specified object"""
        driver = obj.driver
        if self.locator[0] != 'css selector':
            raise 'Using a locator other than css'
        WebDriverWait(driver, 100).until(lambda driver: driver.find_element_by_css_selector(self.locator[1]))
        element = driver.find_element_by_css_selector(self.locator[1])
        return element.get_attribute('value')


Prompt:
Implement the Python class `GameController` described below.

Class description:
Implement the GameController class.

Method signatures and docstrings:
- def __init__(self): creat a PairOfDice() object, initialize the point and score value
- def start_play(self): Start to play the game, roll the dice and get current value
- def show_result(self): get the result based on the rules
- def continue_game(self): didn't get the result, continue to play, compare the point with the origin_point

Implement the Python class `GameController` described below.

Class description:
Implement the GameController class.

Method signatures and docstrings:
- def __init__(self): creat a PairOfDice() object, initialize the point and score value
- def start_play(self): Start to play the game, roll the dice and get current value
- def show_result(self): get the result based on the rules
- def continue_game(self): didn't get the result, continue to play, compare the point with the origin_point

<|skeleton|>
class GameController:

    def __init__(self):
        """creat a PairOfDice() object, initialize the point and score value"""
        <|body_0|>

    def start_play(self):
        """Start to play the game, roll the dice and get current value"""
        <|body_1|>

    def show_result(self):
        """get the result based on the rules"""
        <|body_2|>

    def continue_game(self):
        """didn't get the result, continue to play, compare the point with the origin_point"""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        self.pair = PairOfDice()
        self.point = None
        self.origin_point = None
<|end_body_0|>

<|body_start_1|>
        input('Please enter to roll the dice...\n')
        self.pair.roll_dice()
        self.point = self.pair.current_value()
<|end_body_1|>

<|body_start_2|>
        WIN_POINTS = [7, 11]
        LOSE_POINTS = [2, 3, 12]
        if self.point in LOSE_POINTS:
            print('You rolled {}. You lose.'.format(self.point))
        elif self.point in WIN_POINTS:
            print('You rolled {}. You win.'.format(self.point))
        else:
            print('You point is {}'.format(self.point))
            self.origin_point = self.point
            self.continue_game()
<|end_body_2|>

<|body_start_3|>
        LOSE_POINT = 7
        self.start_play()
        while self.point != self.origin_point and self.point != LOSE_POINT:
            print('You rolled {}.'.format(self.point))
            self.start_play()
        else:
            if self.point == self.origin_point:
                print('You rolled {}. You win.'.format(self.point))
            else:
                print('You rolled {}. You lose.'.format(self.point))
<|end_body_3|>

Solution:
class GameController:
    def __init__(self):
        """creat a PairOfDice() object, initialize the point and score value"""
        self.pair = PairOfDice()
        self.point = None
        self.origin_point = None

    def start_play(self):
        """Start to play the game, roll the dice and get current value"""
        input('Please enter to roll the dice...\n')
        self.pair.roll_dice()
        self.point = self.pair.current_value()

    def show_result(self):
        """get the result based on the rules"""
        WIN_POINTS = [7, 11]
        LOSE_POINTS = [2, 3, 12]
        if self.point in LOSE_POINTS:
            print('You rolled {}. You lose.'.format(self.point))
        elif self.point in WIN_POINTS:
            print('You rolled {}. You win.'.format(self.point))
        else:
            print('You point is {}'.format(self.point))
            self.origin_point = self.point
            self.continue_game()

    def continue_game(self):
        """didn't get the result, continue to play, compare the point with the origin_point"""
        LOSE_POINT = 7
        self.start_play()
        while self.point != self.origin_point and self.point != LOSE_POINT:
            print('You rolled {}.'.format(self.point))
            self.start_play()
        else:
            if self.point == self.origin_point:
                print('You rolled {}. You win.'.format(self.point))
            else:
                print('You rolled {}. You lose.'.format(self.point))


save

Prompt:
Implement the Python class `Video` described below.

Class description:
Implement the Video class.

Method signatures and docstrings:
- def get_embed_url(self): Get correct embed url for Youtube or Vimeo.
- def save(self, force_insert=False, force_update=False, using=None, update_fields=None): Set html field with correct iframe.

Implement the Python class `Video` described below.

Class description:
Implement the Video class.

Method signatures and docstrings:
- def get_embed_url(self): Get correct embed url for Youtube or Vimeo.
- def save(self, force_insert=False, force_update=False, using=None, update_fields=None): Set html field with correct iframe.

<|skeleton|>
class Video:

    def get_embed_url(self):
        """Get correct embed url for Youtube or Vimeo."""
        <|body_0|>

    def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
        """Set html field with correct iframe."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        embed_url = None
        youtube_embed_url = 'https://www.youtube.com/embed/{}'
        vimeo_embed_url = 'https://player.vimeo.com/video/{}'
        if re.match(YOUTUBE_URL_RE, self.url):
            embed_url = youtube_embed_url.format(re.match(YOUTUBE_URL_RE, self.url).group(2))
        if re.match(VIMEO_URL_RE, self.url):
            embed_url = vimeo_embed_url.format(re.match(VIMEO_URL_RE, self.url).group(3))
        return embed_url
<|end_body_0|>

<|body_start_1|>
        if self.url:
            iframe_html = '<iframe src="{}" frameborder="0" title="{}" allowfullscreen></iframe>'
            self.html = iframe_html.format(self.get_embed_url(), self.title)
        return super().save(force_insert, force_update, using, update_fields)
<|end_body_1|>

Solution:
class Video:
    def get_embed_url(self):
        """Get correct embed url for Youtube or Vimeo."""
        embed_url = None
        youtube_embed_url = 'https://www.youtube.com/embed/{}'
        vimeo_embed_url = 'https://player.vimeo.com/video/{}'
        if re.match(YOUTUBE_URL_RE, self.url):
            embed_url = youtube_embed_url.format(re.match(YOUTUBE_URL_RE, self.url).group(2))
        if re.match(VIMEO_URL_RE, self.url):
            embed_url = vimeo_embed_url.format(re.match(VIMEO_URL_RE, self.url).group(3))
        return embed_url

    def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
        """Set html field with correct iframe."""
        if self.url:
            iframe_html = '<iframe src="{}" frameborder="0" title="{}" allowfullscreen></iframe>'
            self.html = iframe_html.format(self.get_embed_url(), self.title)
        return super().save(force_insert, force_update, using, update_fields)


Prompt:
Implement the Python class `InvariantedClass` described below.

Class description:
Implement the InvariantedClass class.

Method signatures and docstrings:
- def _validate(self) -> None: Step 5 (1st flow) or Step 4 (2nd flow). Process contract for object.
- def _patched_method(self, method: Callable, *args, **kwargs): Step 4 (1st flow). Call method
- def __getattribute__(self, name: str): Step 3 (1st flow). Get method
- def __setattr__(self, name: str, value): Step 3 (2nd flow). Set some attribute

Implement the Python class `InvariantedClass` described below.

Class description:
Implement the InvariantedClass class.

Method signatures and docstrings:
- def _validate(self) -> None: Step 5 (1st flow) or Step 4 (2nd flow). Process contract for object.
- def _patched_method(self, method: Callable, *args, **kwargs): Step 4 (1st flow). Call method
- def __getattribute__(self, name: str): Step 3 (1st flow). Get method
- def __setattr__(self, name: str, value): Step 3 (2nd flow). Set some attribute

<|skeleton|>
class InvariantedClass:

    def _validate(self) -> None:
        """Step 5 (1st flow) or Step 4 (2nd flow). Process contract for object."""
        <|body_0|>

    def _patched_method(self, method: Callable, *args, **kwargs):
        """Step 4 (1st flow). Call method"""
        <|body_1|>

    def __getattribute__(self, name: str):
        """Step 3 (1st flow). Get method"""
        <|body_2|>

    def __setattr__(self, name: str, value):
        """Step 3 (2nd flow). Set some attribute"""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        self._disable_patching = True
        self._validate_base(self)
        self._disable_patching = False
<|end_body_0|>

<|body_start_1|>
        self._validate()
        result = method(*args, **kwargs)
        self._validate()
        return result
<|end_body_1|>

<|body_start_2|>
        attr = super().__getattribute__(name)
        if name in ('_patched_method', '_validate', '_validate_base', '_disable_patching'):
            return attr
        if self._disable_patching:
            return attr
        if not isinstance(attr, MethodType):
            return attr
        patched_method = partial(self._patched_method, attr)
        return update_wrapper(patched_method, attr)
<|end_body_2|>

<|body_start_3|>
        super().__setattr__(name, value)
        if name == '_disable_patching':
            return
        self._validate()
<|end_body_3|>

Solution:
class InvariantedClass:
    def _validate(self) -> None:
        """Step 5 (1st flow) or Step 4 (2nd flow). Process contract for object."""
        self._disable_patching = True
        self._validate_base(self)
        self._disable_patching = False

    def _patched_method(self, method: Callable, *args, **kwargs):
        """Step 4 (1st flow). Call method"""
        self._validate()
        result = method(*args, **kwargs)
        self._validate()
        return result

    def __getattribute__(self, name: str):
        """Step 3 (1st flow). Get method"""
        attr = super().__getattribute__(name)
        if name in ('_patched_method', '_validate', '_validate_base', '_disable_patching'):
            return attr
        if self._disable_patching:
            return attr
        if not isinstance(attr, MethodType):
            return attr
        patched_method = partial(self._patched_method, attr)
        return update_wrapper(patched_method, attr)

    def __setattr__(self, name: str, value):
        """Step 3 (2nd flow). Set some attribute"""
        super().__setattr__(name, value)
        if name == '_disable_patching':
            return
        self._validate()


Prompt:
Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def medianSlidingWindow(self, nums, k): Use heap
- def medianSlidingWindow_TLE(self, nums, k): Use priority queue :param nums: A list of integers. :param k: size of window :return: The median of element inside the window at each moving.

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def medianSlidingWindow(self, nums, k): Use heap
- def medianSlidingWindow_TLE(self, nums, k): Use priority queue :param nums: A list of integers. :param k: size of window :return: The median of element inside the window at each moving.

<|skeleton|>
class Solution:

    def medianSlidingWindow(self, nums, k):
        """Use heap"""
        <|body_0|>

    def medianSlidingWindow_TLE(self, nums, k):
        """Use priority queue :param nums: A list of integers. :param k: size of window :return: The median of element inside the window at each moving."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if len(nums) < 1:
            return []
        ret = []
        dh = DualHeap()
        for i in xrange(k):
            dh.add(nums[i])
        ret.append(dh.median())
        for i in xrange(k, len(nums)):
            dh.remove(nums[i - k])
            dh.add(nums[i])
            ret.append(dh.median())
        return ret
<|end_body_0|>

<|body_start_1|>
        if len(nums) < 1:
            return []
        pq = PriorityQueue()
        for i in xrange(k):
            pq.insert(nums[i])
        ret = []
        mid = k / 2
        if k % 2 == 0:
            mid -= 1
        ret.append(pq[mid])
        for i in xrange(k, len(nums)):
            pq.remove(nums[i - k])
            pq.insert(nums[i])
            ret.append(pq[mid])
        return ret
<|end_body_1|>

Solution:
class Solution:
    def medianSlidingWindow(self, nums, k):
        """Use heap"""
        if len(nums) < 1:
            return []
        ret = []
        dh = DualHeap()
        for i in xrange(k):
            dh.add(nums[i])
        ret.append(dh.median())
        for i in xrange(k, len(nums)):
            dh.remove(nums[i - k])
            dh.add(nums[i])
            ret.append(dh.median())
        return ret

    def medianSlidingWindow_TLE(self, nums, k):
        """Use priority queue :param nums: A list of integers. :param k: size of window :return: The median of element inside the window at each moving."""
        if len(nums) < 1:
            return []
        pq = PriorityQueue()
        for i in xrange(k):
            pq.insert(nums[i])
        ret = []
        mid = k / 2
        if k % 2 == 0:
            mid -= 1
        ret.append(pq[mid])
        for i in xrange(k, len(nums)):
            pq.remove(nums[i - k])
            pq.insert(nums[i])
            ret.append(pq[mid])
        return ret


Prompt:
Implement the Python class `Signal` described below.

Class description:
Representation of signals in the database. :attribute leader: The leader that created this signal. :attribute movement: The movement that this signal was created in. :attribute message: Message from the leader.

Method signatures and docstrings:
- def __init__(self, leader, movement, message=None): Construct a new signal.
- def to_json(self): Get the json representation of the signal.

Implement the Python class `Signal` described below.

Class description:
Representation of signals in the database. :attribute leader: The leader that created this signal. :attribute movement: The movement that this signal was created in. :attribute message: Message from the leader.

Method signatures and docstrings:
- def __init__(self, leader, movement, message=None): Construct a new signal.
- def to_json(self): Get the json representation of the signal.

<|skeleton|>
class Signal:
    """Representation of signals in the database. :attribute leader: The leader that created this signal. :attribute movement: The movement that this signal was created in. :attribute message: Message from the leader."""

    def __init__(self, leader, movement, message=None):
        """Construct a new signal."""
        <|body_0|>

    def to_json(self):
        """Get the json representation of the signal."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.leader = leader
        self.movement = movement
        self.time_stamp = datetime.now()
        self.message = message
<|end_body_0|>

<|body_start_1|>
        signal_dict = {'time_stamp': str(self.time_stamp.astimezone())}
        if self.message:
            signal_dict['message'] = self.message
        return signal_dict
<|end_body_1|>

Solution:
class Signal:
    """Representation of signals in the database. :attribute leader: The leader that created this signal. :attribute movement: The movement that this signal was created in. :attribute message: Message from the leader."""

    def __init__(self, leader, movement, message=None):
        """Construct a new signal."""
        self.leader = leader
        self.movement = movement
        self.time_stamp = datetime.now()
        self.message = message

    def to_json(self):
        """Get the json representation of the signal."""
        signal_dict = {'time_stamp': str(self.time_stamp.astimezone())}
        if self.message:
            signal_dict['message'] = self.message
        return signal_dict


findRepeatNumber

第一种方法 维持一个数组，a[n] 位置保存对应的数的个数 空间上有些浪费

第二种方法 把方法一中的数组换成字典来存储，不需要初始化空间，查找也是O(1)

第二种的改版 字典用set来存储

Prompt:
Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def findRepeatNumber(self, nums: List[int]) -> int: 第一种方法 维持一个数组，a[n] 位置保存对应的数的个数 空间上有些浪费
- def findRepeatNumber2(self, nums: List[int]) -> int: 第二种方法 把方法一中的数组换成字典来存储，不需要初始化空间，查找也是O(1)
- def findRepeatNumber2_2(self, nums: List[int]) -> int: 第二种的改版 字典用set来存储

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def findRepeatNumber(self, nums: List[int]) -> int: 第一种方法 维持一个数组，a[n] 位置保存对应的数的个数 空间上有些浪费
- def findRepeatNumber2(self, nums: List[int]) -> int: 第二种方法 把方法一中的数组换成字典来存储，不需要初始化空间，查找也是O(1)
- def findRepeatNumber2_2(self, nums: List[int]) -> int: 第二种的改版 字典用set来存储

<|skeleton|>
class Solution:

    def findRepeatNumber(self, nums: List[int]) -> int:
        """第一种方法 维持一个数组，a[n] 位置保存对应的数的个数 空间上有些浪费"""
        <|body_0|>

    def findRepeatNumber2(self, nums: List[int]) -> int:
        """第二种方法 把方法一中的数组换成字典来存储，不需要初始化空间，查找也是O(1)"""
        <|body_1|>

    def findRepeatNumber2_2(self, nums: List[int]) -> int:
        """第二种的改版 字典用set来存储"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        length = len(nums)
        store = [0] * length
        for num in nums:
            store[num] += 1
            if store[num] >= 2:
                return num
        return -1
<|end_body_0|>

<|body_start_1|>
        find_dict = dict()
        for num in nums:
            if num in find_dict:
                return num
            else:
                find_dict[num] = 0
<|end_body_1|>

<|body_start_2|>
        find_set = set()
        for num in nums:
            if num in find_set:
                return num
            else:
                find_set.add(num)
<|end_body_2|>

Solution:
class Solution:
    def findRepeatNumber(self, nums: List[int]) -> int:
        """第一种方法 维持一个数组，a[n] 位置保存对应的数的个数 空间上有些浪费"""
        length = len(nums)
        store = [0] * length
        for num in nums:
            store[num] += 1
            if store[num] >= 2:
                return num
        return -1

    def findRepeatNumber2(self, nums: List[int]) -> int:
        """第二种方法 把方法一中的数组换成字典来存储，不需要初始化空间，查找也是O(1)"""
        find_dict = dict()
        for num in nums:
            if num in find_dict:
                return num
            else:
                find_dict[num] = 0

    def findRepeatNumber2_2(self, nums: List[int]) -> int:
        """第二种的改版 字典用set来存储"""
        find_set = set()
        for num in nums:
            if num in find_set:
                return num
            else:
                find_set.add(num)


Prompt:
Implement the Python class `WorkerLookups` described below.

Class description:
Implement the WorkerLookups class.

Method signatures and docstrings:
- async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUID: Given a work pool name, return its ID. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based).
- async def _get_default_work_pool_queue_id_from_work_pool_name(self, session: AsyncSession, work_pool_name: str): Given a work pool name, return the ID of its default queue. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based).
- async def _get_work_pool_queue_id_from_name(self, session: AsyncSession, work_pool_name: str, work_pool_queue_name: str) -> UUID: Given a work pool name and work pool queue name, return the ID of the queue. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based).

Implement the Python class `WorkerLookups` described below.

Class description:
Implement the WorkerLookups class.

Method signatures and docstrings:
- async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUID: Given a work pool name, return its ID. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based).
- async def _get_default_work_pool_queue_id_from_work_pool_name(self, session: AsyncSession, work_pool_name: str): Given a work pool name, return the ID of its default queue. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based).
- async def _get_work_pool_queue_id_from_name(self, session: AsyncSession, work_pool_name: str, work_pool_queue_name: str) -> UUID: Given a work pool name and work pool queue name, return the ID of the queue. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based).

<|skeleton|>
class WorkerLookups:

    async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUID:
        """Given a work pool name, return its ID. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based)."""
        <|body_0|>

    async def _get_default_work_pool_queue_id_from_work_pool_name(self, session: AsyncSession, work_pool_name: str):
        """Given a work pool name, return the ID of its default queue. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based)."""
        <|body_1|>

    async def _get_work_pool_queue_id_from_name(self, session: AsyncSession, work_pool_name: str, work_pool_queue_name: str) -> UUID:
        """Given a work pool name and work pool queue name, return the ID of the queue. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based)."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        work_pool = await models.workers.read_work_pool_by_name(session=session, work_pool_name=work_pool_name)
        if not work_pool:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Worker pool "{work_pool_name}" not found.')
        return work_pool.id
<|end_body_0|>

<|body_start_1|>
        work_pool = await models.workers.read_work_pool_by_name(session=session, work_pool_name=work_pool_name)
        if not work_pool:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Worker pool "{work_pool_name}" not found.')
        return work_pool.default_queue_id
<|end_body_1|>

<|body_start_2|>
        work_pool_queue = await models.workers.read_work_pool_queue_by_name(session=session, work_pool_name=work_pool_name, work_pool_queue_name=work_pool_queue_name)
        if not work_pool_queue:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Worker queue '{work_pool_name}/{work_pool_queue_name}' not found.")
        return work_pool_queue.id
<|end_body_2|>

Solution:
class WorkerLookups:
    async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUID:
        """Given a work pool name, return its ID. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based)."""
        work_pool = await models.workers.read_work_pool_by_name(session=session, work_pool_name=work_pool_name)
        if not work_pool:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Worker pool "{work_pool_name}" not found.')
        return work_pool.id

    async def _get_default_work_pool_queue_id_from_work_pool_name(self, session: AsyncSession, work_pool_name: str):
        """Given a work pool name, return the ID of its default queue. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based)."""
        work_pool = await models.workers.read_work_pool_by_name(session=session, work_pool_name=work_pool_name)
        if not work_pool:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Worker pool "{work_pool_name}" not found.')
        return work_pool.default_queue_id

    async def _get_work_pool_queue_id_from_name(self, session: AsyncSession, work_pool_name: str, work_pool_queue_name: str) -> UUID:
        """Given a work pool name and work pool queue name, return the ID of the queue. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based)."""
        work_pool_queue = await models.workers.read_work_pool_queue_by_name(session=session, work_pool_name=work_pool_name, work_pool_queue_name=work_pool_queue_name)
        if not work_pool_queue:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Worker queue '{work_pool_name}/{work_pool_queue_name}' not found.")
        return work_pool_queue.id