learn

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

Class description:
Implement the NNOnlineQAgent class.

Method signatures and docstrings:
- def __init__(self, q_network, optimizer, state_space, action_space, epsilon=0.1, gamma=0.999): Agent that learns action values (Q) through Q-learning method. Assumes Box state space and Discrete action space.
- def learn(self, state, action, next_state, reward, done): Train the agent with a given transition.

Implement the Python class `NNOnlineQAgent` described below.

Class description:
Implement the NNOnlineQAgent class.

Method signatures and docstrings:
- def __init__(self, q_network, optimizer, state_space, action_space, epsilon=0.1, gamma=0.999): Agent that learns action values (Q) through Q-learning method. Assumes Box state space and Discrete action space.
- def learn(self, state, action, next_state, reward, done): Train the agent with a given transition.

<|skeleton|>
class NNOnlineQAgent:

    def __init__(self, q_network, optimizer, state_space, action_space, epsilon=0.1, gamma=0.999):
        """Agent that learns action values (Q) through Q-learning method. Assumes Box state space and Discrete action space."""
        <|body_0|>

    def learn(self, state, action, next_state, reward, done):
        """Train the agent with a given transition."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.state_space = state_space
        self.action_space = action_space
        self.epsilon = epsilon
        self.gamma = gamma
        self.q_network = q_network
        self.optimizer = optimizer
<|end_body_0|>

<|body_start_1|>
        predicted_q_value = self.q_network(torch.FloatTensor(state))[action]
        with torch.no_grad():
            target_q_value = torch.FloatTensor([reward])
            if not done:
                target_q_value += self.gamma * self.q_network(torch.FloatTensor(next_state)).max().item()
        loss = F.smooth_l1_loss(predicted_q_value, target_q_value)
        self.optimizer.zero_grad()
        loss.backward()
        self.optimizer.step()
<|end_body_1|>

Solution:
class NNOnlineQAgent:
    def __init__(self, q_network, optimizer, state_space, action_space, epsilon=0.1, gamma=0.999):
        """Agent that learns action values (Q) through Q-learning method. Assumes Box state space and Discrete action space."""
        self.state_space = state_space
        self.action_space = action_space
        self.epsilon = epsilon
        self.gamma = gamma
        self.q_network = q_network
        self.optimizer = optimizer

    def learn(self, state, action, next_state, reward, done):
        """Train the agent with a given transition."""
        predicted_q_value = self.q_network(torch.FloatTensor(state))[action]
        with torch.no_grad():
            target_q_value = torch.FloatTensor([reward])
            if not done:
                target_q_value += self.gamma * self.q_network(torch.FloatTensor(next_state)).max().item()
        loss = F.smooth_l1_loss(predicted_q_value, target_q_value)
        self.optimizer.zero_grad()
        loss.backward()
        self.optimizer.step()


startSpider

针对硅谷密探的爬虫 :return:

GGListSpider

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

Class description:
Implement the GG class.

Method signatures and docstrings:
- def startSpider(self): 针对硅谷密探的爬虫 :return:
- def GGListSpider(self, index): 硅谷密探网爬虫 :param url: :return: List<PWBean>

Implement the Python class `GG` described below.

Class description:
Implement the GG class.

Method signatures and docstrings:
- def startSpider(self): 针对硅谷密探的爬虫 :return:
- def GGListSpider(self, index): 硅谷密探网爬虫 :param url: :return: List<PWBean>

<|skeleton|>
class GG:

    def startSpider(self):
        """针对硅谷密探的爬虫 :return:"""
        <|body_0|>

    def GGListSpider(self, index):
        """硅谷密探网爬虫 :param url: :return: List<PWBean>"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        for i in range(1, 11):
            dataList = self.GGListSpider(i)
            BmobUtils.insertListBmob('GGBean', dataList)
            print('经过不懈的努力，开哥爬下了品玩科技第 %d 页' % i)
<|end_body_0|>

<|body_start_1|>
        url = 'http://www.svinsight.com/api?callback=jQuery111306490858093306913_%d' % (time.time() * 1000)
        data = {'id': '208', 'query': '{"global": {"Loc": 2, "OS": 2, "Port": 300, "Sign": "", "Token": ""},\n                           "data": {"Index":%d, "OrderBy": 0, "QueryString": [], "Size": 1}}' % index}
        html = HtmlPostUtils.postHtml(url, data=data, type='PW')
        datalist = GGHtmlDealUtils.dealHtml(html)
        return datalist
<|end_body_1|>

Solution:
class GG:
    def startSpider(self):
        """针对硅谷密探的爬虫 :return:"""
        for i in range(1, 11):
            dataList = self.GGListSpider(i)
            BmobUtils.insertListBmob('GGBean', dataList)
            print('经过不懈的努力，开哥爬下了品玩科技第 %d 页' % i)

    def GGListSpider(self, index):
        """硅谷密探网爬虫 :param url: :return: List<PWBean>"""
        url = 'http://www.svinsight.com/api?callback=jQuery111306490858093306913_%d' % (time.time() * 1000)
        data = {'id': '208', 'query': '{"global": {"Loc": 2, "OS": 2, "Port": 300, "Sign": "", "Token": ""},\n                           "data": {"Index":%d, "OrderBy": 0, "QueryString": [], "Size": 1}}' % index}
        html = HtmlPostUtils.postHtml(url, data=data, type='PW')
        datalist = GGHtmlDealUtils.dealHtml(html)
        return datalist


split

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

Class description:
Implement the Parameters class.

Method signatures and docstrings:
- def split(all_parameters: dict, levels: list) -> dict: Split parameter in different levels :param all_parameters: dict with all parameters with keys like key_levels :param levels: list with all the levels presents :return: dict with separated dicts
- def split_by_sources(all_parameters: dict, sources: list) -> dict: Split parameter by different sources All keys should be source_table or source_column_names :param all_parameters: dict with all parameters with keys like source_keys :param sources: list with all levels present :return: dict with separated dicts

Implement the Python class `Parameters` described below.

Class description:
Implement the Parameters class.

Method signatures and docstrings:
- def split(all_parameters: dict, levels: list) -> dict: Split parameter in different levels :param all_parameters: dict with all parameters with keys like key_levels :param levels: list with all the levels presents :return: dict with separated dicts
- def split_by_sources(all_parameters: dict, sources: list) -> dict: Split parameter by different sources All keys should be source_table or source_column_names :param all_parameters: dict with all parameters with keys like source_keys :param sources: list with all levels present :return: dict with separated dicts

<|skeleton|>
class Parameters:

    def split(all_parameters: dict, levels: list) -> dict:
        """Split parameter in different levels :param all_parameters: dict with all parameters with keys like key_levels :param levels: list with all the levels presents :return: dict with separated dicts"""
        <|body_0|>

    def split_by_sources(all_parameters: dict, sources: list) -> dict:
        """Split parameter by different sources All keys should be source_table or source_column_names :param all_parameters: dict with all parameters with keys like source_keys :param sources: list with all levels present :return: dict with separated dicts"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        dict_with_level = {}
        for key in all_parameters.keys():
            split_number = key.rfind('_')
            keyword = key[split_number + 1:]
            if keyword in levels:
                code_name = key[:split_number]
            else:
                code_name = key
                keyword = 'common'
            if keyword not in dict_with_level.keys():
                dict_with_level[keyword] = {}
            dict_with_level[keyword][code_name] = all_parameters[key]
        return dict_with_level
<|end_body_0|>

<|body_start_1|>
        dict_with_sources = {}
        for key in all_parameters.keys():
            code_source = key.replace('_table', '')
            code_source = code_source.replace('_columns_names', '')
            if code_source in sources:
                keyword = code_source
            else:
                keyword = 'common'
            if keyword not in dict_with_sources.keys():
                dict_with_sources[keyword] = {}
            dict_with_sources[keyword][key] = all_parameters[key]
        return dict_with_sources
<|end_body_1|>

Solution:
class Parameters:
    def split(all_parameters: dict, levels: list) -> dict:
        """Split parameter in different levels :param all_parameters: dict with all parameters with keys like key_levels :param levels: list with all the levels presents :return: dict with separated dicts"""
        dict_with_level = {}
        for key in all_parameters.keys():
            split_number = key.rfind('_')
            keyword = key[split_number + 1:]
            if keyword in levels:
                code_name = key[:split_number]
            else:
                code_name = key
                keyword = 'common'
            if keyword not in dict_with_level.keys():
                dict_with_level[keyword] = {}
            dict_with_level[keyword][code_name] = all_parameters[key]
        return dict_with_level

    def split_by_sources(all_parameters: dict, sources: list) -> dict:
        """Split parameter by different sources All keys should be source_table or source_column_names :param all_parameters: dict with all parameters with keys like source_keys :param sources: list with all levels present :return: dict with separated dicts"""
        dict_with_sources = {}
        for key in all_parameters.keys():
            code_source = key.replace('_table', '')
            code_source = code_source.replace('_columns_names', '')
            if code_source in sources:
                keyword = code_source
            else:
                keyword = 'common'
            if keyword not in dict_with_sources.keys():
                dict_with_sources[keyword] = {}
            dict_with_sources[keyword][key] = all_parameters[key]
        return dict_with_sources


call

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

Class description:
Compute the focal loss between `logits` and the golden `target` values. Focal loss = -(1-pt)^gamma * log(pt) where pt is the probability of being classified to the true class.

Method signatures and docstrings:
- def __init__(self, alpha, gamma, label_smoothing=0.0, **kwargs): Initialize focal loss. Args: alpha: A float32 scalar multiplying alpha to the loss from positive examples and (1-alpha) to the loss from negative examples. gamma: A float32 scalar modulating loss from hard and easy examples. label_smoothing: Float in [0, 1]. If > `0` then smooth the labels. **kwargs: other params.
- def call(self, y_true, y_pred): Compute focal loss for y and y_pred. Args: y: A tuple of (normalizer, y_true), where y_true is the target class. y_pred: A float32 tensor [batch, height_in, width_in, num_predictions]. Returns: the focal loss.

Implement the Python class `ClassFocalLoss` described below.

Class description:
Compute the focal loss between `logits` and the golden `target` values. Focal loss = -(1-pt)^gamma * log(pt) where pt is the probability of being classified to the true class.

Method signatures and docstrings:
- def __init__(self, alpha, gamma, label_smoothing=0.0, **kwargs): Initialize focal loss. Args: alpha: A float32 scalar multiplying alpha to the loss from positive examples and (1-alpha) to the loss from negative examples. gamma: A float32 scalar modulating loss from hard and easy examples. label_smoothing: Float in [0, 1]. If > `0` then smooth the labels. **kwargs: other params.
- def call(self, y_true, y_pred): Compute focal loss for y and y_pred. Args: y: A tuple of (normalizer, y_true), where y_true is the target class. y_pred: A float32 tensor [batch, height_in, width_in, num_predictions]. Returns: the focal loss.

<|skeleton|>
class ClassFocalLoss:
    """Compute the focal loss between `logits` and the golden `target` values. Focal loss = -(1-pt)^gamma * log(pt) where pt is the probability of being classified to the true class."""

    def __init__(self, alpha, gamma, label_smoothing=0.0, **kwargs):
        """Initialize focal loss. Args: alpha: A float32 scalar multiplying alpha to the loss from positive examples and (1-alpha) to the loss from negative examples. gamma: A float32 scalar modulating loss from hard and easy examples. label_smoothing: Float in [0, 1]. If > `0` then smooth the labels. **kwargs: other params."""
        <|body_0|>

    def call(self, y_true, y_pred):
        """Compute focal loss for y and y_pred. Args: y: A tuple of (normalizer, y_true), where y_true is the target class. y_pred: A float32 tensor [batch, height_in, width_in, num_predictions]. Returns: the focal loss."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        super().__init__(**kwargs)
        self.alpha = alpha
        self.gamma = gamma
        self.label_smoothing = label_smoothing
