forward

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

Class description:
Implements a BiLSTM network with an embedding layer and single hidden layer. This network will predict a sequence of labels (e.g. PER) for a given token (e.g. Henry) using a featurized window around the token.

Method signatures and docstrings:
- def __init__(self, helper, config, pretrained_embeddings): TODO: - Initialize the layer of the models: - *Unfrozen* embeddings of shape (V, D) which are loaded with pre-trained weights (`pretrained_embeddings`) - BiLSTM layer with hidden size of H/2 per direction - Linear layer with output of shape C Where: V - size of the vocabulary D - size of a word embedding H - size of the hidden layer C - number of classes being predicted Hints: - For the input dimension of the BiLSTM, think about the size of an embedded word representation
- def forward(self, sentences): TODO: - Perform the forward pass of the model, according to the model description in the handout: 1. Get the embeddings of the input 2. Apply dropout on the output of 1 3. Pass the output of 2 through the BiLSTM layer 4. Apply dropout on the output of 3 5. Pass the output of 4 through the linear layer 6. Perform softmax on the output of 5 to get tag_probs Hints: - Reshape the output of the embeddings layer so the full representation of an embedded word fits in one dimension. You might find the .view method of a tensor helpful. Args: - sentences: The input tensor of shape (batch_size, max_length, n_features) Returns: - tag_probs: A tensor of shape (batch_size, max_length, n_classes) which rep

Implement the Python class `NerBiLstmModel` described below.

Class description:
Implements a BiLSTM network with an embedding layer and single hidden layer. This network will predict a sequence of labels (e.g. PER) for a given token (e.g. Henry) using a featurized window around the token.

Method signatures and docstrings:
- def __init__(self, helper, config, pretrained_embeddings): TODO: - Initialize the layer of the models: - *Unfrozen* embeddings of shape (V, D) which are loaded with pre-trained weights (`pretrained_embeddings`) - BiLSTM layer with hidden size of H/2 per direction - Linear layer with output of shape C Where: V - size of the vocabulary D - size of a word embedding H - size of the hidden layer C - number of classes being predicted Hints: - For the input dimension of the BiLSTM, think about the size of an embedded word representation
- def forward(self, sentences): TODO: - Perform the forward pass of the model, according to the model description in the handout: 1. Get the embeddings of the input 2. Apply dropout on the output of 1 3. Pass the output of 2 through the BiLSTM layer 4. Apply dropout on the output of 3 5. Pass the output of 4 through the linear layer 6. Perform softmax on the output of 5 to get tag_probs Hints: - Reshape the output of the embeddings layer so the full representation of an embedded word fits in one dimension. You might find the .view method of a tensor helpful. Args: - sentences: The input tensor of shape (batch_size, max_length, n_features) Returns: - tag_probs: A tensor of shape (batch_size, max_length, n_classes) which rep

<|skeleton|>
class NerBiLstmModel:
    """Implements a BiLSTM network with an embedding layer and single hidden layer. This network will predict a sequence of labels (e.g. PER) for a given token (e.g. Henry) using a featurized window around the token."""

    def __init__(self, helper, config, pretrained_embeddings):
        """TODO: - Initialize the layer of the models: - *Unfrozen* embeddings of shape (V, D) which are loaded with pre-trained weights (`pretrained_embeddings`) - BiLSTM layer with hidden size of H/2 per direction - Linear layer with output of shape C Where: V - size of the vocabulary D - size of a word embedding H - size of the hidden layer C - number of classes being predicted Hints: - For the input dimension of the BiLSTM, think about the size of an embedded word representation"""
        <|body_0|>

    def forward(self, sentences):
        """TODO: - Perform the forward pass of the model, according to the model description in the handout: 1. Get the embeddings of the input 2. Apply dropout on the output of 1 3. Pass the output of 2 through the BiLSTM layer 4. Apply dropout on the output of 3 5. Pass the output of 4 through the linear layer 6. Perform softmax on the output of 5 to get tag_probs Hints: - Reshape the output of the embeddings layer so the full representation of an embedded word fits in one dimension. You might find the .view method of a tensor helpful. Args: - sentences: The input tensor of shape (batch_size, max_length, n_features) Returns: - tag_probs: A tensor of shape (batch_size, max_length, n_classes) which rep"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        super(NerBiLstmModel, self).__init__()
        self.config = config
        self._max_length = min(config.max_length, helper.max_length)
        self._dropout = torch.nn.Dropout(config.dropout)
        self._embeddings = torch.nn.Embedding.from_pretrained(pretrained_embeddings, freeze=False)
        self._nerbilstm = torch.nn.LSTM(input_size=config.embed_size * config.n_features, hidden_size=config.hidden_size // 2, batch_first=True, bidirectional=True)
        self._hidden2tag = torch.nn.Linear(in_features=config.hidden_size, out_features=config.n_classes)
<|end_body_0|>

<|body_start_1|>
        batch_size, seq_length = (sentences.shape[0], sentences.shape[1])
        sentences_embeddings = sentences.long().view((batch_size, seq_length * self.config.n_features))
        sentences_embeddings_reshaped = self._embeddings(sentences_embeddings).view(batch_size, seq_length, -1)
        sentences_embeddings_dropout = self._dropout(sentences_embeddings_reshaped)
        nerbilstm_output, _ = self._nerbilstm(sentences_embeddings_dropout)
        nerbilstm_dropout_output = self._dropout(nerbilstm_output)
        linear_output = self._hidden2tag(nerbilstm_dropout_output)
        tag_probs = torch.nn.functional.log_softmax(linear_output, dim=2)
        return tag_probs
<|end_body_1|>

Solution:
class NerBiLstmModel:
    """Implements a BiLSTM network with an embedding layer and single hidden layer. This network will predict a sequence of labels (e.g. PER) for a given token (e.g. Henry) using a featurized window around the token."""

    def __init__(self, helper, config, pretrained_embeddings):
        """TODO: - Initialize the layer of the models: - *Unfrozen* embeddings of shape (V, D) which are loaded with pre-trained weights (`pretrained_embeddings`) - BiLSTM layer with hidden size of H/2 per direction - Linear layer with output of shape C Where: V - size of the vocabulary D - size of a word embedding H - size of the hidden layer C - number of classes being predicted Hints: - For the input dimension of the BiLSTM, think about the size of an embedded word representation"""
        super(NerBiLstmModel, self).__init__()
        self.config = config
        self._max_length = min(config.max_length, helper.max_length)
        self._dropout = torch.nn.Dropout(config.dropout)
        self._embeddings = torch.nn.Embedding.from_pretrained(pretrained_embeddings, freeze=False)
        self._nerbilstm = torch.nn.LSTM(input_size=config.embed_size * config.n_features, hidden_size=config.hidden_size // 2, batch_first=True, bidirectional=True)
        self._hidden2tag = torch.nn.Linear(in_features=config.hidden_size, out_features=config.n_classes)

    def forward(self, sentences):
        """TODO: - Perform the forward pass of the model, according to the model description in the handout: 1. Get the embeddings of the input 2. Apply dropout on the output of 1 3. Pass the output of 2 through the BiLSTM layer 4. Apply dropout on the output of 3 5. Pass the output of 4 through the linear layer 6. Perform softmax on the output of 5 to get tag_probs Hints: - Reshape the output of the embeddings layer so the full representation of an embedded word fits in one dimension. You might find the .view method of a tensor helpful. Args: - sentences: The input tensor of shape (batch_size, max_length, n_features) Returns: - tag_probs: A tensor of shape (batch_size, max_length, n_classes) which rep"""
        batch_size, seq_length = (sentences.shape[0], sentences.shape[1])
        sentences_embeddings = sentences.long().view((batch_size, seq_length * self.config.n_features))
        sentences_embeddings_reshaped = self._embeddings(sentences_embeddings).view(batch_size, seq_length, -1)
        sentences_embeddings_dropout = self._dropout(sentences_embeddings_reshaped)
        nerbilstm_output, _ = self._nerbilstm(sentences_embeddings_dropout)
        nerbilstm_dropout_output = self._dropout(nerbilstm_output)
        linear_output = self._hidden2tag(nerbilstm_dropout_output)
        tag_probs = torch.nn.functional.log_softmax(linear_output, dim=2)
        return tag_probs


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

Class description:
Implement the DijkstrasAlgorithm class.

Method signatures and docstrings:
- def __init__(self, graph, src, dest): Input: graph (AdjacencyMatrix) = AdjacencyMatrix to find shortest path/distance src (int): Source node to start search from dest (int): Destination node to end search at Output: DijkstrasAlgorithm
- def create_nodes_heap(self, graph): Builds a min heap from the AdjacencyMatrix using node distances Input: graph (AdjacencyMatrix) = AdjacencyMatrix to build heap from Output: (list) adhering to min heap invariant
- def shortest_distance(self): Input: Output: (int) representing shortest distance to the destination from the source
- def shortest_path(self): Input: Output: (list) representing shortest path to the destination from the source
- def build_shortest_path(self): Actual implementation of Dijkstras Algorithm to get shortest path Input: Output:

Implement the Python class `DijkstrasAlgorithm` described below.

Class description:
Implement the DijkstrasAlgorithm class.

Method signatures and docstrings:
- def __init__(self, graph, src, dest): Input: graph (AdjacencyMatrix) = AdjacencyMatrix to find shortest path/distance src (int): Source node to start search from dest (int): Destination node to end search at Output: DijkstrasAlgorithm
- def create_nodes_heap(self, graph): Builds a min heap from the AdjacencyMatrix using node distances Input: graph (AdjacencyMatrix) = AdjacencyMatrix to build heap from Output: (list) adhering to min heap invariant
- def shortest_distance(self): Input: Output: (int) representing shortest distance to the destination from the source
- def shortest_path(self): Input: Output: (list) representing shortest path to the destination from the source
- def build_shortest_path(self): Actual implementation of Dijkstras Algorithm to get shortest path Input: Output:

<|skeleton|>
class DijkstrasAlgorithm:

    def __init__(self, graph, src, dest):
        """Input: graph (AdjacencyMatrix) = AdjacencyMatrix to find shortest path/distance src (int): Source node to start search from dest (int): Destination node to end search at Output: DijkstrasAlgorithm"""
        <|body_0|>

    def create_nodes_heap(self, graph):
        """Builds a min heap from the AdjacencyMatrix using node distances Input: graph (AdjacencyMatrix) = AdjacencyMatrix to build heap from Output: (list) adhering to min heap invariant"""
        <|body_1|>

    def shortest_distance(self):
        """Input: Output: (int) representing shortest distance to the destination from the source"""
        <|body_2|>

    def shortest_path(self):
        """Input: Output: (list) representing shortest path to the destination from the source"""
        <|body_3|>

    def build_shortest_path(self):
        """Actual implementation of Dijkstras Algorithm to get shortest path Input: Output:"""
        <|body_4|>

<|end_skeleton|>

<|body_start_0|>
        self.graph = graph
        self.nodes_heap = self.create_nodes_heap(graph)
        self.src = self.nodes_heap[self.nodes_heap.index(src)]
        self.dest = self.nodes_heap[self.nodes_heap.index(dest)]
        self.src.distance = 0
        heapify(self.nodes_heap)
<|end_body_0|>

<|body_start_1|>
        min_heap = []
        for label, node in self.graph.nodes.items():
            node_container = NodeContainer(node)
            heappush(min_heap, node_container)
        return min_heap
<|end_body_1|>

<|body_start_2|>
        if self.dest.distance == float('inf'):
            self.build_shortest_path()
        return self.dest.distance
<|end_body_2|>

<|body_start_3|>
        if self.dest.distance == float('inf'):
            self.build_shortest_path()
        current_node = self.dest
        path = [current_node.label]
        while current_node.previous:
            path.append(current_node.previous.label)
            current_node = current_node.previous
        path.reverse()
        return path
<|end_body_3|>

<|body_start_4|>
        while self.nodes_heap:
            current_node = heappop(self.nodes_heap)
            for node_label, edge_weight in enumerate(current_node.edges):
                if edge_weight and node_label in self.nodes_heap:
                    neighbor = self.nodes_heap[self.nodes_heap.index(node_label)]
                    if neighbor.distance > current_node.distance + edge_weight:
                        neighbor.distance = current_node.distance + edge_weight
                        neighbor.previous = current_node
            heapify(self.nodes_heap)
<|end_body_4|>

Solution:
class DijkstrasAlgorithm:
    def __init__(self, graph, src, dest):
        """Input: graph (AdjacencyMatrix) = AdjacencyMatrix to find shortest path/distance src (int): Source node to start search from dest (int): Destination node to end search at Output: DijkstrasAlgorithm"""
        self.graph = graph
        self.nodes_heap = self.create_nodes_heap(graph)
        self.src = self.nodes_heap[self.nodes_heap.index(src)]
        self.dest = self.nodes_heap[self.nodes_heap.index(dest)]
        self.src.distance = 0
        heapify(self.nodes_heap)

    def create_nodes_heap(self, graph):
        """Builds a min heap from the AdjacencyMatrix using node distances Input: graph (AdjacencyMatrix) = AdjacencyMatrix to build heap from Output: (list) adhering to min heap invariant"""
        min_heap = []
        for label, node in self.graph.nodes.items():
            node_container = NodeContainer(node)
            heappush(min_heap, node_container)
        return min_heap

    def shortest_distance(self):
        """Input: Output: (int) representing shortest distance to the destination from the source"""
        if self.dest.distance == float('inf'):
            self.build_shortest_path()
        return self.dest.distance

    def shortest_path(self):
        """Input: Output: (list) representing shortest path to the destination from the source"""
        if self.dest.distance == float('inf'):
            self.build_shortest_path()
        current_node = self.dest
        path = [current_node.label]
        while current_node.previous:
            path.append(current_node.previous.label)
            current_node = current_node.previous
        path.reverse()
        return path

    def build_shortest_path(self):
        """Actual implementation of Dijkstras Algorithm to get shortest path Input: Output:"""
        while self.nodes_heap:
            current_node = heappop(self.nodes_heap)
            for node_label, edge_weight in enumerate(current_node.edges):
                if edge_weight and node_label in self.nodes_heap:
                    neighbor = self.nodes_heap[self.nodes_heap.index(node_label)]
                    if neighbor.distance > current_node.distance + edge_weight:
                        neighbor.distance = current_node.distance + edge_weight
                        neighbor.previous = current_node
            heapify(self.nodes_heap)


intersect

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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def intersect(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
- def intersectSort(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int]

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def intersect(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
- def intersectSort(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int]

<|skeleton|>
class Solution:

    def intersect(self, nums1, nums2):
        """:type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
        <|body_0|>

    def intersectSort(self, nums1, nums2):
        """:type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        m = {}
        res = []
        for i in nums1:
            m[i] = m.setdefault(i, 0) + 1
        for i in nums2:
            if i in m and m[i] > 0:
                res.append(i)
                m[i] -= 1
        return res
<|end_body_0|>

<|body_start_1|>
        nums1.sort()
        nums2.sort()
        i, j = (0, 0)
        res = []
        while i < len(nums1) and j < len(nums2):
            if nums1[i] == nums2[j]:
                res.append(nums1[i])
                i += 1
                j += 1
            elif nums1[i] > nums2[j]:
                j += 1
            else:
                i += 1
        return res
<|end_body_1|>

Solution:
class Solution:
    def intersect(self, nums1, nums2):
        """:type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
        m = {}
        res = []
        for i in nums1:
            m[i] = m.setdefault(i, 0) + 1
        for i in nums2:
            if i in m and m[i] > 0:
                res.append(i)
                m[i] -= 1
        return res

    def intersectSort(self, nums1, nums2):
        """:type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
        nums1.sort()
        nums2.sort()
        i, j = (0, 0)
        res = []
        while i < len(nums1) and j < len(nums2):
            if nums1[i] == nums2[j]:
                res.append(nums1[i])
                i += 1
                j += 1
            elif nums1[i] > nums2[j]:
                j += 1
            else:
                i += 1
        return res


reverseList

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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: Natural solutions (iteratively and recursively)
- def reverseList1(self, head): recursively
- def reverseList2(self, head): iteratively

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: Natural solutions (iteratively and recursively)
- def reverseList1(self, head): recursively
- def reverseList2(self, head): iteratively

<|skeleton|>
class Solution:

    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        """Natural solutions (iteratively and recursively)"""
        <|body_0|>

    def reverseList1(self, head):
        """recursively"""
        <|body_1|>

    def reverseList2(self, head):
        """iteratively"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        prev = None
        while head:
            next_node = head.next
            head.next = prev
            prev = head
            head = next_node
        return prev