<|end_body_0|>

<|body_start_1|>
        class_targets = y_true
        class_outputs, mask = y_pred
        alpha = tf.convert_to_tensor(self.alpha, dtype=y_pred[0][0].dtype)
        gamma = tf.convert_to_tensor(self.gamma, dtype=y_pred[0][0].dtype)
        total_loss = 0
        for i in range(len(class_targets)):
            mask_one = tf.cast(mask[i], dtype=tf.float32)
            class_targets_one = class_targets[i]
            class_outputs_one = class_outputs[i]
            normalizer = tf.reduce_sum(mask_one) / tf.cast(tf.shape(mask_one)[0], tf.float32)
            pred_prob = tf.sigmoid(class_outputs_one)
            p_t = class_targets_one * pred_prob + (1 - class_targets_one) * (1 - pred_prob)
            alpha_factor = class_targets_one * alpha + (1 - class_targets_one) * (1 - alpha)
            modulating_factor = (1.0 - p_t) ** gamma
            class_targets_one = class_targets_one * (1.0 - self.label_smoothing) + 0.5 * self.label_smoothing
            ce = tf.nn.sigmoid_cross_entropy_with_logits(labels=class_targets_one, logits=class_outputs_one)
            total_loss += tf.reduce_sum(tf.math.divide_no_nan(alpha_factor * modulating_factor * ce, normalizer))
        return total_loss
<|end_body_1|>

Solution:
class ClassFocalLoss:
    """Compute the focal loss between `logits` and the golden `target` values. Focal loss = -(1-pt)^gamma * log(pt) where pt is the probability of being classified to the true class."""

    def __init__(self, alpha, gamma, label_smoothing=0.0, **kwargs):
        """Initialize focal loss. Args: alpha: A float32 scalar multiplying alpha to the loss from positive examples and (1-alpha) to the loss from negative examples. gamma: A float32 scalar modulating loss from hard and easy examples. label_smoothing: Float in [0, 1]. If > `0` then smooth the labels. **kwargs: other params."""
        super().__init__(**kwargs)
        self.alpha = alpha
        self.gamma = gamma
        self.label_smoothing = label_smoothing

    def call(self, y_true, y_pred):
        """Compute focal loss for y and y_pred. Args: y: A tuple of (normalizer, y_true), where y_true is the target class. y_pred: A float32 tensor [batch, height_in, width_in, num_predictions]. Returns: the focal loss."""
        class_targets = y_true
        class_outputs, mask = y_pred
        alpha = tf.convert_to_tensor(self.alpha, dtype=y_pred[0][0].dtype)
        gamma = tf.convert_to_tensor(self.gamma, dtype=y_pred[0][0].dtype)
        total_loss = 0
        for i in range(len(class_targets)):
            mask_one = tf.cast(mask[i], dtype=tf.float32)
            class_targets_one = class_targets[i]
            class_outputs_one = class_outputs[i]
            normalizer = tf.reduce_sum(mask_one) / tf.cast(tf.shape(mask_one)[0], tf.float32)
            pred_prob = tf.sigmoid(class_outputs_one)
            p_t = class_targets_one * pred_prob + (1 - class_targets_one) * (1 - pred_prob)
            alpha_factor = class_targets_one * alpha + (1 - class_targets_one) * (1 - alpha)
            modulating_factor = (1.0 - p_t) ** gamma
            class_targets_one = class_targets_one * (1.0 - self.label_smoothing) + 0.5 * self.label_smoothing
            ce = tf.nn.sigmoid_cross_entropy_with_logits(labels=class_targets_one, logits=class_outputs_one)
            total_loss += tf.reduce_sum(tf.math.divide_no_nan(alpha_factor * modulating_factor * ce, normalizer))
        return total_loss


forward

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

Class description:
Class LSTMCell that represents an LSTM unit

Method signatures and docstrings:
- def __init__(self, i, h, o): class constructor Argumetns: - i is the dimensionality of the data - h is the dimensionality of the hidden state - o is the dimensionality of the outputs Public instance attributes Wf, Wu, Wc, Wo, Wy, bf, bu, bc, bo, by that represent the weights and biases of the cell - Wf and bf are for the forget gate - Wu and bu are for the update gate - Wc and bc are for the intermediate cell state - Wo and bo are for the output gate - Wy and by are for the outputs
- def softmax(self, x): Function to compute softmax values for each sets of scores in x
- def forward(self, h_prev, c_prev, x_t): Public instance method that performs forward propagation for one time step Arguments: - x_t is a numpy.ndarray of shape (m, i) that contains the data input for the cell * m is the batche size for the data - h_prev is a numpy.ndarray of shape (m, h) containing the previous hidden state - c_prev is a numpy.ndarray of shape (m, h) containing the previous cell state Returns: h_next, c_next, y - h_next is the next hidden state - c_next is the next cell state - y is the output of the cell

Implement the Python class `LSTMCell` described below.

Class description:
Class LSTMCell that represents an LSTM unit

Method signatures and docstrings:
- def __init__(self, i, h, o): class constructor Argumetns: - i is the dimensionality of the data - h is the dimensionality of the hidden state - o is the dimensionality of the outputs Public instance attributes Wf, Wu, Wc, Wo, Wy, bf, bu, bc, bo, by that represent the weights and biases of the cell - Wf and bf are for the forget gate - Wu and bu are for the update gate - Wc and bc are for the intermediate cell state - Wo and bo are for the output gate - Wy and by are for the outputs
- def softmax(self, x): Function to compute softmax values for each sets of scores in x
- def forward(self, h_prev, c_prev, x_t): Public instance method that performs forward propagation for one time step Arguments: - x_t is a numpy.ndarray of shape (m, i) that contains the data input for the cell * m is the batche size for the data - h_prev is a numpy.ndarray of shape (m, h) containing the previous hidden state - c_prev is a numpy.ndarray of shape (m, h) containing the previous cell state Returns: h_next, c_next, y - h_next is the next hidden state - c_next is the next cell state - y is the output of the cell

<|skeleton|>
class LSTMCell:
    """Class LSTMCell that represents an LSTM unit"""

    def __init__(self, i, h, o):
        """class constructor Argumetns: - i is the dimensionality of the data - h is the dimensionality of the hidden state - o is the dimensionality of the outputs Public instance attributes Wf, Wu, Wc, Wo, Wy, bf, bu, bc, bo, by that represent the weights and biases of the cell - Wf and bf are for the forget gate - Wu and bu are for the update gate - Wc and bc are for the intermediate cell state - Wo and bo are for the output gate - Wy and by are for the outputs"""
        <|body_0|>

    def softmax(self, x):
        """Function to compute softmax values for each sets of scores in x"""
        <|body_1|>

    def forward(self, h_prev, c_prev, x_t):
        """Public instance method that performs forward propagation for one time step Arguments: - x_t is a numpy.ndarray of shape (m, i) that contains the data input for the cell * m is the batche size for the data - h_prev is a numpy.ndarray of shape (m, h) containing the previous hidden state - c_prev is a numpy.ndarray of shape (m, h) containing the previous cell state Returns: h_next, c_next, y - h_next is the next hidden state - c_next is the next cell state - y is the output of the cell"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        self.Wf = np.random.normal(size=(h + i, h))
        self.Wu = np.random.normal(size=(h + i, h))
        self.Wc = np.random.normal(size=(h + i, h))
        self.Wo = np.random.normal(size=(h + i, h))
        self.Wy = np.random.normal(size=(h, o))
        self.bf = np.zeros((1, h))
        self.bu = np.zeros((1, h))
        self.bc = np.zeros((1, h))
        self.bo = np.zeros((1, h))
        self.by = np.zeros((1, o))
<|end_body_0|>

<|body_start_1|>
        x_max = np.max(x, axis=1, keepdims=True)
        e_x = np.exp(x - x_max)
        return e_x / np.sum(e_x, axis=1, keepdims=True)
<|end_body_1|>

<|body_start_2|>
        matrix = np.concatenate((h_prev, x_t), axis=1)
        u_t = sigmoid(np.matmul(matrix, self.Wu) + self.bu)
        f_t = sigmoid(np.matmul(matrix, self.Wf) + self.bf)
        o_t = sigmoid(np.matmul(matrix, self.Wo) + self.bo)
        prime_c = np.tanh(np.matmul(matrix, self.Wc) + self.bc)
        c_next = f_t * c_prev + u_t * prime_c
        h_next = o_t * np.tanh(c_next)
        y = self.softmax(np.matmul(h_next, self.Wy) + self.by)
        return (h_next, c_next, y)
<|end_body_2|>

Solution:
class LSTMCell:
    """Class LSTMCell that represents an LSTM unit"""

    def __init__(self, i, h, o):
        """class constructor Argumetns: - i is the dimensionality of the data - h is the dimensionality of the hidden state - o is the dimensionality of the outputs Public instance attributes Wf, Wu, Wc, Wo, Wy, bf, bu, bc, bo, by that represent the weights and biases of the cell - Wf and bf are for the forget gate - Wu and bu are for the update gate - Wc and bc are for the intermediate cell state - Wo and bo are for the output gate - Wy and by are for the outputs"""
        self.Wf = np.random.normal(size=(h + i, h))
        self.Wu = np.random.normal(size=(h + i, h))
        self.Wc = np.random.normal(size=(h + i, h))
        self.Wo = np.random.normal(size=(h + i, h))
        self.Wy = np.random.normal(size=(h, o))
        self.bf = np.zeros((1, h))
        self.bu = np.zeros((1, h))
        self.bc = np.zeros((1, h))
        self.bo = np.zeros((1, h))
        self.by = np.zeros((1, o))

    def softmax(self, x):
        """Function to compute softmax values for each sets of scores in x"""
        x_max = np.max(x, axis=1, keepdims=True)
        e_x = np.exp(x - x_max)
        return e_x / np.sum(e_x, axis=1, keepdims=True)

    def forward(self, h_prev, c_prev, x_t):
        """Public instance method that performs forward propagation for one time step Arguments: - x_t is a numpy.ndarray of shape (m, i) that contains the data input for the cell * m is the batche size for the data - h_prev is a numpy.ndarray of shape (m, h) containing the previous hidden state - c_prev is a numpy.ndarray of shape (m, h) containing the previous cell state Returns: h_next, c_next, y - h_next is the next hidden state - c_next is the next cell state - y is the output of the cell"""
        matrix = np.concatenate((h_prev, x_t), axis=1)
        u_t = sigmoid(np.matmul(matrix, self.Wu) + self.bu)
        f_t = sigmoid(np.matmul(matrix, self.Wf) + self.bf)
        o_t = sigmoid(np.matmul(matrix, self.Wo) + self.bo)
        prime_c = np.tanh(np.matmul(matrix, self.Wc) + self.bc)
        c_next = f_t * c_prev + u_t * prime_c
        h_next = o_t * np.tanh(c_next)
        y = self.softmax(np.matmul(h_next, self.Wy) + self.by)
        return (h_next, c_next, y)


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

Class description:
Provides an event loop for running events.

Method signatures and docstrings:
- def __init__(self) -> None: Creates a EventLoop instance.
- def _run_events(self) -> None: Run events. :return: nothing
- def _schedule_event(self) -> None: Schedule event. :return: nothing
- def run(self) -> None: Start event loop. :return: nothing
- def stop(self) -> None: Stop event loop. :return: nothing
- def add_event(self, delaysec: float, func: Callable, *args: Any, **kwds: Any): Add an event to the event loop. :param delaysec: delay in seconds for event :param func: event function :param args: event arguments :param kwds: event keyword arguments :return: created event

Implement the Python class `EventLoop` described below.

Class description:
Provides an event loop for running events.

Method signatures and docstrings:
- def __init__(self) -> None: Creates a EventLoop instance.
- def _run_events(self) -> None: Run events. :return: nothing
- def _schedule_event(self) -> None: Schedule event. :return: nothing
- def run(self) -> None: Start event loop. :return: nothing
- def stop(self) -> None: Stop event loop. :return: nothing
- def add_event(self, delaysec: float, func: Callable, *args: Any, **kwds: Any): Add an event to the event loop. :param delaysec: delay in seconds for event :param func: event function :param args: event arguments :param kwds: event keyword arguments :return: created event

<|skeleton|>
class EventLoop:
    """Provides an event loop for running events."""

    def __init__(self) -> None:
        """Creates a EventLoop instance."""
        <|body_0|>

    def _run_events(self) -> None:
        """Run events. :return: nothing"""
        <|body_1|>

    def _schedule_event(self) -> None:
        """Schedule event. :return: nothing"""
        <|body_2|>

    def run(self) -> None:
        """Start event loop. :return: nothing"""
        <|body_3|>

    def stop(self) -> None:
        """Stop event loop. :return: nothing"""
        <|body_4|>

    def add_event(self, delaysec: float, func: Callable, *args: Any, **kwds: Any):
        """Add an event to the event loop. :param delaysec: delay in seconds for event :param func: event function :param args: event arguments :param kwds: event keyword arguments :return: created event"""
        <|body_5|>

<|end_skeleton|>

<|body_start_0|>
        self.lock: threading.RLock = threading.RLock()
        self.queue: list[Event] = []
        self.eventnum: int = 0
        self.timer: Optional[Timer] = None
        self.running: bool = False
        self.start: Optional[float] = None
<|end_body_0|>

<|body_start_1|>
        schedule = False
        while True:
            with self.lock:
                if not self.running or not self.queue:
                    break
                now = time.monotonic()
                if self.queue[0].time > now:
                    schedule = True
                    break
                event = heapq.heappop(self.queue)
            if event.time > now:
                raise ValueError('invalid event time: %s > %s', event.time, now)
            event.run()
        with self.lock:
            self.timer = None
            if schedule:
                self._schedule_event()
<|end_body_1|>

<|body_start_2|>
        with self.lock:
            if not self.running:
                raise ValueError('scheduling event while not running')
            if not self.queue:
                return
            delay = self.queue[0].time - time.monotonic()
            if self.timer:
                raise ValueError('timer was already set')
            self.timer = Timer(delay, self._run_events)
            self.timer.daemon = True
            self.timer.start()
<|end_body_2|>

<|body_start_3|>
        with self.lock:
            if self.running:
                return
            self.running = True
            self.start = time.monotonic()
            for event in self.queue:
                event.time += self.start
            self._schedule_event()
<|end_body_3|>

<|body_start_4|>
        with self.lock:
            if not self.running:
                return
            self.queue = []
            self.eventnum = 0
            if self.timer is not None:
                self.timer.cancel()
                self.timer = None
            self.running = False
            self.start = None
<|end_body_4|>

<|body_start_5|>
        with self.lock:
            eventnum = self.eventnum
            self.eventnum += 1
            evtime = float(delaysec)
            if self.running:
                evtime += time.monotonic()
            event = Event(eventnum, evtime, func, *args, **kwds)
            if self.queue:
                prevhead = self.queue[0]
            else:
                prevhead = None
            heapq.heappush(self.queue, event)
            head = self.queue[0]
            if prevhead is not None and prevhead != head:
                if self.timer is not None and self.timer.cancel():
                    self.timer = None
            if self.running and self.timer is None:
                self._schedule_event()
        return event
<|end_body_5|>

Solution:
class EventLoop:
    """Provides an event loop for running events."""

    def __init__(self) -> None:
        """Creates a EventLoop instance."""
        self.lock: threading.RLock = threading.RLock()
        self.queue: list[Event] = []
        self.eventnum: int = 0
        self.timer: Optional[Timer] = None
        self.running: bool = False
        self.start: Optional[float] = None

    def _run_events(self) -> None:
        """Run events. :return: nothing"""
        schedule = False
        while True:
            with self.lock:
                if not self.running or not self.queue:
                    break
                now = time.monotonic()
                if self.queue[0].time > now:
                    schedule = True
                    break
                event = heapq.heappop(self.queue)
            if event.time > now:
                raise ValueError('invalid event time: %s > %s', event.time, now)
            event.run()
        with self.lock:
            self.timer = None
            if schedule:
                self._schedule_event()

    def _schedule_event(self) -> None:
        """Schedule event. :return: nothing"""
        with self.lock:
            if not self.running:
                raise ValueError('scheduling event while not running')
            if not self.queue:
                return
            delay = self.queue[0].time - time.monotonic()
            if self.timer:
                raise ValueError('timer was already set')
            self.timer = Timer(delay, self._run_events)
            self.timer.daemon = True
            self.timer.start()

    def run(self) -> None:
        """Start event loop. :return: nothing"""
        with self.lock:
            if self.running:
                return
            self.running = True
            self.start = time.monotonic()
            for event in self.queue:
                event.time += self.start
            self._schedule_event()

    def stop(self) -> None:
        """Stop event loop. :return: nothing"""
        with self.lock:
            if not self.running:
                return
            self.queue = []
            self.eventnum = 0
            if self.timer is not None:
                self.timer.cancel()
                self.timer = None
            self.running = False
            self.start = None

    def add_event(self, delaysec: float, func: Callable, *args: Any, **kwds: Any):
        """Add an event to the event loop. :param delaysec: delay in seconds for event :param func: event function :param args: event arguments :param kwds: event keyword arguments :return: created event"""
        with self.lock:
            eventnum = self.eventnum
            self.eventnum += 1
            evtime = float(delaysec)
            if self.running:
                evtime += time.monotonic()
            event = Event(eventnum, evtime, func, *args, **kwds)
            if self.queue:
                prevhead = self.queue[0]
            else:
                prevhead = None
            heapq.heappush(self.queue, event)
            head = self.queue[0]
            if prevhead is not None and prevhead != head:
                if self.timer is not None and self.timer.cancel():
                    self.timer = None
            if self.running and self.timer is None:
                self._schedule_event()
        return event


deserialize

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

Class description:
Implement the Codec class.

Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: TreeNode

Implement the Python class `Codec` described below.

Class description:
Implement the Codec class.

Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: TreeNode

<|skeleton|>
class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
        <|body_0|>

    def deserialize(self, data):
        """Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        queue = deque()
        queue.append(root)
        seq = ''
        while queue:
            for _ in range(len(queue)):
                node = queue.popleft()
                if not node:
                    seq += ',#'
                elif not seq:
                    seq += f'{node.val}'
                else:
                    seq += f',{node.val}'
                if node:
                    queue.append(node.left)
                    queue.append(node.right)
        return seq
<|end_body_0|>

<|body_start_1|>
        serial = data.split(',')
        print(data)
        if serial[0] == '':
            return None
        root = TreeNode(serial[0])
        queue = deque()
        queue.append(root)
        i = 0
        while i + 1 < len(serial):
            node = queue.popleft()
            left = serial[i + 1]
            i += 1
            if left != '#':
                node.left = TreeNode(left)
                queue.append(node.left)
            right = serial[i + 1]
            i += 1
            if right != '#':
                node.right = TreeNode(right)
                queue.append(node.right)
        return root
<|end_body_1|>

Solution:
class Codec:
    def serialize(self, root):
        """Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
        queue = deque()
        queue.append(root)
        seq = ''
        while queue:
            for _ in range(len(queue)):
                node = queue.popleft()
                if not node:
                    seq += ',#'
                elif not seq:
                    seq += f'{node.val}'
                else:
                    seq += f',{node.val}'
                if node:
                    queue.append(node.left)
                    queue.append(node.right)
        return seq

    def deserialize(self, data):
        """Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
        serial = data.split(',')
        print(data)
        if serial[0] == '':
            return None
        root = TreeNode(serial[0])
        queue = deque()
        queue.append(root)
        i = 0
        while i + 1 < len(serial):
            node = queue.popleft()
            left = serial[i + 1]
            i += 1
            if left != '#':
                node.left = TreeNode(left)
                queue.append(node.left)
            right = serial[i + 1]
            i += 1
            if right != '#':
                node.right = TreeNode(right)
                queue.append(node.right)
        return root


cdf

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

Class description:
Binomial class

Method signatures and docstrings:
- def __init__(self, data=None, n=1, p=0.5): Class constructor
- def factorial(n): Calculates the factorial of a given number
- def pmf(self, k): Calculates the value of the PMF for a given number of “successes”
- def cdf(self, k): Calculates the value of the CDF for a given number of “successes”

Implement the Python class `Binomial` described below.

Class description:
Binomial class

Method signatures and docstrings:
- def __init__(self, data=None, n=1, p=0.5): Class constructor
- def factorial(n): Calculates the factorial of a given number
- def pmf(self, k): Calculates the value of the PMF for a given number of “successes”
- def cdf(self, k): Calculates the value of the CDF for a given number of “successes”

<|skeleton|>
class Binomial:
    """Binomial class"""

    def __init__(self, data=None, n=1, p=0.5):
        """Class constructor"""
        <|body_0|>

    def factorial(n):
        """Calculates the factorial of a given number"""
        <|body_1|>

    def pmf(self, k):
        """Calculates the value of the PMF for a given number of “successes”"""
        <|body_2|>

    def cdf(self, k):
        """Calculates the value of the CDF for a given number of “successes”"""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        if data is not None:
            if not isinstance(data, list):
                raise TypeError('data must be a list')
            if len(data) <= 2:
                raise ValueError('data must contain multiple values')
            mean = sum(data) / len(data)
            variance = 0
            for x in data:
                variance += (x - mean) ** 2
            variance = variance / len(data)
            p = 1 - variance / mean
            self.n = int(round(mean / p))
            self.p = float(mean / self.n)
        else:
            if n <= 0:
                raise ValueError('n must be a positive value')
            self.n = int(n)
            if p <= 0 or p >= 1:
                raise ValueError('p must be greater than 0 and less than 1')
            self.p = float(p)
<|end_body_0|>

<|body_start_1|>
        factorial_num = 1
        for m in range(1, n + 1):
            factorial_num *= m
        return factorial_num
<|end_body_1|>