<|end_body_0|>

<|body_start_1|>
        if not (head and head.next):
            return head
        res = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return res
<|end_body_1|>

<|body_start_2|>
        if not head:
            return head
        res = ListNode(0)
        while head:
            cur = res.next
            res.next = ListNode(head.val)
            res.next.next = cur
            head = head.next
        return res.next
<|end_body_2|>

Solution:
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        """Natural solutions (iteratively and recursively)"""
        prev = None
        while head:
            next_node = head.next
            head.next = prev
            prev = head
            head = next_node
        return prev

    def reverseList1(self, head):
        """recursively"""
        if not (head and head.next):
            return head
        res = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return res

    def reverseList2(self, head):
        """iteratively"""
        if not head:
            return head
        res = ListNode(0)
        while head:
            cur = res.next
            res.next = ListNode(head.val)
            res.next.next = cur
            head = head.next
        return res.next


testGetReportDescriptor

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

Class description:
Implement the ReportPluginsTest class.

Method signatures and docstrings:
- def testGetAvailableReportPlugins(self): Ensure GetAvailableReportPlugins lists ReportPluginBase's subclasses.
- def testGetReportByName(self): Ensure GetReportByName instantiates correct subclasses based on name.
- def testGetReportDescriptor(self): Ensure GetReportDescriptor returns a correctly filled in proto.

Implement the Python class `ReportPluginsTest` described below.

Class description:
Implement the ReportPluginsTest class.

Method signatures and docstrings:
- def testGetAvailableReportPlugins(self): Ensure GetAvailableReportPlugins lists ReportPluginBase's subclasses.
- def testGetReportByName(self): Ensure GetReportByName instantiates correct subclasses based on name.
- def testGetReportDescriptor(self): Ensure GetReportDescriptor returns a correctly filled in proto.

<|skeleton|>
class ReportPluginsTest:

    def testGetAvailableReportPlugins(self):
        """Ensure GetAvailableReportPlugins lists ReportPluginBase's subclasses."""
        <|body_0|>

    def testGetReportByName(self):
        """Ensure GetReportByName instantiates correct subclasses based on name."""
        <|body_1|>

    def testGetReportDescriptor(self):
        """Ensure GetReportDescriptor returns a correctly filled in proto."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        with report_plugins_test_mocks.MockedReportPlugins():
            self.assertIn(report_plugins_test_mocks.FooReportPlugin, report_plugins.GetAvailableReportPlugins())
            self.assertIn(report_plugins_test_mocks.BarReportPlugin, report_plugins.GetAvailableReportPlugins())
<|end_body_0|>

<|body_start_1|>
        with report_plugins_test_mocks.MockedReportPlugins():
            report_object = report_plugins.GetReportByName('BarReportPlugin')
            self.assertIsInstance(report_object, report_plugins_test_mocks.BarReportPlugin)
<|end_body_1|>

<|body_start_2|>
        desc = report_plugins_test_mocks.BarReportPlugin.GetReportDescriptor()
        self.assertEqual(desc.type, rdf_report_plugins.ApiReportDescriptor.ReportType.SERVER)
        self.assertEqual(desc.title, 'Bar Activity')
        self.assertEqual(desc.summary, "Reports bars' activity in the given time range.")
        self.assertEqual(desc.requires_time_range, True)
<|end_body_2|>

Solution:
class ReportPluginsTest:
    def testGetAvailableReportPlugins(self):
        """Ensure GetAvailableReportPlugins lists ReportPluginBase's subclasses."""
        with report_plugins_test_mocks.MockedReportPlugins():
            self.assertIn(report_plugins_test_mocks.FooReportPlugin, report_plugins.GetAvailableReportPlugins())
            self.assertIn(report_plugins_test_mocks.BarReportPlugin, report_plugins.GetAvailableReportPlugins())

    def testGetReportByName(self):
        """Ensure GetReportByName instantiates correct subclasses based on name."""
        with report_plugins_test_mocks.MockedReportPlugins():
            report_object = report_plugins.GetReportByName('BarReportPlugin')
            self.assertIsInstance(report_object, report_plugins_test_mocks.BarReportPlugin)

    def testGetReportDescriptor(self):
        """Ensure GetReportDescriptor returns a correctly filled in proto."""
        desc = report_plugins_test_mocks.BarReportPlugin.GetReportDescriptor()
        self.assertEqual(desc.type, rdf_report_plugins.ApiReportDescriptor.ReportType.SERVER)
        self.assertEqual(desc.title, 'Bar Activity')
        self.assertEqual(desc.summary, "Reports bars' activity in the given time range.")
        self.assertEqual(desc.requires_time_range, True)


clear

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

Class description:
A class to store the evaluation metrics.