<|body_start_2|>
        k = int(k)
        if k < 0 or k > self.n:
            return 0
        n_factorial = self.factorial(self.n)
        k_factorial = self.factorial(k)
        nk_factorial = self.factorial(self.n - k)
        binomial_coefficient = n_factorial / (nk_factorial * k_factorial)
        q = 1 - self.p
        return binomial_coefficient * (self.p ** k * q ** (self.n - k))
<|end_body_2|>

<|body_start_3|>
        k = int(k)
        if k < 0:
            return 0
        cdf = 0
        for x in range(k + 1):
            cdf += self.pmf(x)
        return cdf
<|end_body_3|>

Solution:
class Binomial:
    """Binomial class"""

    def __init__(self, data=None, n=1, p=0.5):
        """Class constructor"""
        if data is not None:
            if not isinstance(data, list):
                raise TypeError('data must be a list')
            if len(data) <= 2:
                raise ValueError('data must contain multiple values')
            mean = sum(data) / len(data)
            variance = 0
            for x in data:
                variance += (x - mean) ** 2
            variance = variance / len(data)
            p = 1 - variance / mean
            self.n = int(round(mean / p))
            self.p = float(mean / self.n)
        else:
            if n <= 0:
                raise ValueError('n must be a positive value')
            self.n = int(n)
            if p <= 0 or p >= 1:
                raise ValueError('p must be greater than 0 and less than 1')
            self.p = float(p)

    def factorial(n):
        """Calculates the factorial of a given number"""
        factorial_num = 1
        for m in range(1, n + 1):
            factorial_num *= m
        return factorial_num

    def pmf(self, k):
        """Calculates the value of the PMF for a given number of “successes”"""
        k = int(k)
        if k < 0 or k > self.n:
            return 0
        n_factorial = self.factorial(self.n)
        k_factorial = self.factorial(k)
        nk_factorial = self.factorial(self.n - k)
        binomial_coefficient = n_factorial / (nk_factorial * k_factorial)
        q = 1 - self.p
        return binomial_coefficient * (self.p ** k * q ** (self.n - k))

    def cdf(self, k):
        """Calculates the value of the CDF for a given number of “successes”"""
        k = int(k)
        if k < 0:
            return 0
        cdf = 0
        for x in range(k + 1):
            cdf += self.pmf(x)
        return cdf


subsets

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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def subsets(self, nums): Use binary to implement. :type nums: List[int] :rtype: List[List[int]]
- def subsets(self, nums): DFS :type nums: List[int] :rtype: List[List[int]]

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def subsets(self, nums): Use binary to implement. :type nums: List[int] :rtype: List[List[int]]
- def subsets(self, nums): DFS :type nums: List[int] :rtype: List[List[int]]

<|skeleton|>
class Solution:

    def subsets(self, nums):
        """Use binary to implement. :type nums: List[int] :rtype: List[List[int]]"""
        <|body_0|>

    def subsets(self, nums):
        """DFS :type nums: List[int] :rtype: List[List[int]]"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        res_lst = []
        for x in range(1 << len(nums)):
            subset = []
            pow_2 = 1
            for i in range(len(nums)):
                if x & pow_2 > 0:
                    subset.append(nums[i])
                pow_2 <<= 1
            res_lst.append(subset)
        return res_lst
<|end_body_0|>

<|body_start_1|>
        res_lst = []

        def dfs(index, subset):
            if index >= len(nums):
                res_lst.append(subset)
                return
            dfs(index + 1, subset)
            dfs(index + 1, subset + [nums[index]])
        dfs(0, [])
        return res_lst
<|end_body_1|>

Solution:
class Solution:
    def subsets(self, nums):
        """Use binary to implement. :type nums: List[int] :rtype: List[List[int]]"""
        res_lst = []
        for x in range(1 << len(nums)):
            subset = []
            pow_2 = 1
            for i in range(len(nums)):
                if x & pow_2 > 0:
                    subset.append(nums[i])
                pow_2 <<= 1
            res_lst.append(subset)
        return res_lst

    def subsets(self, nums):
        """DFS :type nums: List[int] :rtype: List[List[int]]"""
        res_lst = []

        def dfs(index, subset):
            if index >= len(nums):
                res_lst.append(subset)
                return
            dfs(index + 1, subset)
            dfs(index + 1, subset + [nums[index]])
        dfs(0, [])
        return res_lst


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

Class description:
Implement the PullBaseImagePlugin class.

Method signatures and docstrings:
- def __init__(self, tasker, workflow, parent_registry=None, parent_registry_insecure=False): constructor :param tasker: DockerTasker instance :param workflow: DockerBuildWorkflow instance :param parent_registry: registry to enforce pulling from :param parent_registry_insecure: allow connecting to the registry over plain http
- def run(self): pull base image

Implement the Python class `PullBaseImagePlugin` described below.

Class description:
Implement the PullBaseImagePlugin class.

Method signatures and docstrings:
- def __init__(self, tasker, workflow, parent_registry=None, parent_registry_insecure=False): constructor :param tasker: DockerTasker instance :param workflow: DockerBuildWorkflow instance :param parent_registry: registry to enforce pulling from :param parent_registry_insecure: allow connecting to the registry over plain http
- def run(self): pull base image

<|skeleton|>
class PullBaseImagePlugin:

    def __init__(self, tasker, workflow, parent_registry=None, parent_registry_insecure=False):
        """constructor :param tasker: DockerTasker instance :param workflow: DockerBuildWorkflow instance :param parent_registry: registry to enforce pulling from :param parent_registry_insecure: allow connecting to the registry over plain http"""
        <|body_0|>

    def run(self):
        """pull base image"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        super(PullBaseImagePlugin, self).__init__(tasker, workflow)
        self.parent_registry = parent_registry
        self.parent_registry_insecure = parent_registry_insecure
<|end_body_0|>

<|body_start_1|>
        base_image = self.workflow.builder.base_image
        self.log.info("pulling base image '%s' from registry '%s'", base_image, self.parent_registry)
        base_image_with_registry = base_image.copy()
        if self.parent_registry:
            if base_image.registry and base_image.registry != self.parent_registry:
                self.log.error("registry in dockerfile doesn't match provided source registry, dockerfile = '%s', provided = '%s'", base_image.registry, self.parent_registry)
                raise RuntimeError("Registry specified in dockerfile doesn't match provided one. Dockerfile: '%s', Provided: '%s'" % (base_image.registry, self.parent_registry))
            base_image_with_registry.registry = self.parent_registry
        pulled_base = self.tasker.pull_image(base_image_with_registry, insecure=self.parent_registry_insecure)
        self.workflow.pulled_base_images.add(pulled_base)
        if not base_image.registry:
            response = self.tasker.tag_image(base_image_with_registry, base_image, force=True)
            self.workflow.pulled_base_images.add(response)
            pulled_base = response
        self.log.debug("image '%s' is available", pulled_base)
<|end_body_1|>

Solution:
class PullBaseImagePlugin:
    def __init__(self, tasker, workflow, parent_registry=None, parent_registry_insecure=False):
        """constructor :param tasker: DockerTasker instance :param workflow: DockerBuildWorkflow instance :param parent_registry: registry to enforce pulling from :param parent_registry_insecure: allow connecting to the registry over plain http"""
        super(PullBaseImagePlugin, self).__init__(tasker, workflow)
        self.parent_registry = parent_registry
        self.parent_registry_insecure = parent_registry_insecure

    def run(self):
        """pull base image"""
        base_image = self.workflow.builder.base_image
        self.log.info("pulling base image '%s' from registry '%s'", base_image, self.parent_registry)
        base_image_with_registry = base_image.copy()
        if self.parent_registry:
            if base_image.registry and base_image.registry != self.parent_registry:
                self.log.error("registry in dockerfile doesn't match provided source registry, dockerfile = '%s', provided = '%s'", base_image.registry, self.parent_registry)
                raise RuntimeError("Registry specified in dockerfile doesn't match provided one. Dockerfile: '%s', Provided: '%s'" % (base_image.registry, self.parent_registry))
            base_image_with_registry.registry = self.parent_registry
        pulled_base = self.tasker.pull_image(base_image_with_registry, insecure=self.parent_registry_insecure)
        self.workflow.pulled_base_images.add(pulled_base)
        if not base_image.registry:
            response = self.tasker.tag_image(base_image_with_registry, base_image, force=True)
            self.workflow.pulled_base_images.add(response)
            pulled_base = response
        self.log.debug("image '%s' is available", pulled_base)


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

Class description:
Implement the CartesianTriangle class.

Method signatures and docstrings:
- def __init__(self, pt_3d_1, pt_3d_2, pt_3d_3): :param pt_3d_1: :param pt_3d_2: :param pt_3d_3:
- def is_pt_within(self, pt_3d): :param pt_3d: :return:

Implement the Python class `CartesianTriangle` described below.

Class description:
Implement the CartesianTriangle class.

Method signatures and docstrings:
- def __init__(self, pt_3d_1, pt_3d_2, pt_3d_3): :param pt_3d_1: :param pt_3d_2: :param pt_3d_3:
- def is_pt_within(self, pt_3d): :param pt_3d: :return:

<|skeleton|>
class CartesianTriangle:

    def __init__(self, pt_3d_1, pt_3d_2, pt_3d_3):
        """:param pt_3d_1: :param pt_3d_2: :param pt_3d_3:"""
        <|body_0|>

    def is_pt_within(self, pt_3d):
        """:param pt_3d: :return:"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self._pt_1 = pt_3d_1
        self._pt_2 = pt_3d_2
        self._pt_3 = pt_3d_3
<|end_body_0|>

<|body_start_1|>
        def versor3d(pt_1, pt_2):
            """

                    :param pt_1:
                    :param pt_2:
                    :return:
                    """
            return Segment(pt_1, pt_2).vector().versor_full()

        def is_pt_in_fascio(pt_1, pt_2, pt_3):
            """

                    :param pt_1:
                    :param pt_2:
                    :param pt_3:
                    :return:
                    """
            apex = pt_1
            versor_1 = versor3d(pt_1, pt_2)
            versor_2 = versor3d(pt_1, pt_3)
            fascio = TriangBeam(apex, versor_1, versor_2)
            if not fascio.is_within_fascio(pt_3d):
                return False
            else:
                return True
        if not (is_pt_in_fascio(self._pt_1, self._pt_2, self._pt_3) and is_pt_in_fascio(self._pt_2, self._pt_1, self._pt_3)):
            return False
        else:
            return True
<|end_body_1|>

Solution:
class CartesianTriangle:
    def __init__(self, pt_3d_1, pt_3d_2, pt_3d_3):
        """:param pt_3d_1: :param pt_3d_2: :param pt_3d_3:"""
        self._pt_1 = pt_3d_1
        self._pt_2 = pt_3d_2
        self._pt_3 = pt_3d_3

    def is_pt_within(self, pt_3d):
        """:param pt_3d: :return:"""
        def versor3d(pt_1, pt_2):
            """

                    :param pt_1:
                    :param pt_2:
                    :return:
                    """
            return Segment(pt_1, pt_2).vector().versor_full()

        def is_pt_in_fascio(pt_1, pt_2, pt_3):
            """

                    :param pt_1:
                    :param pt_2:
                    :param pt_3:
                    :return:
                    """
            apex = pt_1
            versor_1 = versor3d(pt_1, pt_2)
            versor_2 = versor3d(pt_1, pt_3)
            fascio = TriangBeam(apex, versor_1, versor_2)
            if not fascio.is_within_fascio(pt_3d):
                return False
            else:
                return True
        if not (is_pt_in_fascio(self._pt_1, self._pt_2, self._pt_3) and is_pt_in_fascio(self._pt_2, self._pt_1, self._pt_3)):
            return False
        else:
            return True


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

Class description:
Implement the ProcessSubscriptionTests class.

Method signatures and docstrings:
- def test_channel_prefer_whatsapp(self): Should set the channel, but never overwrite WhatsApp with SMS
- def test_subscription_types(self): Should add to the subscription list depending on the name

Implement the Python class `ProcessSubscriptionTests` described below.

Class description:
Implement the ProcessSubscriptionTests class.

Method signatures and docstrings:
- def test_channel_prefer_whatsapp(self): Should set the channel, but never overwrite WhatsApp with SMS
- def test_subscription_types(self): Should add to the subscription list depending on the name

<|skeleton|>
class ProcessSubscriptionTests:

    def test_channel_prefer_whatsapp(self):
        """Should set the channel, but never overwrite WhatsApp with SMS"""
        <|body_0|>

    def test_subscription_types(self):
        """Should add to the subscription list depending on the name"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        identities = {'identity-uuid': {'uuid': 'identity-uuid'}}
        timestamp = datetime.datetime(2020, 1, 1)
        process_subscription(identities, 'identity-uuid', 'momconnect', timestamp)
        self.assertEqual(identities, {'identity-uuid': {'uuid': 'identity-uuid', 'channel': 'SMS'}})
        process_subscription(identities, 'identity-uuid', 'whatsapp_momconnect', timestamp)
        self.assertEqual(identities, {'identity-uuid': {'uuid': 'identity-uuid', 'channel': 'WhatsApp'}})
        process_subscription(identities, 'identity-uuid', 'momconnect', timestamp)
        self.assertEqual(identities, {'identity-uuid': {'uuid': 'identity-uuid', 'channel': 'WhatsApp'}})