Method signatures and docstrings:
- def __init__(self, num_class, top_k, accumulate_per_tag=False): Construct an EvaluationMetrics object to store the evaluation metrics. Args: num_class: A positive integer specifying the number of classes. top_k: A positive integer specifying how many predictions are considered per video. Raises: ValueError: An error occurred when MeanAveragePrecisionCalculator cannot not be constructed.
- def accumulate(self, predictions, labels, loss): Accumulate the metrics calculated locally for this mini-batch. Args: predictions: A numpy matrix containing the outputs of the model. Dimensions are 'batch' x 'num_classes'. labels: A numpy matrix containing the ground truth labels. Dimensions are 'batch' x 'num_classes'. loss: A numpy array containing the loss for each sample. Returns: dictionary: A dictionary storing the metrics for the mini-batch. Raises: ValueError: An error occurred when the shape of predictions and actuals does not match.
- def get(self): Calculate the evaluation metrics for the whole epoch. Raises: ValueError: If no examples were accumulated. Returns: dictionary: a dictionary storing the evaluation metrics for the epoch. The dictionary has the fields: avg_hit_at_one, avg_perr, avg_loss, and aps (default nan).
- def clear(self): Clear the evaluation metrics and reset the EvaluationMetrics object.

Implement the Python class `EvaluationMetrics` described below.

Class description:
A class to store the evaluation metrics.

Method signatures and docstrings:
- def __init__(self, num_class, top_k, accumulate_per_tag=False): Construct an EvaluationMetrics object to store the evaluation metrics. Args: num_class: A positive integer specifying the number of classes. top_k: A positive integer specifying how many predictions are considered per video. Raises: ValueError: An error occurred when MeanAveragePrecisionCalculator cannot not be constructed.
- def accumulate(self, predictions, labels, loss): Accumulate the metrics calculated locally for this mini-batch. Args: predictions: A numpy matrix containing the outputs of the model. Dimensions are 'batch' x 'num_classes'. labels: A numpy matrix containing the ground truth labels. Dimensions are 'batch' x 'num_classes'. loss: A numpy array containing the loss for each sample. Returns: dictionary: A dictionary storing the metrics for the mini-batch. Raises: ValueError: An error occurred when the shape of predictions and actuals does not match.
- def get(self): Calculate the evaluation metrics for the whole epoch. Raises: ValueError: If no examples were accumulated. Returns: dictionary: a dictionary storing the evaluation metrics for the epoch. The dictionary has the fields: avg_hit_at_one, avg_perr, avg_loss, and aps (default nan).
- def clear(self): Clear the evaluation metrics and reset the EvaluationMetrics object.

<|skeleton|>
class EvaluationMetrics:
    """A class to store the evaluation metrics."""

    def __init__(self, num_class, top_k, accumulate_per_tag=False):
        """Construct an EvaluationMetrics object to store the evaluation metrics. Args: num_class: A positive integer specifying the number of classes. top_k: A positive integer specifying how many predictions are considered per video. Raises: ValueError: An error occurred when MeanAveragePrecisionCalculator cannot not be constructed."""
        <|body_0|>

    def accumulate(self, predictions, labels, loss):
        """Accumulate the metrics calculated locally for this mini-batch. Args: predictions: A numpy matrix containing the outputs of the model. Dimensions are 'batch' x 'num_classes'. labels: A numpy matrix containing the ground truth labels. Dimensions are 'batch' x 'num_classes'. loss: A numpy array containing the loss for each sample. Returns: dictionary: A dictionary storing the metrics for the mini-batch. Raises: ValueError: An error occurred when the shape of predictions and actuals does not match."""
        <|body_1|>

    def get(self):
        """Calculate the evaluation metrics for the whole epoch. Raises: ValueError: If no examples were accumulated. Returns: dictionary: a dictionary storing the evaluation metrics for the epoch. The dictionary has the fields: avg_hit_at_one, avg_perr, avg_loss, and aps (default nan)."""
        <|body_2|>

    def clear(self):
        """Clear the evaluation metrics and reset the EvaluationMetrics object."""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        self.sum_hit_at_one = 0.0
        self.sum_perr = 0.0
        self.sum_loss = 0.0
        self.map_calculator = map_calculator.MeanAveragePrecisionCalculator(num_class)
        self.global_ap_calculator = ap_calculator.AveragePrecisionCalculator()
        self.pr_calculator = PRCalculator()
        self.pr_calculator_per_tag = PRCalculatorPerTag(num_class)
        self.accumulate_per_tag = accumulate_per_tag
        self.top_k = top_k
        self.num_examples = 0
        self.nums_per_tag = np.zeros(num_class)
        self.tag_corrlation = np.zeros((num_class, num_class))
        self.tag_confidence = np.zeros(num_class)
<|end_body_0|>

<|body_start_1|>
        batch_size = labels.shape[0]
        mean_hit_at_one = calculate_hit_at_one(predictions, labels)
        mean_perr = calculate_precision_at_equal_recall_rate(predictions, labels)
        mean_loss = loss
        self.nums_per_tag = self.nums_per_tag + get_tag_stat(labels)
        self.tag_correlation = self.tag_correlation + get_tag_correlation(predictions, labels, self.top_k)
        self.tag_confidence = self.tag_confidence + get_tag_confidence(predictions, labels)
        self.pr_calculator.accumulate(predictions, labels)
        if self.accumulate_per_tag:
            self.pr_calculator_per_tag.accumulate(predictions, labels)
        sparse_predictions, sparse_labels, num_positives = top_k_by_class(predictions, labels, self.top_k)
        self.map_calculator.accumulate(sparse_predictions, sparse_labels, num_positives)
        self.global_ap_calculator.accumulate(flatten(sparse_predictions), flatten(sparse_labels), sum(num_positives))
        self.num_examples += batch_size
        self.sum_hit_at_one += mean_hit_at_one * batch_size
        self.sum_perr += mean_perr * batch_size
        self.sum_loss += mean_loss * batch_size
        return {'hit_at_one': mean_hit_at_one, 'perr': mean_perr, 'loss': mean_loss}
<|end_body_1|>

<|body_start_2|>
        if self.num_examples <= 0:
            raise ValueError('total_sample must be positive.')
        avg_hit_at_one = self.sum_hit_at_one / self.num_examples
        avg_perr = self.sum_perr / self.num_examples
        avg_loss = self.sum_loss / self.num_examples
        aps = self.map_calculator.peek_map_at_n()
        gap = self.global_ap_calculator.peek_ap_at_n()
        tag_confidence = self.tag_confidence / (self.nums_per_tag + 1e-10)
        precision_at_1 = self.pr_calculator.get_precision_at_conf(0.1)
        recall_at_1 = self.pr_calculator.get_recall_at_conf(0.1)
        precision_at_5 = self.pr_calculator.get_precision_at_conf(0.5)
        recall_at_5 = self.pr_calculator.get_recall_at_conf(0.5)
        tag_precision = self.pr_calculator_per_tag.get_precision_list(0.5) if self.accumulate_per_tag else []
        tag_recall = self.pr_calculator_per_tag.get_recall_list(0.5) if self.accumulate_per_tag else []
        epoch_info_dict = {'avg_hit_at_one': avg_hit_at_one, 'avg_perr': avg_perr, 'avg_loss': avg_loss, 'aps': aps, 'gap': gap, 'num': self.nums_per_tag, 'tag_correlation': self.tag_correlation, 'tag_confidence': tag_confidence, 'precision_at_1': precision_at_1, 'recall_at_1': recall_at_1, 'precision_at_5': precision_at_5, 'recall_at_5': recall_at_5, 'tag_precision': tag_precision, 'tag_recall': tag_recall}
        return epoch_info_dict
<|end_body_2|>

<|body_start_3|>
        self.sum_hit_at_one = 0.0
        self.sum_perr = 0.0
        self.sum_loss = 0.0
        self.map_calculator.clear()
        self.global_ap_calculator.clear()
        self.pr_calculator.clear()
        self.pr_calculator_per_tag.clear()
        self.num_examples = 0
        self.tag_correlation = 0.0
        self.nums_per_tag = 0.0
        self.tag_confidence = 0.0
<|end_body_3|>

Solution:
class EvaluationMetrics:
    """A class to store the evaluation metrics."""

    def __init__(self, num_class, top_k, accumulate_per_tag=False):
        """Construct an EvaluationMetrics object to store the evaluation metrics. Args: num_class: A positive integer specifying the number of classes. top_k: A positive integer specifying how many predictions are considered per video. Raises: ValueError: An error occurred when MeanAveragePrecisionCalculator cannot not be constructed."""
        self.sum_hit_at_one = 0.0
        self.sum_perr = 0.0
        self.sum_loss = 0.0
        self.map_calculator = map_calculator.MeanAveragePrecisionCalculator(num_class)
        self.global_ap_calculator = ap_calculator.AveragePrecisionCalculator()
        self.pr_calculator = PRCalculator()
        self.pr_calculator_per_tag = PRCalculatorPerTag(num_class)
        self.accumulate_per_tag = accumulate_per_tag
        self.top_k = top_k
        self.num_examples = 0
        self.nums_per_tag = np.zeros(num_class)
        self.tag_corrlation = np.zeros((num_class, num_class))
        self.tag_confidence = np.zeros(num_class)

    def accumulate(self, predictions, labels, loss):
        """Accumulate the metrics calculated locally for this mini-batch. Args: predictions: A numpy matrix containing the outputs of the model. Dimensions are 'batch' x 'num_classes'. labels: A numpy matrix containing the ground truth labels. Dimensions are 'batch' x 'num_classes'. loss: A numpy array containing the loss for each sample. Returns: dictionary: A dictionary storing the metrics for the mini-batch. Raises: ValueError: An error occurred when the shape of predictions and actuals does not match."""
        batch_size = labels.shape[0]
        mean_hit_at_one = calculate_hit_at_one(predictions, labels)
        mean_perr = calculate_precision_at_equal_recall_rate(predictions, labels)
        mean_loss = loss
        self.nums_per_tag = self.nums_per_tag + get_tag_stat(labels)
        self.tag_correlation = self.tag_correlation + get_tag_correlation(predictions, labels, self.top_k)
        self.tag_confidence = self.tag_confidence + get_tag_confidence(predictions, labels)
        self.pr_calculator.accumulate(predictions, labels)
        if self.accumulate_per_tag:
            self.pr_calculator_per_tag.accumulate(predictions, labels)
        sparse_predictions, sparse_labels, num_positives = top_k_by_class(predictions, labels, self.top_k)
        self.map_calculator.accumulate(sparse_predictions, sparse_labels, num_positives)
        self.global_ap_calculator.accumulate(flatten(sparse_predictions), flatten(sparse_labels), sum(num_positives))
        self.num_examples += batch_size
        self.sum_hit_at_one += mean_hit_at_one * batch_size
        self.sum_perr += mean_perr * batch_size
        self.sum_loss += mean_loss * batch_size
        return {'hit_at_one': mean_hit_at_one, 'perr': mean_perr, 'loss': mean_loss}

    def get(self):
        """Calculate the evaluation metrics for the whole epoch. Raises: ValueError: If no examples were accumulated. Returns: dictionary: a dictionary storing the evaluation metrics for the epoch. The dictionary has the fields: avg_hit_at_one, avg_perr, avg_loss, and aps (default nan)."""
        if self.num_examples <= 0:
            raise ValueError('total_sample must be positive.')
        avg_hit_at_one = self.sum_hit_at_one / self.num_examples
        avg_perr = self.sum_perr / self.num_examples
        avg_loss = self.sum_loss / self.num_examples
        aps = self.map_calculator.peek_map_at_n()
        gap = self.global_ap_calculator.peek_ap_at_n()
        tag_confidence = self.tag_confidence / (self.nums_per_tag + 1e-10)
        precision_at_1 = self.pr_calculator.get_precision_at_conf(0.1)
        recall_at_1 = self.pr_calculator.get_recall_at_conf(0.1)
        precision_at_5 = self.pr_calculator.get_precision_at_conf(0.5)
        recall_at_5 = self.pr_calculator.get_recall_at_conf(0.5)
        tag_precision = self.pr_calculator_per_tag.get_precision_list(0.5) if self.accumulate_per_tag else []
        tag_recall = self.pr_calculator_per_tag.get_recall_list(0.5) if self.accumulate_per_tag else []
        epoch_info_dict = {'avg_hit_at_one': avg_hit_at_one, 'avg_perr': avg_perr, 'avg_loss': avg_loss, 'aps': aps, 'gap': gap, 'num': self.nums_per_tag, 'tag_correlation': self.tag_correlation, 'tag_confidence': tag_confidence, 'precision_at_1': precision_at_1, 'recall_at_1': recall_at_1, 'precision_at_5': precision_at_5, 'recall_at_5': recall_at_5, 'tag_precision': tag_precision, 'tag_recall': tag_recall}
        return epoch_info_dict

    def clear(self):
        """Clear the evaluation metrics and reset the EvaluationMetrics object."""
        self.sum_hit_at_one = 0.0
        self.sum_perr = 0.0
        self.sum_loss = 0.0
        self.map_calculator.clear()
        self.global_ap_calculator.clear()
        self.pr_calculator.clear()
        self.pr_calculator_per_tag.clear()
        self.num_examples = 0
        self.tag_correlation = 0.0
        self.nums_per_tag = 0.0
        self.tag_confidence = 0.0


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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def rand10(self): 拒绝采样
- def rand10_new(self): 拒绝采样-减少舍弃数字

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def rand10(self): 拒绝采样
- def rand10_new(self): 拒绝采样-减少舍弃数字