<|end_body_0|>

<|body_start_1|>
        identities = {'identity-uuid': {'uuid': 'identity-uuid'}}
        timestamp = datetime.datetime(2020, 1, 1)
        process_subscription(identities, 'identity-uuid', 'pmtct_prebirth.hw_full.1', timestamp)
        self.assertEqual(identities['identity-uuid']['pmtct_messaging'], 'TRUE')
        process_subscription(identities, 'identity-uuid', 'loss_miscarriage.patient.1', timestamp)
        self.assertEqual(identities['identity-uuid']['loss_messaging'], 'TRUE')
        self.assertEqual(identities['identity-uuid']['optout_reason'], 'miscarriage')
        self.assertEqual(identities['identity-uuid']['optout_timestamp'], '2020-01-01T00:00:00')
        process_subscription(identities, 'identity-uuid', 'momconnect_prebirth.hw_partial.1', timestamp)
        self.assertEqual(identities['identity-uuid']['public_messaging'], 'TRUE')
        self.assertEqual(identities['identity-uuid']['public_registration_date'], '2020-01-01T00:00:00')
        process_subscription(identities, 'identity-uuid', 'momconnect_prebirth.hw_full.3', timestamp)
        self.assertEqual(identities['identity-uuid']['prebirth_messaging'], '3')
        process_subscription(identities, 'identity-uuid', 'momconnect_postbirth.hw_full.2', timestamp)
        self.assertEqual(identities['identity-uuid']['postbirth_messaging'], 'TRUE')
<|end_body_1|>

Solution:
class ProcessSubscriptionTests:
    def test_channel_prefer_whatsapp(self):
        """Should set the channel, but never overwrite WhatsApp with SMS"""
        identities = {'identity-uuid': {'uuid': 'identity-uuid'}}
        timestamp = datetime.datetime(2020, 1, 1)
        process_subscription(identities, 'identity-uuid', 'momconnect', timestamp)
        self.assertEqual(identities, {'identity-uuid': {'uuid': 'identity-uuid', 'channel': 'SMS'}})
        process_subscription(identities, 'identity-uuid', 'whatsapp_momconnect', timestamp)
        self.assertEqual(identities, {'identity-uuid': {'uuid': 'identity-uuid', 'channel': 'WhatsApp'}})
        process_subscription(identities, 'identity-uuid', 'momconnect', timestamp)
        self.assertEqual(identities, {'identity-uuid': {'uuid': 'identity-uuid', 'channel': 'WhatsApp'}})

    def test_subscription_types(self):
        """Should add to the subscription list depending on the name"""
        identities = {'identity-uuid': {'uuid': 'identity-uuid'}}
        timestamp = datetime.datetime(2020, 1, 1)
        process_subscription(identities, 'identity-uuid', 'pmtct_prebirth.hw_full.1', timestamp)
        self.assertEqual(identities['identity-uuid']['pmtct_messaging'], 'TRUE')
        process_subscription(identities, 'identity-uuid', 'loss_miscarriage.patient.1', timestamp)
        self.assertEqual(identities['identity-uuid']['loss_messaging'], 'TRUE')
        self.assertEqual(identities['identity-uuid']['optout_reason'], 'miscarriage')
        self.assertEqual(identities['identity-uuid']['optout_timestamp'], '2020-01-01T00:00:00')
        process_subscription(identities, 'identity-uuid', 'momconnect_prebirth.hw_partial.1', timestamp)
        self.assertEqual(identities['identity-uuid']['public_messaging'], 'TRUE')
        self.assertEqual(identities['identity-uuid']['public_registration_date'], '2020-01-01T00:00:00')
        process_subscription(identities, 'identity-uuid', 'momconnect_prebirth.hw_full.3', timestamp)
        self.assertEqual(identities['identity-uuid']['prebirth_messaging'], '3')
        process_subscription(identities, 'identity-uuid', 'momconnect_postbirth.hw_full.2', timestamp)
        self.assertEqual(identities['identity-uuid']['postbirth_messaging'], 'TRUE')


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

Class description:
Define the view for UserReactionOnComment

Method signatures and docstrings:
- def set_reaction(self, comment, profile, reaction): Helper method to set the reaction
- def post(self, request): Post a new comment reaction
- def get(self, request): View the reactions on all comments

Implement the Python class `UserReactionOnCommentView` described below.

Class description:
Define the view for UserReactionOnComment

Method signatures and docstrings:
- def set_reaction(self, comment, profile, reaction): Helper method to set the reaction
- def post(self, request): Post a new comment reaction
- def get(self, request): View the reactions on all comments

<|skeleton|>
class UserReactionOnCommentView:
    """Define the view for UserReactionOnComment"""

    def set_reaction(self, comment, profile, reaction):
        """Helper method to set the reaction"""
        <|body_0|>

    def post(self, request):
        """Post a new comment reaction"""
        <|body_1|>

    def get(self, request):
        """View the reactions on all comments"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        try:
            existing_reaction = UserReactionOnComment.objects.get(comment=comment, user=profile)
            existing_reaction.delete()
        except UserReactionOnComment.DoesNotExist:
            pass
        data = {'comment': comment.id, 'user': profile, 'reaction': reaction}
        serializer = self.serializer_class(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        response = {'message': 'Reaction successfully set.', 'reaction': serializer.data}
        status_code = status.HTTP_201_CREATED
        return (response, status_code)
<|end_body_0|>

<|body_start_1|>
        comment_id = request.data.get('comment_id')
        comment = find_comment_helper(comment_id)
        user = request.user
        profile = Profile.objects.get(user=user)
        reaction = request.data.get('reaction')
        try:
            existing_same_reaction = UserReactionOnComment.objects.get(comment=comment, user=profile, reaction=reaction)
            existing_same_reaction.delete()
            response = {'message': 'You nolonger `{}` this comment'.format('LIKE' if reaction in [1, '1'] else 'DISLIKE')}
            status_code = status.HTTP_200_OK
        except UserReactionOnComment.DoesNotExist:
            response, status_code = self.set_reaction(comment, profile, reaction)
        return Response(response, status_code)
<|end_body_1|>

<|body_start_2|>
        reactions = UserReactionOnComment.objects.all()
        list_reactions = [format_response(reaction) for reaction in reactions]
        response = {'reactions': list_reactions}
        return Response(response, status.HTTP_200_OK)
<|end_body_2|>

Solution:
class UserReactionOnCommentView:
    """Define the view for UserReactionOnComment"""

    def set_reaction(self, comment, profile, reaction):
        """Helper method to set the reaction"""
        try:
            existing_reaction = UserReactionOnComment.objects.get(comment=comment, user=profile)
            existing_reaction.delete()
        except UserReactionOnComment.DoesNotExist:
            pass
        data = {'comment': comment.id, 'user': profile, 'reaction': reaction}
        serializer = self.serializer_class(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        response = {'message': 'Reaction successfully set.', 'reaction': serializer.data}
        status_code = status.HTTP_201_CREATED
        return (response, status_code)

    def post(self, request):
        """Post a new comment reaction"""
        comment_id = request.data.get('comment_id')
        comment = find_comment_helper(comment_id)
        user = request.user
        profile = Profile.objects.get(user=user)
        reaction = request.data.get('reaction')
        try:
            existing_same_reaction = UserReactionOnComment.objects.get(comment=comment, user=profile, reaction=reaction)
            existing_same_reaction.delete()
            response = {'message': 'You nolonger `{}` this comment'.format('LIKE' if reaction in [1, '1'] else 'DISLIKE')}
            status_code = status.HTTP_200_OK
        except UserReactionOnComment.DoesNotExist:
            response, status_code = self.set_reaction(comment, profile, reaction)
        return Response(response, status_code)

    def get(self, request):
        """View the reactions on all comments"""
        reactions = UserReactionOnComment.objects.all()
        list_reactions = [format_response(reaction) for reaction in reactions]
        response = {'reactions': list_reactions}
        return Response(response, status.HTTP_200_OK)


serialize

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

Class description:
Implement the Host class.

Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Host: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Host
- def get_field_deserializers(self) -> Dict[str, Callable[[ParseNode], None]]: The deserialization information for the current model Returns: Dict[str, Callable[[ParseNode], None]]
- def serialize(self, writer: SerializationWriter) -> None: Serializes information the current object Args: writer: Serialization writer to use to serialize this model

Implement the Python class `Host` described below.

Class description:
Implement the Host class.

Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Host: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Host
- def get_field_deserializers(self) -> Dict[str, Callable[[ParseNode], None]]: The deserialization information for the current model Returns: Dict[str, Callable[[ParseNode], None]]
- def serialize(self, writer: SerializationWriter) -> None: Serializes information the current object Args: writer: Serialization writer to use to serialize this model

<|skeleton|>
class Host:

    def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Host:
        """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Host"""
        <|body_0|>

    def get_field_deserializers(self) -> Dict[str, Callable[[ParseNode], None]]:
        """The deserialization information for the current model Returns: Dict[str, Callable[[ParseNode], None]]"""
        <|body_1|>

    def serialize(self, writer: SerializationWriter) -> None:
        """Serializes information the current object Args: writer: Serialization writer to use to serialize this model"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        if not parse_node:
            raise TypeError('parse_node cannot be null.')
        try:
            mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
        except AttributeError:
            mapping_value = None
        if mapping_value and mapping_value.casefold() == '#microsoft.graph.security.hostname'.casefold():
            from .hostname import Hostname
            return Hostname()
        if mapping_value and mapping_value.casefold() == '#microsoft.graph.security.ipAddress'.casefold():
            from .ip_address import IpAddress
            return IpAddress()
        return Host()