<|skeleton|>
class Solution:

    def rand10(self):
        """拒绝采样"""
        <|body_0|>

    def rand10_new(self):
        """拒绝采样-减少舍弃数字"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        while True:
            num = (rand7() - 1) * 7 + rand7()
            if num <= 40:
                return num % 10 + 1
<|end_body_0|>

<|body_start_1|>
        while True:
            num = (rand7() - 1) * 7 + rand7()
            if num <= 40:
                return num % 10 + 1
            rand9 = num - 40
            num = (rand9 - 1) * 7 + rand7()
            if num <= 60:
                return num % 10 + 1
            rand3 = num - 60
            num = (rand3 - 1) * 7 + rand7()
            if num <= 20:
                return num % 10 + 1
<|end_body_1|>

Solution:
class Solution:
    def rand10(self):
        """拒绝采样"""
        while True:
            num = (rand7() - 1) * 7 + rand7()
            if num <= 40:
                return num % 10 + 1

    def rand10_new(self):
        """拒绝采样-减少舍弃数字"""
        while True:
            num = (rand7() - 1) * 7 + rand7()
            if num <= 40:
                return num % 10 + 1
            rand9 = num - 40
            num = (rand9 - 1) * 7 + rand7()
            if num <= 60:
                return num % 10 + 1
            rand3 = num - 60
            num = (rand3 - 1) * 7 + rand7()
            if num <= 20:
                return num % 10 + 1


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

Class description:
Routine to find the ge transition frequency via qubit spectroscopy. A series of qubit spectroscopies is performed. A Decision step decides whether a fit failed for some qubits and whether to rerun the spectroscopy for them. The user can specify the number of spectroscopies via the keyword "n_spectroscopies" in the configuration parameter dictionary. The settings of each spectroscopy can be specified by using their unique label. For example, a routine with 2 spectroscopies can have the following routine steps: 1) QubitSpectroscopy1DStep (qubit_spectroscopy_<n>): Performs a qubit spectroscopy and fits the result with a Lorentzian to extract the ge transition frequency. 2) Decision (decision_sp

Method signatures and docstrings:
- def __init__(self, dev: Device, qubits: List[QuDev_transmon], **kw): Initialize the AdaptiveQubitSpectroscopy routine. Args: dev (Device): Device to be used for the routine qubits (list): The qubits which should be calibrated. By default, all qubits of the device are selected. Configuration parameters (coming from the configuration parameter dictionary): n_spectroscopies (int): Number of (successful) spectroscopies that will be run. max_iterations (int): Maximum number of iterations that will be performed if a spectroscopy fails. auto_repetition_settings (bool): Whether the settings of the repeated spectroscopy should be automatically set. If True, the range of the sweep and the density of the sweep points will be doubled at each repetition. max_waiting_secon
- def create_routine_template(self): Creates the routine template for the AdaptiveQubitSpectroscopy routine.
- def add_rerun_qubit_spectroscopy_step(self, index_spectroscopy, index_iteration, qubits): Adds a next QubitSpectroscopy1DStep followed by a Decision step Args: index_spectroscopy (int): Index of the spectroscopy whose fit failed. index_iteration (int): Index of the iteration for the spectroscopy with index `index_spectroscopy`. qubits (list): List of qubits (QuDev_transmon objects) whose spectroscopy should be run again.

Implement the Python class `AdaptiveQubitSpectroscopy` described below.

Class description:
Routine to find the ge transition frequency via qubit spectroscopy. A series of qubit spectroscopies is performed. A Decision step decides whether a fit failed for some qubits and whether to rerun the spectroscopy for them. The user can specify the number of spectroscopies via the keyword "n_spectroscopies" in the configuration parameter dictionary. The settings of each spectroscopy can be specified by using their unique label. For example, a routine with 2 spectroscopies can have the following routine steps: 1) QubitSpectroscopy1DStep (qubit_spectroscopy_<n>): Performs a qubit spectroscopy and fits the result with a Lorentzian to extract the ge transition frequency. 2) Decision (decision_sp

Method signatures and docstrings:
- def __init__(self, dev: Device, qubits: List[QuDev_transmon], **kw): Initialize the AdaptiveQubitSpectroscopy routine. Args: dev (Device): Device to be used for the routine qubits (list): The qubits which should be calibrated. By default, all qubits of the device are selected. Configuration parameters (coming from the configuration parameter dictionary): n_spectroscopies (int): Number of (successful) spectroscopies that will be run. max_iterations (int): Maximum number of iterations that will be performed if a spectroscopy fails. auto_repetition_settings (bool): Whether the settings of the repeated spectroscopy should be automatically set. If True, the range of the sweep and the density of the sweep points will be doubled at each repetition. max_waiting_secon
- def create_routine_template(self): Creates the routine template for the AdaptiveQubitSpectroscopy routine.
- def add_rerun_qubit_spectroscopy_step(self, index_spectroscopy, index_iteration, qubits): Adds a next QubitSpectroscopy1DStep followed by a Decision step Args: index_spectroscopy (int): Index of the spectroscopy whose fit failed. index_iteration (int): Index of the iteration for the spectroscopy with index `index_spectroscopy`. qubits (list): List of qubits (QuDev_transmon objects) whose spectroscopy should be run again.

<|skeleton|>
class AdaptiveQubitSpectroscopy:
    """Routine to find the ge transition frequency via qubit spectroscopy. A series of qubit spectroscopies is performed. A Decision step decides whether a fit failed for some qubits and whether to rerun the spectroscopy for them. The user can specify the number of spectroscopies via the keyword "n_spectroscopies" in the configuration parameter dictionary. The settings of each spectroscopy can be specified by using their unique label. For example, a routine with 2 spectroscopies can have the following routine steps: 1) QubitSpectroscopy1DStep (qubit_spectroscopy_<n>): Performs a qubit spectroscopy and fits the result with a Lorentzian to extract the ge transition frequency. 2) Decision (decision_sp"""

    def __init__(self, dev: Device, qubits: List[QuDev_transmon], **kw):
        """Initialize the AdaptiveQubitSpectroscopy routine. Args: dev (Device): Device to be used for the routine qubits (list): The qubits which should be calibrated. By default, all qubits of the device are selected. Configuration parameters (coming from the configuration parameter dictionary): n_spectroscopies (int): Number of (successful) spectroscopies that will be run. max_iterations (int): Maximum number of iterations that will be performed if a spectroscopy fails. auto_repetition_settings (bool): Whether the settings of the repeated spectroscopy should be automatically set. If True, the range of the sweep and the density of the sweep points will be doubled at each repetition. max_waiting_secon"""
        <|body_0|>

    def create_routine_template(self):
        """Creates the routine template for the AdaptiveQubitSpectroscopy routine."""
        <|body_1|>

    def add_rerun_qubit_spectroscopy_step(self, index_spectroscopy, index_iteration, qubits):
        """Adds a next QubitSpectroscopy1DStep followed by a Decision step Args: index_spectroscopy (int): Index of the spectroscopy whose fit failed. index_iteration (int): Index of the iteration for the spectroscopy with index `index_spectroscopy`. qubits (list): List of qubits (QuDev_transmon objects) whose spectroscopy should be run again."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        super().__init__(dev=dev, qubits=qubits, **kw)
        self.index_iteration = 1
        self.index_spectroscopy = 1
        self.previous_freqs = {qb.name: qb.ge_freq() for qb in qubits}
        self.results = {}
        self.final_init(**kw)
<|end_body_0|>

<|body_start_1|>
        super().create_routine_template()
        for i in range(self.get_param_value('n_spectroscopies', default=2)):
            qb_spec_settings = {'qubits': self.qubits}
            self.add_step(QubitSpectroscopy1DStep, f'qubit_spectroscopy_{i + 1}', qb_spec_settings)
            decision_settings = {'qubits': self.qubits}
            self.add_step(self.Decision, f'decision_spectroscopy_{i + 1}', decision_settings)
<|end_body_1|>

<|body_start_2|>
        settings = {'QubitSpectroscopy1D': {'qubits': {}}}
        if self.get_param_value('auto_repetition_settings', default=False):
            previous_qb_spec: QubitSpectroscopy1DStep = self.routine_steps[-1]
            for qb in qubits:
                settings['QubitSpectroscopy1D']['qubits'][qb.name] = {'freq_range': previous_qb_spec.freq_ranges[qb.name] * 2, 'freq_center': previous_qb_spec.freq_centers[qb.name], 'spec_power': previous_qb_spec.spec_powers[qb.name][1], 'pts': previous_qb_spec.pts[qb.name] * 4}
        self.add_step(*[QubitSpectroscopy1DStep, f'qubit_spectroscopy_{index_spectroscopy}_repetition_{index_iteration}', {'settings': settings, 'qubits': qubits}], index=self.current_step_index + 1)
        self.add_step(*[self.Decision, f'decision_spectroscopy_{index_spectroscopy}_repetition_{index_iteration}', {'qubits': qubits}], index=self.current_step_index + 2)
<|end_body_2|>

Solution:
class AdaptiveQubitSpectroscopy:
    """Routine to find the ge transition frequency via qubit spectroscopy. A series of qubit spectroscopies is performed. A Decision step decides whether a fit failed for some qubits and whether to rerun the spectroscopy for them. The user can specify the number of spectroscopies via the keyword "n_spectroscopies" in the configuration parameter dictionary. The settings of each spectroscopy can be specified by using their unique label. For example, a routine with 2 spectroscopies can have the following routine steps: 1) QubitSpectroscopy1DStep (qubit_spectroscopy_<n>): Performs a qubit spectroscopy and fits the result with a Lorentzian to extract the ge transition frequency. 2) Decision (decision_sp"""

    def __init__(self, dev: Device, qubits: List[QuDev_transmon], **kw):
        """Initialize the AdaptiveQubitSpectroscopy routine. Args: dev (Device): Device to be used for the routine qubits (list): The qubits which should be calibrated. By default, all qubits of the device are selected. Configuration parameters (coming from the configuration parameter dictionary): n_spectroscopies (int): Number of (successful) spectroscopies that will be run. max_iterations (int): Maximum number of iterations that will be performed if a spectroscopy fails. auto_repetition_settings (bool): Whether the settings of the repeated spectroscopy should be automatically set. If True, the range of the sweep and the density of the sweep points will be doubled at each repetition. max_waiting_secon"""
        super().__init__(dev=dev, qubits=qubits, **kw)
        self.index_iteration = 1
        self.index_spectroscopy = 1
        self.previous_freqs = {qb.name: qb.ge_freq() for qb in qubits}
        self.results = {}
        self.final_init(**kw)

    def create_routine_template(self):
        """Creates the routine template for the AdaptiveQubitSpectroscopy routine."""
        super().create_routine_template()
        for i in range(self.get_param_value('n_spectroscopies', default=2)):
            qb_spec_settings = {'qubits': self.qubits}
            self.add_step(QubitSpectroscopy1DStep, f'qubit_spectroscopy_{i + 1}', qb_spec_settings)
            decision_settings = {'qubits': self.qubits}
            self.add_step(self.Decision, f'decision_spectroscopy_{i + 1}', decision_settings)

    def add_rerun_qubit_spectroscopy_step(self, index_spectroscopy, index_iteration, qubits):
        """Adds a next QubitSpectroscopy1DStep followed by a Decision step Args: index_spectroscopy (int): Index of the spectroscopy whose fit failed. index_iteration (int): Index of the iteration for the spectroscopy with index `index_spectroscopy`. qubits (list): List of qubits (QuDev_transmon objects) whose spectroscopy should be run again."""
        settings = {'QubitSpectroscopy1D': {'qubits': {}}}
        if self.get_param_value('auto_repetition_settings', default=False):
            previous_qb_spec: QubitSpectroscopy1DStep = self.routine_steps[-1]
            for qb in qubits:
                settings['QubitSpectroscopy1D']['qubits'][qb.name] = {'freq_range': previous_qb_spec.freq_ranges[qb.name] * 2, 'freq_center': previous_qb_spec.freq_centers[qb.name], 'spec_power': previous_qb_spec.spec_powers[qb.name][1], 'pts': previous_qb_spec.pts[qb.name] * 4}
        self.add_step(*[QubitSpectroscopy1DStep, f'qubit_spectroscopy_{index_spectroscopy}_repetition_{index_iteration}', {'settings': settings, 'qubits': qubits}], index=self.current_step_index + 1)
        self.add_step(*[self.Decision, f'decision_spectroscopy_{index_spectroscopy}_repetition_{index_iteration}', {'qubits': qubits}], index=self.current_step_index + 2)


run

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

Class description:
Local TFX DAG runner.

Method signatures and docstrings:
- def __init__(self, config: Optional[pipeline_config.PipelineConfig]=None): Initializes local TFX orchestrator. Args: config: Optional pipeline config for customizing the launching of each component. Defaults to pipeline config that supports InProcessComponentLauncher and DockerComponentLauncher.
- def run(self, tfx_pipeline: pipeline.Pipeline) -> None: Runs given logical pipeline locally. Args: tfx_pipeline: Logical pipeline containing pipeline args and components.

Implement the Python class `LocalDagRunner` described below.

Class description:
Local TFX DAG runner.

Method signatures and docstrings:
- def __init__(self, config: Optional[pipeline_config.PipelineConfig]=None): Initializes local TFX orchestrator. Args: config: Optional pipeline config for customizing the launching of each component. Defaults to pipeline config that supports InProcessComponentLauncher and DockerComponentLauncher.
- def run(self, tfx_pipeline: pipeline.Pipeline) -> None: Runs given logical pipeline locally. Args: tfx_pipeline: Logical pipeline containing pipeline args and components.

<|skeleton|>
class LocalDagRunner:
    """Local TFX DAG runner."""

    def __init__(self, config: Optional[pipeline_config.PipelineConfig]=None):
        """Initializes local TFX orchestrator. Args: config: Optional pipeline config for customizing the launching of each component. Defaults to pipeline config that supports InProcessComponentLauncher and DockerComponentLauncher."""
        <|body_0|>

    def run(self, tfx_pipeline: pipeline.Pipeline) -> None:
        """Runs given logical pipeline locally. Args: tfx_pipeline: Logical pipeline containing pipeline args and components."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if config is None:
            config = pipeline_config.PipelineConfig(supported_launcher_classes=[in_process_component_launcher.InProcessComponentLauncher, docker_component_launcher.DockerComponentLauncher])
        super().__init__(config)
<|end_body_0|>

<|body_start_1|>
        tfx_pipeline.pipeline_info.run_id = datetime.datetime.now().isoformat()
        with telemetry_utils.scoped_labels({telemetry_utils.LABEL_TFX_RUNNER: 'local'}):
            for component in tfx_pipeline.components:
                if isinstance(component, base_component.BaseComponent):
                    component._resolve_pip_dependencies(tfx_pipeline.pipeline_info.pipeline_root)
                component_launcher_class, component_config = config_utils.find_component_launch_info(self._config, component)
                driver_args = data_types.DriverArgs(enable_cache=tfx_pipeline.enable_cache)
                metadata_connection = metadata.Metadata(tfx_pipeline.metadata_connection_config)
                node_launcher = component_launcher_class.create(component=component, pipeline_info=tfx_pipeline.pipeline_info, driver_args=driver_args, metadata_connection=metadata_connection, beam_pipeline_args=tfx_pipeline.beam_pipeline_args, additional_pipeline_args=tfx_pipeline.additional_pipeline_args, component_config=component_config)
                logging.info('Component %s is running.', component.id)
                node_launcher.launch()
                logging.info('Component %s is finished.', component.id)
<|end_body_1|>

Solution:
class LocalDagRunner:
    """Local TFX DAG runner."""

    def __init__(self, config: Optional[pipeline_config.PipelineConfig]=None):
        """Initializes local TFX orchestrator. Args: config: Optional pipeline config for customizing the launching of each component. Defaults to pipeline config that supports InProcessComponentLauncher and DockerComponentLauncher."""
        if config is None:
            config = pipeline_config.PipelineConfig(supported_launcher_classes=[in_process_component_launcher.InProcessComponentLauncher, docker_component_launcher.DockerComponentLauncher])
        super().__init__(config)

    def run(self, tfx_pipeline: pipeline.Pipeline) -> None:
        """Runs given logical pipeline locally. Args: tfx_pipeline: Logical pipeline containing pipeline args and components."""
        tfx_pipeline.pipeline_info.run_id = datetime.datetime.now().isoformat()
        with telemetry_utils.scoped_labels({telemetry_utils.LABEL_TFX_RUNNER: 'local'}):
            for component in tfx_pipeline.components:
                if isinstance(component, base_component.BaseComponent):
                    component._resolve_pip_dependencies(tfx_pipeline.pipeline_info.pipeline_root)
                component_launcher_class, component_config = config_utils.find_component_launch_info(self._config, component)
                driver_args = data_types.DriverArgs(enable_cache=tfx_pipeline.enable_cache)
                metadata_connection = metadata.Metadata(tfx_pipeline.metadata_connection_config)
                node_launcher = component_launcher_class.create(component=component, pipeline_info=tfx_pipeline.pipeline_info, driver_args=driver_args, metadata_connection=metadata_connection, beam_pipeline_args=tfx_pipeline.beam_pipeline_args, additional_pipeline_args=tfx_pipeline.additional_pipeline_args, component_config=component_config)
                logging.info('Component %s is running.', component.id)
                node_launcher.launch()
                logging.info('Component %s is finished.', component.id)


deserialize

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

Class description:
Implement the Codec class.

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

Implement the Python class `Codec` described below.

Class description:
Implement the Codec class.

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

<|skeleton|>
class Codec:

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

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

<|end_skeleton|>

<|body_start_0|>
        def helper(node):
            if not node:
                return ''
            if not node.children:
                return str(node.val)
            res = str(node.val) + '['
            for i in range(len(node.children) - 1):
                res += helper(node.children[i])
                res += ' '
            res += helper(node.children[-1])
            res += ']'
            return res
        string = helper(root)
        return string
<|end_body_0|>

<|body_start_1|>
        if not data:
            return None
        start = 0
        while start < len(data) and data[start] != '[':
            start += 1
        root = Node(int(data[:start]), [])
        new_str = []
        count = 0
        left = start + 1
        for i, char in enumerate(data[start + 1:-1]):
            if char == '[':
                count += 1
            elif char == ']':
                count -= 1
            elif char == ' ':
                if count == 0:
                    new_str.append(data[left:i + start + 1])
                    left = i + 2 + start
        if data[left:-1] != '':
            new_str.append(data[left:-1])
        for sub_str in new_str:
            root.children.append(self.deserialize(sub_str))
        return root
<|end_body_1|>

Solution:
class Codec:
    def serialize(self, root: 'Node') -> str:
        """Encodes a tree to a single string. :type root: Node :rtype: str"""
        def helper(node):
            if not node:
                return ''
            if not node.children:
                return str(node.val)
            res = str(node.val) + '['
            for i in range(len(node.children) - 1):
                res += helper(node.children[i])
                res += ' '
            res += helper(node.children[-1])
            res += ']'
            return res
        string = helper(root)
        return string

    def deserialize(self, data: str) -> 'Node':
        """Decodes your encoded data to tree. :type data: str :rtype: Node"""
        if not data:
            return None
        start = 0
        while start < len(data) and data[start] != '[':
            start += 1
        root = Node(int(data[:start]), [])
        new_str = []
        count = 0
        left = start + 1
        for i, char in enumerate(data[start + 1:-1]):
            if char == '[':
                count += 1
            elif char == ']':
                count -= 1
            elif char == ' ':
                if count == 0:
                    new_str.append(data[left:i + start + 1])
                    left = i + 2 + start
        if data[left:-1] != '':
            new_str.append(data[left:-1])
        for sub_str in new_str:
            root.children.append(self.deserialize(sub_str))
        return root


store

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

Class description:
Prioritized Replay buffer. Attributes: max_priority (float): max priority tree_ptr (int): next index of tree alpha (float): alpha parameter for prioritized replay buffer sum_tree (SumSegmentTree): sum tree for prior min_tree (MinSegmentTree): min tree for min prior to get max weight

Method signatures and docstrings:
- def __init__(self, size: int, batch_size: int=32, alpha: float=0.6, n_step: int=1, gamma: float=0.99): Initialization.
- def store(self, obs: OdinsynthEnvStep, act: int, rew: float, next_obs: OdinsynthEnvStep, done: bool) -> Tuple[OdinsynthEnvStep, int, float, OdinsynthEnvStep, bool]: Store experience and priority.
- def sample_batch(self, beta: float=0.4) -> Dict[str, np.ndarray]: Sample a batch of experiences.
- def update_priorities(self, indices: List[int], priorities: np.ndarray): Update priorities of sampled transitions.
- def _sample_proportional(self) -> List[int]: Sample indices based on proportions.
- def _calculate_weight(self, idx: int, beta: float): Calculate the weight of the experience at idx.

Implement the Python class `PrioritizedReplayBuffer` described below.

Class description:
Prioritized Replay buffer. Attributes: max_priority (float): max priority tree_ptr (int): next index of tree alpha (float): alpha parameter for prioritized replay buffer sum_tree (SumSegmentTree): sum tree for prior min_tree (MinSegmentTree): min tree for min prior to get max weight

Method signatures and docstrings:
- def __init__(self, size: int, batch_size: int=32, alpha: float=0.6, n_step: int=1, gamma: float=0.99): Initialization.
- def store(self, obs: OdinsynthEnvStep, act: int, rew: float, next_obs: OdinsynthEnvStep, done: bool) -> Tuple[OdinsynthEnvStep, int, float, OdinsynthEnvStep, bool]: Store experience and priority.
- def sample_batch(self, beta: float=0.4) -> Dict[str, np.ndarray]: Sample a batch of experiences.
- def update_priorities(self, indices: List[int], priorities: np.ndarray): Update priorities of sampled transitions.
- def _sample_proportional(self) -> List[int]: Sample indices based on proportions.
- def _calculate_weight(self, idx: int, beta: float): Calculate the weight of the experience at idx.

<|skeleton|>
class PrioritizedReplayBuffer:
    """Prioritized Replay buffer. Attributes: max_priority (float): max priority tree_ptr (int): next index of tree alpha (float): alpha parameter for prioritized replay buffer sum_tree (SumSegmentTree): sum tree for prior min_tree (MinSegmentTree): min tree for min prior to get max weight"""

    def __init__(self, size: int, batch_size: int=32, alpha: float=0.6, n_step: int=1, gamma: float=0.99):
        """Initialization."""
        <|body_0|>

    def store(self, obs: OdinsynthEnvStep, act: int, rew: float, next_obs: OdinsynthEnvStep, done: bool) -> Tuple[OdinsynthEnvStep, int, float, OdinsynthEnvStep, bool]:
        """Store experience and priority."""
        <|body_1|>

    def sample_batch(self, beta: float=0.4) -> Dict[str, np.ndarray]:
        """Sample a batch of experiences."""
        <|body_2|>

    def update_priorities(self, indices: List[int], priorities: np.ndarray):
        """Update priorities of sampled transitions."""
        <|body_3|>

    def _sample_proportional(self) -> List[int]:
        """Sample indices based on proportions."""
        <|body_4|>

    def _calculate_weight(self, idx: int, beta: float):
        """Calculate the weight of the experience at idx."""
        <|body_5|>

<|end_skeleton|>

<|body_start_0|>
        assert alpha >= 0
        super(PrioritizedReplayBuffer, self).__init__(size, batch_size, n_step, gamma)
        self.max_priority, self.tree_ptr = (1.0, 0)
        self.alpha = alpha
        tree_capacity = 1
        while tree_capacity < self.max_size:
            tree_capacity *= 2
        self.sum_tree = SumSegmentTree(tree_capacity)
        self.min_tree = MinSegmentTree(tree_capacity)
<|end_body_0|>

<|body_start_1|>
        transition = super().store(obs, act, rew, next_obs, done)
        if transition:
            self.sum_tree[self.tree_ptr] = self.max_priority ** self.alpha
            self.min_tree[self.tree_ptr] = self.max_priority ** self.alpha
            self.tree_ptr = (self.tree_ptr + 1) % self.max_size
        return transition
<|end_body_1|>

<|body_start_2|>
        assert len(self) >= self.batch_size
        assert beta > 0
        indices = self._sample_proportional()
        obs = [self.obs_buf[i] for i in indices]
        next_obs = [self.next_obs_buf[i] for i in indices]
        acts = [self.acts_buf[i] for i in indices]
        rews = [self.rews_buf[i] for i in indices]
        done = [self.done_buf[i] for i in indices]
        weights = np.array([self._calculate_weight(i, beta) for i in indices])
        return PrioritizedExperienceReplayBatch(obs, acts, rews, next_obs, done, weights, indices)
<|end_body_2|>

<|body_start_3|>
        assert len(indices) == len(priorities)
        for idx, priority in zip(indices, priorities):
            assert priority > 0
            assert 0 <= idx < len(self)
            self.sum_tree[idx] = priority ** self.alpha
            self.min_tree[idx] = priority ** self.alpha
            self.max_priority = max(self.max_priority, priority)
<|end_body_3|>

<|body_start_4|>
        indices = []
        p_total = self.sum_tree.sum(0, len(self) - 1)
        segment = p_total / self.batch_size
        for i in range(self.batch_size):
            a = segment * i
            b = segment * (i + 1)
            upperbound = random.uniform(a, b)
            idx = self.sum_tree.retrieve(upperbound)
            indices.append(idx)
        return indices
<|end_body_4|>

<|body_start_5|>
        p_min = self.min_tree.min() / self.sum_tree.sum()
        max_weight = (p_min * len(self)) ** (-beta)
        p_sample = self.sum_tree[idx] / self.sum_tree.sum()
        weight = (p_sample * len(self)) ** (-beta)
        weight = weight / max_weight
        return weight
<|end_body_5|>

Solution:
class PrioritizedReplayBuffer:
    """Prioritized Replay buffer. Attributes: max_priority (float): max priority tree_ptr (int): next index of tree alpha (float): alpha parameter for prioritized replay buffer sum_tree (SumSegmentTree): sum tree for prior min_tree (MinSegmentTree): min tree for min prior to get max weight"""

    def __init__(self, size: int, batch_size: int=32, alpha: float=0.6, n_step: int=1, gamma: float=0.99):
        """Initialization."""
        assert alpha >= 0
        super(PrioritizedReplayBuffer, self).__init__(size, batch_size, n_step, gamma)
        self.max_priority, self.tree_ptr = (1.0, 0)
        self.alpha = alpha
        tree_capacity = 1
        while tree_capacity < self.max_size:
            tree_capacity *= 2
        self.sum_tree = SumSegmentTree(tree_capacity)
        self.min_tree = MinSegmentTree(tree_capacity)

    def store(self, obs: OdinsynthEnvStep, act: int, rew: float, next_obs: OdinsynthEnvStep, done: bool) -> Tuple[OdinsynthEnvStep, int, float, OdinsynthEnvStep, bool]:
        """Store experience and priority."""
        transition = super().store(obs, act, rew, next_obs, done)
        if transition:
            self.sum_tree[self.tree_ptr] = self.max_priority ** self.alpha
            self.min_tree[self.tree_ptr] = self.max_priority ** self.alpha
            self.tree_ptr = (self.tree_ptr + 1) % self.max_size
        return transition

    def sample_batch(self, beta: float=0.4) -> Dict[str, np.ndarray]:
        """Sample a batch of experiences."""
        assert len(self) >= self.batch_size
        assert beta > 0
        indices = self._sample_proportional()
        obs = [self.obs_buf[i] for i in indices]
        next_obs = [self.next_obs_buf[i] for i in indices]
        acts = [self.acts_buf[i] for i in indices]
        rews = [self.rews_buf[i] for i in indices]
        done = [self.done_buf[i] for i in indices]
        weights = np.array([self._calculate_weight(i, beta) for i in indices])
        return PrioritizedExperienceReplayBatch(obs, acts, rews, next_obs, done, weights, indices)

    def update_priorities(self, indices: List[int], priorities: np.ndarray):
        """Update priorities of sampled transitions."""
        assert len(indices) == len(priorities)
        for idx, priority in zip(indices, priorities):
            assert priority > 0
            assert 0 <= idx < len(self)
            self.sum_tree[idx] = priority ** self.alpha
            self.min_tree[idx] = priority ** self.alpha
            self.max_priority = max(self.max_priority, priority)

    def _sample_proportional(self) -> List[int]:
        """Sample indices based on proportions."""
        indices = []
        p_total = self.sum_tree.sum(0, len(self) - 1)
        segment = p_total / self.batch_size
        for i in range(self.batch_size):
            a = segment * i
            b = segment * (i + 1)
            upperbound = random.uniform(a, b)
            idx = self.sum_tree.retrieve(upperbound)
            indices.append(idx)
        return indices

    def _calculate_weight(self, idx: int, beta: float):
        """Calculate the weight of the experience at idx."""
        p_min = self.min_tree.min() / self.sum_tree.sum()
        max_weight = (p_min * len(self)) ** (-beta)
        p_sample = self.sum_tree[idx] / self.sum_tree.sum()
        weight = (p_sample * len(self)) ** (-beta)
        weight = weight / max_weight
        return weight


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

Class description:
Implement the TemplateGet class.

Method signatures and docstrings:
- def get(self, template_name): Get a specific template
- def put(self, template_name): Update a template
- def delete(self, template_name): Delete a template

Implement the Python class `TemplateGet` described below.

Class description:
Implement the TemplateGet class.

Method signatures and docstrings:
- def get(self, template_name): Get a specific template
- def put(self, template_name): Update a template
- def delete(self, template_name): Delete a template

<|skeleton|>
class TemplateGet:

    def get(self, template_name):
        """Get a specific template"""
        <|body_0|>

    def put(self, template_name):
        """Update a template"""
        <|body_1|>

    def delete(self, template_name):
        """Delete a template"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        template = db.Template.find_one(template_name=template_name)
        if not template:
            return self.make_response('No such template found', HTTP.NOT_FOUND)
        return self.make_response({'template': template})
<|end_body_0|>

<|body_start_1|>
        self.reqparse.add_argument('template', type=str, required=True)
        args = self.reqparse.parse_args()
        template = db.Template.find_one(template_name=template_name)
        if not template:
            return self.make_response('No such template found', HTTP.NOT_FOUND)
        changes = diff(template.template, args['template'])
        template.template = args['template']
        template.is_modified = True
        db.session.add(template)
        db.session.commit()
        auditlog(event='template.update', actor=session['user'].username, data={'template_name': template_name, 'template_changes': changes})
        return self.make_response('Template {} has been updated'.format(template_name))
<|end_body_1|>

<|body_start_2|>
        template = db.Template.find_one(template_name=template_name)
        if not template:
            return self.make_response('No such template found', HTTP.NOT_FOUND)
        db.session.delete(template)
        db.session.commit()
        auditlog(event='template.delete', actor=session['user'].username, data={'template_name': template_name})
        return self.make_response({'message': 'Template has been deleted', 'templateName': template_name})
<|end_body_2|>

Solution:
class TemplateGet:
    def get(self, template_name):
        """Get a specific template"""
        template = db.Template.find_one(template_name=template_name)
        if not template:
            return self.make_response('No such template found', HTTP.NOT_FOUND)
        return self.make_response({'template': template})

    def put(self, template_name):
        """Update a template"""
        self.reqparse.add_argument('template', type=str, required=True)
        args = self.reqparse.parse_args()
        template = db.Template.find_one(template_name=template_name)
        if not template:
            return self.make_response('No such template found', HTTP.NOT_FOUND)
        changes = diff(template.template, args['template'])
        template.template = args['template']
        template.is_modified = True
        db.session.add(template)
        db.session.commit()
        auditlog(event='template.update', actor=session['user'].username, data={'template_name': template_name, 'template_changes': changes})
        return self.make_response('Template {} has been updated'.format(template_name))

    def delete(self, template_name):
        """Delete a template"""
        template = db.Template.find_one(template_name=template_name)
        if not template:
            return self.make_response('No such template found', HTTP.NOT_FOUND)
        db.session.delete(template)
        db.session.commit()
        auditlog(event='template.delete', actor=session['user'].username, data={'template_name': template_name})
        return self.make_response({'message': 'Template has been deleted', 'templateName': template_name})


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

Class description:
Base form for adding cases.

Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize form; possibly add suite field.
- def clean(self): Verify that products all match up.

Implement the Python class `BaseAddCaseForm` described below.

Class description:
Base form for adding cases.

Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize form; possibly add suite field.
- def clean(self): Verify that products all match up.

<|skeleton|>
class BaseAddCaseForm:
    """Base form for adding cases."""

    def __init__(self, *args, **kwargs):
        """Initialize form; possibly add suite field."""
        <|body_0|>

    def clean(self):
        """Verify that products all match up."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        super(BaseAddCaseForm, self).__init__(*args, **kwargs)
        if self.user and self.user.has_perm('library.manage_suite_cases'):
            self.fields['suite'] = mtforms.MTModelChoiceField(model.Suite.objects.all(), choice_attrs=mtforms.product_id_attrs, required=False)
<|end_body_0|>

<|body_start_1|>
        productversion = self.cleaned_data.get('productversion')
        suite = self.cleaned_data.get('suite')
        product = self.cleaned_data.get('product')
        if product and productversion and (productversion.product != product):
            raise forms.ValidationError('Must select a version of the correct product.')
        if product and suite and (suite.product != product):
            raise forms.ValidationError('Must select a suite for the correct product.')
        return self.cleaned_data
<|end_body_1|>

Solution:
class BaseAddCaseForm:
    """Base form for adding cases."""

    def __init__(self, *args, **kwargs):
        """Initialize form; possibly add suite field."""
        super(BaseAddCaseForm, self).__init__(*args, **kwargs)
        if self.user and self.user.has_perm('library.manage_suite_cases'):
            self.fields['suite'] = mtforms.MTModelChoiceField(model.Suite.objects.all(), choice_attrs=mtforms.product_id_attrs, required=False)

    def clean(self):
        """Verify that products all match up."""
        productversion = self.cleaned_data.get('productversion')
        suite = self.cleaned_data.get('suite')
        product = self.cleaned_data.get('product')
        if product and productversion and (productversion.product != product):
            raise forms.ValidationError('Must select a version of the correct product.')
        if product and suite and (suite.product != product):
            raise forms.ValidationError('Must select a suite for the correct product.')
        return self.cleaned_data


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

Class description:
Implementation of the 'IsilonProtectionSource' model. Specifies a Protection Source in Isilon OneFs environment. Attributes: access_zone (IsilonAccessZone): Specifies an access zone in an Isilon OneFs file system. This is set only when the entity type is 'kZone'. cluster (IsilonCluster): Specifies information of an Isilon OneFs Cluster. This is set only when the entity type is 'kCluster'. mount_point (IsilonMountPoint): Specifies information about a mount point in an Isilon OneFs file system. This is set only when the entity type is 'kMountPoint'. name (string): Specifies a unique name of the Protection Source. mtype (TypeIsilonProtectionSourceEnum): Specifies the type of the entity in an Is

Method signatures and docstrings:
- def __init__(self, access_zone=None, cluster=None, mount_point=None, name=None, mtype=None): Constructor for the IsilonProtectionSource class
- def from_dictionary(cls, dictionary): Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class.

Implement the Python class `IsilonProtectionSource` described below.

Class description:
Implementation of the 'IsilonProtectionSource' model. Specifies a Protection Source in Isilon OneFs environment. Attributes: access_zone (IsilonAccessZone): Specifies an access zone in an Isilon OneFs file system. This is set only when the entity type is 'kZone'. cluster (IsilonCluster): Specifies information of an Isilon OneFs Cluster. This is set only when the entity type is 'kCluster'. mount_point (IsilonMountPoint): Specifies information about a mount point in an Isilon OneFs file system. This is set only when the entity type is 'kMountPoint'. name (string): Specifies a unique name of the Protection Source. mtype (TypeIsilonProtectionSourceEnum): Specifies the type of the entity in an Is

Method signatures and docstrings:
- def __init__(self, access_zone=None, cluster=None, mount_point=None, name=None, mtype=None): Constructor for the IsilonProtectionSource class
- def from_dictionary(cls, dictionary): Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class.

<|skeleton|>
class IsilonProtectionSource:
    """Implementation of the 'IsilonProtectionSource' model. Specifies a Protection Source in Isilon OneFs environment. Attributes: access_zone (IsilonAccessZone): Specifies an access zone in an Isilon OneFs file system. This is set only when the entity type is 'kZone'. cluster (IsilonCluster): Specifies information of an Isilon OneFs Cluster. This is set only when the entity type is 'kCluster'. mount_point (IsilonMountPoint): Specifies information about a mount point in an Isilon OneFs file system. This is set only when the entity type is 'kMountPoint'. name (string): Specifies a unique name of the Protection Source. mtype (TypeIsilonProtectionSourceEnum): Specifies the type of the entity in an Is"""

    def __init__(self, access_zone=None, cluster=None, mount_point=None, name=None, mtype=None):
        """Constructor for the IsilonProtectionSource class"""
        <|body_0|>

    def from_dictionary(cls, dictionary):
        """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.access_zone = access_zone
        self.cluster = cluster
        self.mount_point = mount_point
        self.name = name
        self.mtype = mtype
<|end_body_0|>

<|body_start_1|>
        if dictionary is None:
            return None
        access_zone = cohesity_management_sdk.models.isilon_access_zone.IsilonAccessZone.from_dictionary(dictionary.get('accessZone')) if dictionary.get('accessZone') else None
        cluster = cohesity_management_sdk.models.isilon_cluster.IsilonCluster.from_dictionary(dictionary.get('cluster')) if dictionary.get('cluster') else None
        mount_point = cohesity_management_sdk.models.isilon_mount_point.IsilonMountPoint.from_dictionary(dictionary.get('mountPoint')) if dictionary.get('mountPoint') else None
        name = dictionary.get('name')
        mtype = dictionary.get('type')
        return cls(access_zone, cluster, mount_point, name, mtype)
<|end_body_1|>

Solution:
class IsilonProtectionSource:
    """Implementation of the 'IsilonProtectionSource' model. Specifies a Protection Source in Isilon OneFs environment. Attributes: access_zone (IsilonAccessZone): Specifies an access zone in an Isilon OneFs file system. This is set only when the entity type is 'kZone'. cluster (IsilonCluster): Specifies information of an Isilon OneFs Cluster. This is set only when the entity type is 'kCluster'. mount_point (IsilonMountPoint): Specifies information about a mount point in an Isilon OneFs file system. This is set only when the entity type is 'kMountPoint'. name (string): Specifies a unique name of the Protection Source. mtype (TypeIsilonProtectionSourceEnum): Specifies the type of the entity in an Is"""

    def __init__(self, access_zone=None, cluster=None, mount_point=None, name=None, mtype=None):
        """Constructor for the IsilonProtectionSource class"""
        self.access_zone = access_zone
        self.cluster = cluster
        self.mount_point = mount_point
        self.name = name
        self.mtype = mtype

    def from_dictionary(cls, dictionary):
        """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class."""
        if dictionary is None:
            return None
        access_zone = cohesity_management_sdk.models.isilon_access_zone.IsilonAccessZone.from_dictionary(dictionary.get('accessZone')) if dictionary.get('accessZone') else None
        cluster = cohesity_management_sdk.models.isilon_cluster.IsilonCluster.from_dictionary(dictionary.get('cluster')) if dictionary.get('cluster') else None
        mount_point = cohesity_management_sdk.models.isilon_mount_point.IsilonMountPoint.from_dictionary(dictionary.get('mountPoint')) if dictionary.get('mountPoint') else None
        name = dictionary.get('name')
        mtype = dictionary.get('type')
        return cls(access_zone, cluster, mount_point, name, mtype)


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

Class description:
Class for handling the data retrieval for pins.

Method signatures and docstrings:
- def __init__(self, resource, pin): Initialize the aREST data object.
- def update(self) -> None: Get the latest data from aREST device.

Implement the Python class `ArestData` described below.

Class description:
Class for handling the data retrieval for pins.

Method signatures and docstrings:
- def __init__(self, resource, pin): Initialize the aREST data object.
- def update(self) -> None: Get the latest data from aREST device.

<|skeleton|>
class ArestData:
    """Class for handling the data retrieval for pins."""

    def __init__(self, resource, pin):
        """Initialize the aREST data object."""
        <|body_0|>

    def update(self) -> None:
        """Get the latest data from aREST device."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self._resource = resource
        self._pin = pin
        self.data = {}
<|end_body_0|>

<|body_start_1|>
        try:
            response = requests.get(f'{self._resource}/digital/{self._pin}', timeout=10)
            self.data = {'state': response.json()['return_value']}
        except requests.exceptions.ConnectionError:
            _LOGGER.error("No route to device '%s'", self._resource)
<|end_body_1|>

Solution:
class ArestData:
    """Class for handling the data retrieval for pins."""

    def __init__(self, resource, pin):
        """Initialize the aREST data object."""
        self._resource = resource
        self._pin = pin
        self.data = {}

    def update(self) -> None:
        """Get the latest data from aREST device."""
        try:
            response = requests.get(f'{self._resource}/digital/{self._pin}', timeout=10)
            self.data = {'state': response.json()['return_value']}
        except requests.exceptions.ConnectionError:
            _LOGGER.error("No route to device '%s'", self._resource)


forward

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

Class description:
Implement the DistilBertLayerBetterTransformer class.

Method signatures and docstrings:
- def __init__(self, bert_layer, config): A simple conversion of the Distill-BERTLayer to its `BetterTransformer` implementation. Args: bert_layer (`torch.nn.Module`): The original Distill-BERT Layer where the weights needs to be retrieved.
- def forward(self, x, attn_mask, head_mask=None, output_attentions=None, *_): This is just a wrapper around the forward function proposed in: https://github.com/huggingface/transformers/pull/19553

Implement the Python class `DistilBertLayerBetterTransformer` described below.

Class description:
Implement the DistilBertLayerBetterTransformer class.

Method signatures and docstrings:
- def __init__(self, bert_layer, config): A simple conversion of the Distill-BERTLayer to its `BetterTransformer` implementation. Args: bert_layer (`torch.nn.Module`): The original Distill-BERT Layer where the weights needs to be retrieved.
- def forward(self, x, attn_mask, head_mask=None, output_attentions=None, *_): This is just a wrapper around the forward function proposed in: https://github.com/huggingface/transformers/pull/19553

<|skeleton|>
class DistilBertLayerBetterTransformer:

    def __init__(self, bert_layer, config):
        """A simple conversion of the Distill-BERTLayer to its `BetterTransformer` implementation. Args: bert_layer (`torch.nn.Module`): The original Distill-BERT Layer where the weights needs to be retrieved."""
        <|body_0|>

    def forward(self, x, attn_mask, head_mask=None, output_attentions=None, *_):
        """This is just a wrapper around the forward function proposed in: https://github.com/huggingface/transformers/pull/19553"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        super().__init__(config)
        self.in_proj_weight = nn.Parameter(torch.cat([bert_layer.attention.q_lin.weight, bert_layer.attention.k_lin.weight, bert_layer.attention.v_lin.weight]))
        self.in_proj_bias = nn.Parameter(torch.cat([bert_layer.attention.q_lin.bias, bert_layer.attention.k_lin.bias, bert_layer.attention.v_lin.bias]))
        self.out_proj_weight = bert_layer.attention.out_lin.weight
        self.out_proj_bias = bert_layer.attention.out_lin.bias
        self.linear1_weight = bert_layer.ffn.lin1.weight
        self.linear1_bias = bert_layer.ffn.lin1.bias
        self.linear2_weight = bert_layer.ffn.lin2.weight
        self.linear2_bias = bert_layer.ffn.lin2.bias
        self.norm1_eps = bert_layer.sa_layer_norm.eps
        self.norm1_weight = bert_layer.sa_layer_norm.weight
        self.norm1_bias = bert_layer.sa_layer_norm.bias
        self.norm2_eps = bert_layer.output_layer_norm.eps
        self.norm2_weight = bert_layer.output_layer_norm.weight
        self.norm2_bias = bert_layer.output_layer_norm.bias
        self.num_heads = bert_layer.attention.n_heads
        self.embed_dim = bert_layer.attention.dim
        self.is_last_layer = False
        self.validate_bettertransformer()
<|end_body_0|>

<|body_start_1|>
        super().forward_checker()
        if x.is_nested:
            attn_mask = None
        if attn_mask is not None:
            attn_mask = attn_mask.bool()
            attn_mask = torch.reshape(attn_mask, (attn_mask.shape[0], attn_mask.shape[-1]))
            seqlen = attn_mask.shape[1]
            lengths = torch.sum(~attn_mask, 1)
            if not all([l == seqlen for l in lengths]):
                x = torch._nested_tensor_from_mask(x, attn_mask)
            attn_mask = None
        x = torch._transformer_encoder_layer_fwd(x, self.embed_dim, self.num_heads, self.in_proj_weight, self.in_proj_bias, self.out_proj_weight, self.out_proj_bias, self.use_gelu, self.norm_first, self.norm1_eps, self.norm1_weight, self.norm1_bias, self.norm2_weight, self.norm2_bias, self.linear1_weight, self.linear1_bias, self.linear2_weight, self.linear2_bias, attn_mask)
        if x.is_nested and self.is_last_layer:
            x = x.to_padded_tensor(0.0)
        return (x,)
<|end_body_1|>

Solution:
class DistilBertLayerBetterTransformer:
    def __init__(self, bert_layer, config):
        """A simple conversion of the Distill-BERTLayer to its `BetterTransformer` implementation. Args: bert_layer (`torch.nn.Module`): The original Distill-BERT Layer where the weights needs to be retrieved."""
        super().__init__(config)
        self.in_proj_weight = nn.Parameter(torch.cat([bert_layer.attention.q_lin.weight, bert_layer.attention.k_lin.weight, bert_layer.attention.v_lin.weight]))
        self.in_proj_bias = nn.Parameter(torch.cat([bert_layer.attention.q_lin.bias, bert_layer.attention.k_lin.bias, bert_layer.attention.v_lin.bias]))
        self.out_proj_weight = bert_layer.attention.out_lin.weight
        self.out_proj_bias = bert_layer.attention.out_lin.bias
        self.linear1_weight = bert_layer.ffn.lin1.weight
        self.linear1_bias = bert_layer.ffn.lin1.bias
        self.linear2_weight = bert_layer.ffn.lin2.weight
        self.linear2_bias = bert_layer.ffn.lin2.bias
        self.norm1_eps = bert_layer.sa_layer_norm.eps
        self.norm1_weight = bert_layer.sa_layer_norm.weight
        self.norm1_bias = bert_layer.sa_layer_norm.bias
        self.norm2_eps = bert_layer.output_layer_norm.eps
        self.norm2_weight = bert_layer.output_layer_norm.weight
        self.norm2_bias = bert_layer.output_layer_norm.bias
        self.num_heads = bert_layer.attention.n_heads
        self.embed_dim = bert_layer.attention.dim
        self.is_last_layer = False
        self.validate_bettertransformer()

    def forward(self, x, attn_mask, head_mask=None, output_attentions=None, *_):
        """This is just a wrapper around the forward function proposed in: https://github.com/huggingface/transformers/pull/19553"""
        super().forward_checker()
        if x.is_nested:
            attn_mask = None
        if attn_mask is not None:
            attn_mask = attn_mask.bool()
            attn_mask = torch.reshape(attn_mask, (attn_mask.shape[0], attn_mask.shape[-1]))
            seqlen = attn_mask.shape[1]
            lengths = torch.sum(~attn_mask, 1)
            if not all([l == seqlen for l in lengths]):
                x = torch._nested_tensor_from_mask(x, attn_mask)
            attn_mask = None
        x = torch._transformer_encoder_layer_fwd(x, self.embed_dim, self.num_heads, self.in_proj_weight, self.in_proj_bias, self.out_proj_weight, self.out_proj_bias, self.use_gelu, self.norm_first, self.norm1_eps, self.norm1_weight, self.norm1_bias, self.norm2_weight, self.norm2_bias, self.linear1_weight, self.linear1_bias, self.linear2_weight, self.linear2_bias, attn_mask)
        if x.is_nested and self.is_last_layer:
            x = x.to_padded_tensor(0.0)
        return (x,)


zigzagLevelOrder

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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: BFS with Reverse, Time: O(n), Space: O(n)
- def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: BFS without Reverse, Time: O(n), Space: O(n)

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: BFS with Reverse, Time: O(n), Space: O(n)
- def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: BFS without Reverse, Time: O(n), Space: O(n)

<|skeleton|>
class Solution:

    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        """BFS with Reverse, Time: O(n), Space: O(n)"""
        <|body_0|>

    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        """BFS without Reverse, Time: O(n), Space: O(n)"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        from collections import deque
        if root is None:
            return []
        q = deque([root])
        level = 0
        result = []
        while q:
            sz = len(q)
            result.append([])
            for _ in range(sz):
                node = q.popleft()
                result[-1].append(node.val)
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            if level % 2 != 0:
                result[-1] = result[-1][::-1]
            level += 1
        return result
<|end_body_0|>

<|body_start_1|>
        from collections import deque
        if root is None:
            return []
        q = deque([root])
        level = 0
        result = []
        while q:
            sz = len(q)
            result.append([0] * sz)
            for i in range(sz):
                node = q.popleft()
                if level % 2 == 0:
                    idx = i
                else:
                    idx = sz - i - 1
                result[-1][idx] = node.val
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            level += 1
        return result
<|end_body_1|>

Solution:
class Solution:
    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        """BFS with Reverse, Time: O(n), Space: O(n)"""
        from collections import deque
        if root is None:
            return []
        q = deque([root])
        level = 0
        result = []
        while q:
            sz = len(q)
            result.append([])
            for _ in range(sz):
                node = q.popleft()
                result[-1].append(node.val)
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            if level % 2 != 0:
                result[-1] = result[-1][::-1]
            level += 1
        return result

    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        """BFS without Reverse, Time: O(n), Space: O(n)"""
        from collections import deque
        if root is None:
            return []
        q = deque([root])
        level = 0
        result = []
        while q:
            sz = len(q)
            result.append([0] * sz)
            for i in range(sz):
                node = q.popleft()
                if level % 2 == 0:
                    idx = i
                else:
                    idx = sz - i - 1
                result[-1][idx] = node.val
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            level += 1
        return result

python/103-Binary Tree Zigzag Level Order Traversal.py