<|end_body_0|>

<|body_start_1|>
        from .artifact import Artifact
        from .host_component import HostComponent
        from .host_cookie import HostCookie
        from .hostname import Hostname
        from .host_reputation import HostReputation
        from .host_tracker import HostTracker
        from .ip_address import IpAddress
        from .passive_dns_record import PassiveDnsRecord
        from .artifact import Artifact
        from .host_component import HostComponent
        from .host_cookie import HostCookie
        from .hostname import Hostname
        from .host_reputation import HostReputation
        from .host_tracker import HostTracker
        from .ip_address import IpAddress
        from .passive_dns_record import PassiveDnsRecord
        fields: Dict[str, Callable[[Any], None]] = {'components': lambda n: setattr(self, 'components', n.get_collection_of_object_values(HostComponent)), 'cookies': lambda n: setattr(self, 'cookies', n.get_collection_of_object_values(HostCookie)), 'firstSeenDateTime': lambda n: setattr(self, 'first_seen_date_time', n.get_datetime_value()), 'lastSeenDateTime': lambda n: setattr(self, 'last_seen_date_time', n.get_datetime_value()), 'passiveDns': lambda n: setattr(self, 'passive_dns', n.get_collection_of_object_values(PassiveDnsRecord)), 'passiveDnsReverse': lambda n: setattr(self, 'passive_dns_reverse', n.get_collection_of_object_values(PassiveDnsRecord)), 'reputation': lambda n: setattr(self, 'reputation', n.get_object_value(HostReputation)), 'trackers': lambda n: setattr(self, 'trackers', n.get_collection_of_object_values(HostTracker))}
        super_fields = super().get_field_deserializers()
        fields.update(super_fields)
        return fields
<|end_body_1|>

<|body_start_2|>
        if not writer:
            raise TypeError('writer cannot be null.')
        super().serialize(writer)
        writer.write_collection_of_object_values('components', self.components)
        writer.write_collection_of_object_values('cookies', self.cookies)
        writer.write_datetime_value('firstSeenDateTime', self.first_seen_date_time)
        writer.write_datetime_value('lastSeenDateTime', self.last_seen_date_time)
        writer.write_collection_of_object_values('passiveDns', self.passive_dns)
        writer.write_collection_of_object_values('passiveDnsReverse', self.passive_dns_reverse)
        writer.write_object_value('reputation', self.reputation)
        writer.write_collection_of_object_values('trackers', self.trackers)
<|end_body_2|>

Solution:
class Host:
    def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Host:
        """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Host"""
        if not parse_node:
            raise TypeError('parse_node cannot be null.')
        try:
            mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
        except AttributeError:
            mapping_value = None
        if mapping_value and mapping_value.casefold() == '#microsoft.graph.security.hostname'.casefold():
            from .hostname import Hostname
            return Hostname()
        if mapping_value and mapping_value.casefold() == '#microsoft.graph.security.ipAddress'.casefold():
            from .ip_address import IpAddress
            return IpAddress()
        return Host()

    def get_field_deserializers(self) -> Dict[str, Callable[[ParseNode], None]]:
        """The deserialization information for the current model Returns: Dict[str, Callable[[ParseNode], None]]"""
        from .artifact import Artifact
        from .host_component import HostComponent
        from .host_cookie import HostCookie
        from .hostname import Hostname
        from .host_reputation import HostReputation
        from .host_tracker import HostTracker
        from .ip_address import IpAddress
        from .passive_dns_record import PassiveDnsRecord
        from .artifact import Artifact
        from .host_component import HostComponent
        from .host_cookie import HostCookie
        from .hostname import Hostname
        from .host_reputation import HostReputation
        from .host_tracker import HostTracker
        from .ip_address import IpAddress
        from .passive_dns_record import PassiveDnsRecord
        fields: Dict[str, Callable[[Any], None]] = {'components': lambda n: setattr(self, 'components', n.get_collection_of_object_values(HostComponent)), 'cookies': lambda n: setattr(self, 'cookies', n.get_collection_of_object_values(HostCookie)), 'firstSeenDateTime': lambda n: setattr(self, 'first_seen_date_time', n.get_datetime_value()), 'lastSeenDateTime': lambda n: setattr(self, 'last_seen_date_time', n.get_datetime_value()), 'passiveDns': lambda n: setattr(self, 'passive_dns', n.get_collection_of_object_values(PassiveDnsRecord)), 'passiveDnsReverse': lambda n: setattr(self, 'passive_dns_reverse', n.get_collection_of_object_values(PassiveDnsRecord)), 'reputation': lambda n: setattr(self, 'reputation', n.get_object_value(HostReputation)), 'trackers': lambda n: setattr(self, 'trackers', n.get_collection_of_object_values(HostTracker))}
        super_fields = super().get_field_deserializers()
        fields.update(super_fields)
        return fields

    def serialize(self, writer: SerializationWriter) -> None:
        """Serializes information the current object Args: writer: Serialization writer to use to serialize this model"""
        if not writer:
            raise TypeError('writer cannot be null.')
        super().serialize(writer)
        writer.write_collection_of_object_values('components', self.components)
        writer.write_collection_of_object_values('cookies', self.cookies)
        writer.write_datetime_value('firstSeenDateTime', self.first_seen_date_time)
        writer.write_datetime_value('lastSeenDateTime', self.last_seen_date_time)
        writer.write_collection_of_object_values('passiveDns', self.passive_dns)
        writer.write_collection_of_object_values('passiveDnsReverse', self.passive_dns_reverse)
        writer.write_object_value('reputation', self.reputation)
        writer.write_collection_of_object_values('trackers', self.trackers)


activate

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

Class description:
Manage the tools in the database

Method signatures and docstrings:
- def add(tool_name, version, cad_exe, hls_exe, sim_exe, script): Add a new tool to the database Args: tool_name (str): Name of the tool version (str): Tool version cad_exe (str): Name of CAD tool executable. None if not applicable hls_exe (str): Name of HLS tool executable. None if not applicable sim_exe (str): Name of simulation tool executable. None if not applicable script (str): Shell script to initialize the tool Raises: SonarInvalidOpError: Raised if attempting to add an already existing tool.
- def get(tool=None): Get a tool from the database Args: tool (str, optional): Get a particular tool only. Defaults to None. Raises: SonarInvalidArgError: Raised if named tool not found in the database Returns: dict: Tool entry from the database
- def get_active(): Get the active tool Returns: dict: Tool entry from the database
- def clear(): Clear all tools from the database
- def activate(cad_tool, hls_tool, sim_tool): Activate a set of tools Args: cad_tool (str): Name of CAD tool hls_tool (str): Name of HLS tool sim_tool (str): Name of SIM tool
- def deactivate(): Deactivate all active tools

Implement the Python class `Tool` described below.

Class description:
Manage the tools in the database

Method signatures and docstrings:
- def add(tool_name, version, cad_exe, hls_exe, sim_exe, script): Add a new tool to the database Args: tool_name (str): Name of the tool version (str): Tool version cad_exe (str): Name of CAD tool executable. None if not applicable hls_exe (str): Name of HLS tool executable. None if not applicable sim_exe (str): Name of simulation tool executable. None if not applicable script (str): Shell script to initialize the tool Raises: SonarInvalidOpError: Raised if attempting to add an already existing tool.
- def get(tool=None): Get a tool from the database Args: tool (str, optional): Get a particular tool only. Defaults to None. Raises: SonarInvalidArgError: Raised if named tool not found in the database Returns: dict: Tool entry from the database
- def get_active(): Get the active tool Returns: dict: Tool entry from the database
- def clear(): Clear all tools from the database
- def activate(cad_tool, hls_tool, sim_tool): Activate a set of tools Args: cad_tool (str): Name of CAD tool hls_tool (str): Name of HLS tool sim_tool (str): Name of SIM tool
- def deactivate(): Deactivate all active tools

<|skeleton|>
class Tool:
    """Manage the tools in the database"""

    def add(tool_name, version, cad_exe, hls_exe, sim_exe, script):
        """Add a new tool to the database Args: tool_name (str): Name of the tool version (str): Tool version cad_exe (str): Name of CAD tool executable. None if not applicable hls_exe (str): Name of HLS tool executable. None if not applicable sim_exe (str): Name of simulation tool executable. None if not applicable script (str): Shell script to initialize the tool Raises: SonarInvalidOpError: Raised if attempting to add an already existing tool."""
        <|body_0|>

    def get(tool=None):
        """Get a tool from the database Args: tool (str, optional): Get a particular tool only. Defaults to None. Raises: SonarInvalidArgError: Raised if named tool not found in the database Returns: dict: Tool entry from the database"""
        <|body_1|>

    def get_active():
        """Get the active tool Returns: dict: Tool entry from the database"""
        <|body_2|>

    def clear():
        """Clear all tools from the database"""
        <|body_3|>

    def activate(cad_tool, hls_tool, sim_tool):
        """Activate a set of tools Args: cad_tool (str): Name of CAD tool hls_tool (str): Name of HLS tool sim_tool (str): Name of SIM tool"""
        <|body_4|>

    def deactivate():
        """Deactivate all active tools"""
        <|body_5|>

<|end_skeleton|>

<|body_start_0|>
        with shelve.open(Constants.SONAR_DB_PATH) as db:
            tools = db['tool']
            try:
                _dict = tools[tool_name]
            except KeyError:
                _dict = {'versions': [], 'executable': {}, 'script': {}}
            if version in _dict['versions']:
                logger.error("%s already exists. Use 'edit' to modify existing tools", version)
                raise SonarInvalidOpError
            _dict['versions'].append(version)
            _dict['executable']['cad'] = cad_exe
            _dict['executable']['hls'] = hls_exe
            _dict['executable']['sim'] = sim_exe
            _dict['script'][version] = script
            tools[tool_name] = _dict
            db['tool'] = tools
<|end_body_0|>

<|body_start_1|>
        with shelve.open(Constants.SONAR_DB_PATH) as db:
            tools = db['tool']
        if tool is None:
            return tools
        if tool not in tools:
            raise SonarInvalidArgError
        return tools[tool]
<|end_body_1|>

<|body_start_2|>
        with shelve.open(Constants.SONAR_DB_PATH) as db:
            active = db['active']
            return {k: active[k] for k in ('cad', 'hls', 'sim')}
<|end_body_2|>

<|body_start_3|>
        with shelve.open(Constants.SONAR_DB_PATH) as db:
            db['tool'] = {}
            active = db['active']
            for key in ('cad', 'hls', 'sim'):
                active[key] = None
            db['active'] = active
<|end_body_3|>

<|body_start_4|>
        with shelve.open(Constants.SONAR_DB_PATH) as db:
            active = db['active']
            active['cad'] = cad_tool
            active['hls'] = hls_tool
            active['sim'] = sim_tool
            tools = db['tool']
            with open(Constants.SONAR_SHELL_TOOL_SOURCE, 'w') as f:
                script = []
                for key in ['cad', 'sim', 'hls']:
                    tool = active[key]
                    if tool:
                        tool_id, version = tool
                        tool_script = tools[tool_id]['script'][version]
                        if tool_script not in script:
                            script.append(tool_script)
                f.write('\n'.join(script))
            db['active'] = active
<|end_body_4|>

<|body_start_5|>
        if os.path.exists(Constants.SONAR_SHELL_TOOL_SOURCE):
            os.remove(Constants.SONAR_SHELL_TOOL_SOURCE)
        with shelve.open(Constants.SONAR_DB_PATH) as db:
            active = db['active']
            active['cad'] = None
            active['hls'] = None
            active['sim'] = None
            db['active'] = active
<|end_body_5|>

Solution:
class Tool:
    """Manage the tools in the database"""

    def add(tool_name, version, cad_exe, hls_exe, sim_exe, script):
        """Add a new tool to the database Args: tool_name (str): Name of the tool version (str): Tool version cad_exe (str): Name of CAD tool executable. None if not applicable hls_exe (str): Name of HLS tool executable. None if not applicable sim_exe (str): Name of simulation tool executable. None if not applicable script (str): Shell script to initialize the tool Raises: SonarInvalidOpError: Raised if attempting to add an already existing tool."""
        with shelve.open(Constants.SONAR_DB_PATH) as db:
            tools = db['tool']
            try:
                _dict = tools[tool_name]
            except KeyError:
                _dict = {'versions': [], 'executable': {}, 'script': {}}
            if version in _dict['versions']:
                logger.error("%s already exists. Use 'edit' to modify existing tools", version)
                raise SonarInvalidOpError
            _dict['versions'].append(version)
            _dict['executable']['cad'] = cad_exe
            _dict['executable']['hls'] = hls_exe
            _dict['executable']['sim'] = sim_exe
            _dict['script'][version] = script
            tools[tool_name] = _dict
            db['tool'] = tools

    def get(tool=None):
        """Get a tool from the database Args: tool (str, optional): Get a particular tool only. Defaults to None. Raises: SonarInvalidArgError: Raised if named tool not found in the database Returns: dict: Tool entry from the database"""
        with shelve.open(Constants.SONAR_DB_PATH) as db:
            tools = db['tool']
        if tool is None:
            return tools
        if tool not in tools:
            raise SonarInvalidArgError
        return tools[tool]

    def get_active():
        """Get the active tool Returns: dict: Tool entry from the database"""
        with shelve.open(Constants.SONAR_DB_PATH) as db:
            active = db['active']
            return {k: active[k] for k in ('cad', 'hls', 'sim')}

    def clear():
        """Clear all tools from the database"""
        with shelve.open(Constants.SONAR_DB_PATH) as db:
            db['tool'] = {}
            active = db['active']
            for key in ('cad', 'hls', 'sim'):
                active[key] = None
            db['active'] = active

    def activate(cad_tool, hls_tool, sim_tool):
        """Activate a set of tools Args: cad_tool (str): Name of CAD tool hls_tool (str): Name of HLS tool sim_tool (str): Name of SIM tool"""
        with shelve.open(Constants.SONAR_DB_PATH) as db:
            active = db['active']
            active['cad'] = cad_tool
            active['hls'] = hls_tool
            active['sim'] = sim_tool
            tools = db['tool']
            with open(Constants.SONAR_SHELL_TOOL_SOURCE, 'w') as f:
                script = []
                for key in ['cad', 'sim', 'hls']:
                    tool = active[key]
                    if tool:
                        tool_id, version = tool
                        tool_script = tools[tool_id]['script'][version]
                        if tool_script not in script:
                            script.append(tool_script)
                f.write('\n'.join(script))
            db['active'] = active

    def deactivate():
        """Deactivate all active tools"""
        if os.path.exists(Constants.SONAR_SHELL_TOOL_SOURCE):
            os.remove(Constants.SONAR_SHELL_TOOL_SOURCE)
        with shelve.open(Constants.SONAR_DB_PATH) as db:
            active = db['active']
            active['cad'] = None
            active['hls'] = None
            active['sim'] = None
            db['active'] = active


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

Class description:
a leaky BLSTM layer

Method signatures and docstrings:
- def __init__(self, num_units, layer_norm=False, recurrent_dropout=1.0, leak_factor=1.0): LeakyBLSTMLayer constructor Args: num_units: The number of units in the one directon layer_norm: whether layer normalization should be applied recurrent_dropout: the recurrent dropout keep probability leak_factor: the leak factor (if 1, there is no leakage)
- def __call__(self, inputs, sequence_length, scope=None): Create the variables and do the forward computation Args: inputs: the input to the layer as a [batch_size, max_length, dim] tensor sequence_length: the length of the input sequences as a [batch_size] tensor scope: The variable scope sets the namespace under which the variables created during this call will be stored. Returns: the output of the layer

Implement the Python class `LeakyBLSTMLayer` described below.

Class description:
a leaky BLSTM layer

Method signatures and docstrings:
- def __init__(self, num_units, layer_norm=False, recurrent_dropout=1.0, leak_factor=1.0): LeakyBLSTMLayer constructor Args: num_units: The number of units in the one directon layer_norm: whether layer normalization should be applied recurrent_dropout: the recurrent dropout keep probability leak_factor: the leak factor (if 1, there is no leakage)
- def __call__(self, inputs, sequence_length, scope=None): Create the variables and do the forward computation Args: inputs: the input to the layer as a [batch_size, max_length, dim] tensor sequence_length: the length of the input sequences as a [batch_size] tensor scope: The variable scope sets the namespace under which the variables created during this call will be stored. Returns: the output of the layer

<|skeleton|>
class LeakyBLSTMLayer:
    """a leaky BLSTM layer"""

    def __init__(self, num_units, layer_norm=False, recurrent_dropout=1.0, leak_factor=1.0):
        """LeakyBLSTMLayer constructor Args: num_units: The number of units in the one directon layer_norm: whether layer normalization should be applied recurrent_dropout: the recurrent dropout keep probability leak_factor: the leak factor (if 1, there is no leakage)"""
        <|body_0|>

    def __call__(self, inputs, sequence_length, scope=None):
        """Create the variables and do the forward computation Args: inputs: the input to the layer as a [batch_size, max_length, dim] tensor sequence_length: the length of the input sequences as a [batch_size] tensor scope: The variable scope sets the namespace under which the variables created during this call will be stored. Returns: the output of the layer"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.num_units = num_units
        self.layer_norm = layer_norm
        self.recurrent_dropout = recurrent_dropout
        self.leak_factor = leak_factor
<|end_body_0|>

<|body_start_1|>
        with tf.variable_scope(scope or type(self).__name__):
            lstm_cell_fw = rnn_cell.LayerNormBasicLeakLSTMCell(num_units=self.num_units, leak_factor=self.leak_factor, layer_norm=self.layer_norm, dropout_keep_prob=self.recurrent_dropout, reuse=tf.get_variable_scope().reuse)
            lstm_cell_bw = rnn_cell.LayerNormBasicLeakLSTMCell(self.num_units, leak_factor=self.leak_factor, layer_norm=self.layer_norm, dropout_keep_prob=self.recurrent_dropout, reuse=tf.get_variable_scope().reuse)
            outputs_tupple, _ = bidirectional_dynamic_rnn(lstm_cell_fw, lstm_cell_bw, inputs, dtype=tf.float32, sequence_length=sequence_length)
            outputs = tf.concat(outputs_tupple, 2)
            return outputs
<|end_body_1|>

Solution:
class LeakyBLSTMLayer:
    """a leaky BLSTM layer"""

    def __init__(self, num_units, layer_norm=False, recurrent_dropout=1.0, leak_factor=1.0):
        """LeakyBLSTMLayer constructor Args: num_units: The number of units in the one directon layer_norm: whether layer normalization should be applied recurrent_dropout: the recurrent dropout keep probability leak_factor: the leak factor (if 1, there is no leakage)"""
        self.num_units = num_units
        self.layer_norm = layer_norm
        self.recurrent_dropout = recurrent_dropout
        self.leak_factor = leak_factor

    def __call__(self, inputs, sequence_length, scope=None):
        """Create the variables and do the forward computation Args: inputs: the input to the layer as a [batch_size, max_length, dim] tensor sequence_length: the length of the input sequences as a [batch_size] tensor scope: The variable scope sets the namespace under which the variables created during this call will be stored. Returns: the output of the layer"""
        with tf.variable_scope(scope or type(self).__name__):
            lstm_cell_fw = rnn_cell.LayerNormBasicLeakLSTMCell(num_units=self.num_units, leak_factor=self.leak_factor, layer_norm=self.layer_norm, dropout_keep_prob=self.recurrent_dropout, reuse=tf.get_variable_scope().reuse)
            lstm_cell_bw = rnn_cell.LayerNormBasicLeakLSTMCell(self.num_units, leak_factor=self.leak_factor, layer_norm=self.layer_norm, dropout_keep_prob=self.recurrent_dropout, reuse=tf.get_variable_scope().reuse)
            outputs_tupple, _ = bidirectional_dynamic_rnn(lstm_cell_fw, lstm_cell_bw, inputs, dtype=tf.float32, sequence_length=sequence_length)
            outputs = tf.concat(outputs_tupple, 2)
            return outputs


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

Class description:
Eucken correlation for thermal conductivity

Method signatures and docstrings:
- def build_parameters(cobj, p): Builds dimensionless parameter f_int
- def return_expression(b, cobj, p, T): Returns expression for therm_cond_phase_comp

Implement the Python class `therm_cond_phase_comp` described below.

Class description:
Eucken correlation for thermal conductivity

Method signatures and docstrings:
- def build_parameters(cobj, p): Builds dimensionless parameter f_int
- def return_expression(b, cobj, p, T): Returns expression for therm_cond_phase_comp

<|skeleton|>
class therm_cond_phase_comp:
    """Eucken correlation for thermal conductivity"""

    def build_parameters(cobj, p):
        """Builds dimensionless parameter f_int"""
        <|body_0|>

    def return_expression(b, cobj, p, T):
        """Returns expression for therm_cond_phase_comp"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if not hasattr(cobj, 'f_int_eucken'):
            cobj.f_int_eucken = Var(doc='Dimensionless factor in Eucken formula associated with internal degrees of freedom', units=pyunits.dimensionless)
            set_param_from_config(cobj, param='f_int_eucken')
<|end_body_0|>

<|body_start_1|>
        units = b.params.get_metadata().derived_units
        M = pyunits.convert(cobj.mw, pyunits.kg / pyunits.mol)
        R = pyunits.convert(Constants.gas_constant, units['heat_capacity_mole'])
        f_int = cobj.f_int_eucken
        try:
            cp_mol_ig_comp = cobj.config.cp_mol_ig_comp
        except AttributeError:
            raise ConfigurationError(f'Cannot find method to calculate cp_mol_ig_comp for component {cobj.local_name}.')
        if not hasattr(b, '_visc_d_phase_comp'):
            b._make_visc_d_phase_comp()
        if hasattr(cp_mol_ig_comp, 'return_expression'):
            cp_func = cp_mol_ig_comp.return_expression
        else:
            cp_func = cp_mol_ig_comp.cp_mol_ig_comp.return_expression
        therm_cond = b._visc_d_phase_comp[p, cobj.local_name] / M * (f_int * cp_func(b, cobj, T) + (15 / 4 - 5 * f_int / 2) * R)
        return pyunits.convert(therm_cond, units['thermal_conductivity'])
<|end_body_1|>

Solution:
class therm_cond_phase_comp:
    """Eucken correlation for thermal conductivity"""

    def build_parameters(cobj, p):
        """Builds dimensionless parameter f_int"""
        if not hasattr(cobj, 'f_int_eucken'):
            cobj.f_int_eucken = Var(doc='Dimensionless factor in Eucken formula associated with internal degrees of freedom', units=pyunits.dimensionless)
            set_param_from_config(cobj, param='f_int_eucken')

    def return_expression(b, cobj, p, T):
        """Returns expression for therm_cond_phase_comp"""
        units = b.params.get_metadata().derived_units
        M = pyunits.convert(cobj.mw, pyunits.kg / pyunits.mol)
        R = pyunits.convert(Constants.gas_constant, units['heat_capacity_mole'])
        f_int = cobj.f_int_eucken
        try:
            cp_mol_ig_comp = cobj.config.cp_mol_ig_comp
        except AttributeError:
            raise ConfigurationError(f'Cannot find method to calculate cp_mol_ig_comp for component {cobj.local_name}.')
        if not hasattr(b, '_visc_d_phase_comp'):
            b._make_visc_d_phase_comp()
        if hasattr(cp_mol_ig_comp, 'return_expression'):
            cp_func = cp_mol_ig_comp.return_expression
        else:
            cp_func = cp_mol_ig_comp.cp_mol_ig_comp.return_expression
        therm_cond = b._visc_d_phase_comp[p, cobj.local_name] / M * (f_int * cp_func(b, cobj, T) + (15 / 4 - 5 * f_int / 2) * R)
        return pyunits.convert(therm_cond, units['thermal_conductivity'])


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

Class description:
Biothings Annotation Endpoint URL pattern examples: /{pre}/{ver}/{typ}/? /{pre}/{ver}/{typ}/([^\\/]+)/? queries a term against a pre-determined field that represents the id of a document, like _id and dbsnp.rsid GET -> {...} POST -> [{...}, ...]

Method signatures and docstrings:
- def pre_query_builder_hook(self, options): Annotation query has default scopes. Annotation query include _version field.
- def pre_finish_hook(self, options, res): Return single result for GET. Empty results trigger 404 error. Keep _version field, Discard _score field.

Implement the Python class `BiothingHandler` described below.

Class description:
Biothings Annotation Endpoint URL pattern examples: /{pre}/{ver}/{typ}/? /{pre}/{ver}/{typ}/([^\\/]+)/? queries a term against a pre-determined field that represents the id of a document, like _id and dbsnp.rsid GET -> {...} POST -> [{...}, ...]

Method signatures and docstrings:
- def pre_query_builder_hook(self, options): Annotation query has default scopes. Annotation query include _version field.
- def pre_finish_hook(self, options, res): Return single result for GET. Empty results trigger 404 error. Keep _version field, Discard _score field.

<|skeleton|>
class BiothingHandler:
    """Biothings Annotation Endpoint URL pattern examples: /{pre}/{ver}/{typ}/? /{pre}/{ver}/{typ}/([^\\/]+)/? queries a term against a pre-determined field that represents the id of a document, like _id and dbsnp.rsid GET -> {...} POST -> [{...}, ...]"""

    def pre_query_builder_hook(self, options):
        """Annotation query has default scopes. Annotation query include _version field."""
        <|body_0|>

    def pre_finish_hook(self, options, res):
        """Return single result for GET. Empty results trigger 404 error. Keep _version field, Discard _score field."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if self.request.method == 'POST':
            self.event['qsize'] = len(options.ids)
            options.esqb.q = options.ids
        elif self.request.method == 'GET':
            options.esqb.q = options.id
        options.esqb.regexs = self.web_settings.ANNOTATION_ID_REGEX_LIST
        options.esqb.scopes = self.web_settings.ANNOTATION_DEFAULT_SCOPES
        options.esqb.version = True
        options = super().pre_query_builder_hook(options)
        return options
<|end_body_0|>

<|body_start_1|>
        if isinstance(res, dict):
            if not res.get('hits'):
                template = self.web_settings.ID_NOT_FOUND_TEMPLATE
                reason = template.format(bid=options.esqb.q)
                raise EndRequest(404, reason=reason)
            if len(res['hits']) > 1:
                raise EndRequest(404, reason='not a unique id.')
            res = res['hits'][0]
            res.pop('_score', None)
        elif isinstance(res, list):
            for hit in res:
                hit.pop('_score', None)
        return res
<|end_body_1|>

Solution:
class BiothingHandler:
    """Biothings Annotation Endpoint URL pattern examples: /{pre}/{ver}/{typ}/? /{pre}/{ver}/{typ}/([^\\/]+)/? queries a term against a pre-determined field that represents the id of a document, like _id and dbsnp.rsid GET -> {...} POST -> [{...}, ...]"""

    def pre_query_builder_hook(self, options):
        """Annotation query has default scopes. Annotation query include _version field."""
        if self.request.method == 'POST':
            self.event['qsize'] = len(options.ids)
            options.esqb.q = options.ids
        elif self.request.method == 'GET':
            options.esqb.q = options.id
        options.esqb.regexs = self.web_settings.ANNOTATION_ID_REGEX_LIST
        options.esqb.scopes = self.web_settings.ANNOTATION_DEFAULT_SCOPES
        options.esqb.version = True
        options = super().pre_query_builder_hook(options)
        return options

    def pre_finish_hook(self, options, res):
        """Return single result for GET. Empty results trigger 404 error. Keep _version field, Discard _score field."""
        if isinstance(res, dict):
            if not res.get('hits'):
                template = self.web_settings.ID_NOT_FOUND_TEMPLATE
                reason = template.format(bid=options.esqb.q)
                raise EndRequest(404, reason=reason)
            if len(res['hits']) > 1:
                raise EndRequest(404, reason='not a unique id.')
            res = res['hits'][0]
            res.pop('_score', None)
        elif isinstance(res, list):
            for hit in res:
                hit.pop('_score', None)
        return res


重置年度计划查询 :return:

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

Class description:
Implement the TestDevPlanList class.

Method signatures and docstrings:
- def set_up(self): 前置操作 :return:
- def test_query_dev_plan(self, set_up): 年度计划查询 :return:
- def test_reset_dev_plan_query(self): 重置年度计划查询 :return:
- def test_click_create_dev_plan(self): 查看市级计划 :return:
- def test_view_shi_plan_list(self): 查看市级计划 :return:
- def test_view_shi_plan_detail(self): 查看市级计划 :return:

Implement the Python class `TestDevPlanList` described below.

Class description:
Implement the TestDevPlanList class.

Method signatures and docstrings:
- def set_up(self): 前置操作 :return:
- def test_query_dev_plan(self, set_up): 年度计划查询 :return:
- def test_reset_dev_plan_query(self): 重置年度计划查询 :return:
- def test_click_create_dev_plan(self): 查看市级计划 :return:
- def test_view_shi_plan_list(self): 查看市级计划 :return:
- def test_view_shi_plan_detail(self): 查看市级计划 :return:

<|skeleton|>
class TestDevPlanList:

    def set_up(self):
        """前置操作 :return:"""
        <|body_0|>

    def test_query_dev_plan(self, set_up):
        """年度计划查询 :return:"""
        <|body_1|>

    def test_reset_dev_plan_query(self):
        """重置年度计划查询 :return:"""
        <|body_2|>

    def test_click_create_dev_plan(self):
        """查看市级计划 :return:"""
        <|body_3|>

    def test_view_shi_plan_list(self):
        """查看市级计划 :return:"""
        <|body_4|>

    def test_view_shi_plan_detail(self):
        """查看市级计划 :return:"""
        <|body_5|>

<|end_skeleton|>

<|body_start_0|>
        global dev_plan_list_page, admin_page
        dev_plan_list_page = DevPlanListPage(self.driver)
        admin_page = AdminPage(self.driver)
        admin_page.into_subsystem('业务管理')
        admin_page.select_menu('首页/渠道业务管理/年度发展计划')
<|end_body_0|>

<|body_start_1|>
        admin_page.select_menu('计划列表')
        dev_plan_list_page.query_by_year(_year='2020')
        assert '2020' in dev_plan_list_page.read_table_cell_value(1, 3), '年度计划查询失败'
<|end_body_1|>

<|body_start_2|>
        admin_page.select_menu('计划列表')
        dev_plan_list_page.reset_query()
        assert dev_plan_list_page.read_query_year() == '', '重置年度计划查询条件失败'
<|end_body_2|>

<|body_start_3|>
        admin_page.select_menu('计划列表')
        dev_plan_list_page.click_create_dev_plan()
        assert dev_plan_list_page.check_current_menu('新建年度发展计划'), '点击新建年度发展计划失败'
<|end_body_3|>

<|body_start_4|>
        admin_page.select_menu('计划列表')
        dev_plan_list_page.click_shi_plan_btn()
        assert dev_plan_list_page.check_current_menu('市级计划列表'), '点击查看渠道管市级计划列表详情失败'
<|end_body_4|>

<|body_start_5|>
        admin_page.select_menu('计划列表')
        dev_plan_list_page.click_view_plan_btn()
        assert dev_plan_list_page.check_current_menu('年度发展计划详情'), '点击查看年度发展计划详情失败'
<|end_body_5|>

Solution:
class TestDevPlanList:
    def set_up(self):
        """前置操作 :return:"""
        global dev_plan_list_page, admin_page
        dev_plan_list_page = DevPlanListPage(self.driver)
        admin_page = AdminPage(self.driver)
        admin_page.into_subsystem('业务管理')
        admin_page.select_menu('首页/渠道业务管理/年度发展计划')

    def test_query_dev_plan(self, set_up):
        """年度计划查询 :return:"""
        admin_page.select_menu('计划列表')
        dev_plan_list_page.query_by_year(_year='2020')
        assert '2020' in dev_plan_list_page.read_table_cell_value(1, 3), '年度计划查询失败'

    def test_reset_dev_plan_query(self):
        """重置年度计划查询 :return:"""
        admin_page.select_menu('计划列表')
        dev_plan_list_page.reset_query()
        assert dev_plan_list_page.read_query_year() == '', '重置年度计划查询条件失败'

    def test_click_create_dev_plan(self):
        """查看市级计划 :return:"""
        admin_page.select_menu('计划列表')
        dev_plan_list_page.click_create_dev_plan()
        assert dev_plan_list_page.check_current_menu('新建年度发展计划'), '点击新建年度发展计划失败'

    def test_view_shi_plan_list(self):
        """查看市级计划 :return:"""
        admin_page.select_menu('计划列表')
        dev_plan_list_page.click_shi_plan_btn()
        assert dev_plan_list_page.check_current_menu('市级计划列表'), '点击查看渠道管市级计划列表详情失败'

    def test_view_shi_plan_detail(self):
        """查看市级计划 :return:"""
        admin_page.select_menu('计划列表')
        dev_plan_list_page.click_view_plan_btn()
        assert dev_plan_list_page.check_current_menu('年度发展计划详情'), '点击查看年度发展计划详情失败'