crossfile_context_retrievalwref dict | prompt stringlengths 252 32.6k | right_context stringlengths 0 81.2k | metadata dict | crossfile_context_retrieval dict | groundtruth stringlengths 5 208 |
|---|---|---|---|---|---|
{
"list": [
{
"filename": "zxlive/edit_panel.py",
"retrieved_chunk": " self.undo_stack.push(cmd)\n def _add_vert(self, x: float, y: float) -> None:\n cmd = AddNode(self.graph_view, x, y, self._curr_vty)\n self.undo_stack.push(cmd)\n def _add_edge(self, u: VT, v: VT) -> N... | from __future__ import annotations
import copy
from typing import Iterator, Union, cast
import pyzx
from PySide6.QtCore import QPointF, QPersistentModelIndex, Qt, \
QModelIndex, QItemSelection, QRect, QSize
from PySide6.QtGui import QVector2D, QFont, QColor, QPainter, QPen, QFontMetrics, QIcon
from PySide6.QtWidg... |
anims.anticipate_fuse(self.graph_scene.vertex_map[w])
elif pyzx.basicrules.check_strong_comp(self.graph, v, w):
anims.anticipate_strong_comp(self.graph_scene.vertex_map[w])
else:
anims.back_to_default(self.graph_scene.vertex_map[w])
def _vertex_dropp... | {
"context_start_lineno": 0,
"file": "zxlive/proof_panel.py",
"groundtruth_start_lineno": 124,
"repository": "Quantomatic-zxlive-c7b5c28",
"right_context_start_lineno": 125,
"task_id": "project_cc_python/392"
} | {
"list": [
{
"filename": "zxlive/edit_panel.py",
"retrieved_chunk": " def _vert_double_clicked(self, v: VT) -> None:\n if self.graph.type(v) == VertexType.BOUNDARY:\n input_, ok = QInputDialog.getText(\n self, \"Input Dialog\", \"Enter Qubit Index:\"\n )... | graph, v, w): |
{
"list": [
{
"filename": "zxlive/commands.py",
"retrieved_chunk": " self.step_view = step_view\n self.step = step\n self.old_step = old_step\n def redo(self) -> None:\n idx = self.step_view.model().index(self.step, 0, QModelIndex())\n self.step_view.clearSelectio... | from __future__ import annotations
import copy
from typing import Iterator, Union, cast
import pyzx
from PySide6.QtCore import QPointF, QPersistentModelIndex, Qt, \
QModelIndex, QItemSelection, QRect, QSize
from PySide6.QtGui import QVector2D, QFont, QColor, QPainter, QPen, QFontMetrics, QIcon
from PySide6.QtWidg... |
def _toolbar_sections(self) -> Iterator[ToolbarSection]:
icon_size = QSize(32, 32)
self.selection = QToolButton(self, checkable=True, checked=True)
self.magic_wand = QToolButton(self, checkable=True)
self.selection.setIcon(QIcon(get_data("icons/tikzit-tool-select.svg")))
se... | {
"context_start_lineno": 0,
"file": "zxlive/proof_panel.py",
"groundtruth_start_lineno": 56,
"repository": "Quantomatic-zxlive-c7b5c28",
"right_context_start_lineno": 57,
"task_id": "project_cc_python/382"
} | {
"list": [
{
"filename": "zxlive/mainwindow.py",
"retrieved_chunk": " def close_action(self) -> bool:\n assert self.active_panel is not None\n i = self.tab_widget.currentIndex()\n if i == -1: # no tabs open\n self.close()\n if not self.active_panel.undo_stack... | splitter.addWidget(self.step_view) |
{
"list": [
{
"filename": "zxlive/edit_panel.py",
"retrieved_chunk": " self.undo_stack.push(cmd)\n def _add_vert(self, x: float, y: float) -> None:\n cmd = AddNode(self.graph_view, x, y, self._curr_vty)\n self.undo_stack.push(cmd)\n def _add_edge(self, u: VT, v: VT) -> N... | from __future__ import annotations
import copy
from typing import Iterator, Union, cast
import pyzx
from PySide6.QtCore import QPointF, QPersistentModelIndex, Qt, \
QModelIndex, QItemSelection, QRect, QSize
from PySide6.QtGui import QVector2D, QFont, QColor, QPainter, QPen, QFontMetrics, QIcon
from PySide6.QtWidg... |
elif pyzx.basicrules.check_strong_comp(self.graph, v, w):
anims.anticipate_strong_comp(self.graph_scene.vertex_map[w])
else:
anims.back_to_default(self.graph_scene.vertex_map[w])
def _vertex_dropped_onto(self, v: VT, w: VT) -> None:
if pyzx.basicrules.check_... | {
"context_start_lineno": 0,
"file": "zxlive/proof_panel.py",
"groundtruth_start_lineno": 125,
"repository": "Quantomatic-zxlive-c7b5c28",
"right_context_start_lineno": 126,
"task_id": "project_cc_python/393"
} | {
"list": [
{
"filename": "zxlive/edit_panel.py",
"retrieved_chunk": " def _vert_double_clicked(self, v: VT) -> None:\n if self.graph.type(v) == VertexType.BOUNDARY:\n input_, ok = QInputDialog.getText(\n self, \"Input Dialog\", \"Enter Qubit Index:\"\n )... | anticipate_fuse(self.graph_scene.vertex_map[w]) |
{
"list": [
{
"filename": "zxlive/commands.py",
"retrieved_chunk": " _new_vert: Optional[VT] = field(default=None, init=False)\n def undo(self) -> None:\n u, v, w = self.u, self.v, self._new_vert\n assert w is not None\n g = self.g\n et = g.edge_type(g.edge(v, w))\n ... | from __future__ import annotations
import copy
from typing import Iterator, Union, cast
import pyzx
from PySide6.QtCore import QPointF, QPersistentModelIndex, Qt, \
QModelIndex, QItemSelection, QRect, QSize
from PySide6.QtGui import QVector2D, QFont, QColor, QPainter, QPen, QFontMetrics, QIcon
from PySide6.QtWidg... |
cmd = AddRewriteStep(self.graph_view, g, self.step_view, "fuse spiders")
self.undo_stack.push(cmd, anim_before=anim)
elif pyzx.basicrules.check_strong_comp(self.graph, v, w):
g = copy.deepcopy(self.graph)
pyzx.basicrules.strong_comp(g, w, v)
anim = an... | {
"context_start_lineno": 0,
"file": "zxlive/proof_panel.py",
"groundtruth_start_lineno": 135,
"repository": "Quantomatic-zxlive-c7b5c28",
"right_context_start_lineno": 136,
"task_id": "project_cc_python/397"
} | {
"list": [
{
"filename": "zxlive/commands.py",
"retrieved_chunk": " self.update_graph_view()\n def redo(self) -> None:\n u, v = self.u, self.v\n g = self.g\n uv = g.edge(u, v)\n r = 0.5 * (g.row(u) + g.row(v))\n q = 0.5 * (g.qubit(u) + g.qubit(v))\n ... | fuse(self.graph_scene.vertex_map[v], self.graph_scene.vertex_map[w]) |
{
"list": [
{
"filename": "zxlive/edit_panel.py",
"retrieved_chunk": " self.undo_stack.push(cmd)\n def _add_vert(self, x: float, y: float) -> None:\n cmd = AddNode(self.graph_view, x, y, self._curr_vty)\n self.undo_stack.push(cmd)\n def _add_edge(self, u: VT, v: VT) -> N... | from __future__ import annotations
import copy
from typing import Iterator, Union, cast
import pyzx
from PySide6.QtCore import QPointF, QPersistentModelIndex, Qt, \
QModelIndex, QItemSelection, QRect, QSize
from PySide6.QtGui import QVector2D, QFont, QColor, QPainter, QPen, QFontMetrics, QIcon
from PySide6.QtWidg... |
elif pyzx.basicrules.check_strong_comp(self.graph, v, w):
anims.anticipate_strong_comp(self.graph_scene.vertex_map[w])
else:
anims.back_to_default(self.graph_scene.vertex_map[w])
def _vertex_dropped_onto(self, v: VT, w: VT) -> None:
if pyzx.basicrules.check_... | {
"context_start_lineno": 0,
"file": "zxlive/proof_panel.py",
"groundtruth_start_lineno": 125,
"repository": "Quantomatic-zxlive-c7b5c28",
"right_context_start_lineno": 126,
"task_id": "project_cc_python/394"
} | {
"list": [
{
"filename": "zxlive/edit_panel.py",
"retrieved_chunk": " def _vert_double_clicked(self, v: VT) -> None:\n if self.graph.type(v) == VertexType.BOUNDARY:\n input_, ok = QInputDialog.getText(\n self, \"Input Dialog\", \"Enter Qubit Index:\"\n )... | vertex_map[w]) |
{
"list": [
{
"filename": "zxlive/proof_actions.py",
"retrieved_chunk": " print('To do: animate ' + self.name)\n panel.undo_stack.push(cmd)\n elif self.name == operations['rem_id']['text']:\n anim = anims.remove_id(panel.graph_scene.vertex_map[verts[0]])\n ... | import itertools
import random
from typing import Optional, Callable
from PySide6.QtCore import QEasingCurve, QPointF, QAbstractAnimation, \
QParallelAnimationGroup
from PySide6.QtGui import QUndoStack, QUndoCommand
from .common import VT, GraphT, pos_to_view
from .graphscene import GraphScene
from .vitem import ... |
# Important: end value must be a float, otherwise the animation doesn't work because
# start and end have different types
anim.setEndValue(float(target))
anim.setEasingCurve(ease)
return anim
def move(it: VItem, target: QPointF, duration: int, ease: QEasingCurve, start: Optional[QPointF] = None) ... | {
"context_start_lineno": 0,
"file": "zxlive/animations.py",
"groundtruth_start_lineno": 66,
"repository": "Quantomatic-zxlive-c7b5c28",
"right_context_start_lineno": 67,
"task_id": "project_cc_python/404"
} | {
"list": [
{
"filename": "zxlive/proof_actions.py",
"retrieved_chunk": " elif self.name == operations['pauli']['text']:\n print('To do: animate ' + self.name)\n panel.undo_stack.push(cmd)\n elif self.name == operations['bialgebra']['text']:\n anim = anim... | setStartValue(start or it.scale()) |
{
"list": [
{
"filename": "zxlive/edit_panel.py",
"retrieved_chunk": " return\n cmd = ChangePhase(self.graph_view, v, new_phase)\n self.undo_stack.push(cmd)\n def paste_graph(self, graph: GraphT) -> None:\n if graph is None: return\n new_g = copy.deepcopy(self... | from __future__ import annotations
import copy
from typing import Iterator, Union, cast
import pyzx
from PySide6.QtCore import QPointF, QPersistentModelIndex, Qt, \
QModelIndex, QItemSelection, QRect, QSize
from PySide6.QtGui import QVector2D, QFont, QColor, QPainter, QPen, QFontMetrics, QIcon
from PySide6.QtWidg... |
cmd = AddRewriteStep(self.graph_view, new_g, self.step_view, "id")
self.undo_stack.push(cmd, anim_before=anim)
def _unfuse(self, v: VT, left_neighbours: list[VT], mouse_dir: QPointF) -> None:
def snap_vector(v: QVector2D) -> None:
if abs(v.x()) > abs(v.y()):
v.s... | {
"context_start_lineno": 0,
"file": "zxlive/proof_panel.py",
"groundtruth_start_lineno": 217,
"repository": "Quantomatic-zxlive-c7b5c28",
"right_context_start_lineno": 218,
"task_id": "project_cc_python/400"
} | {
"list": [
{
"filename": "zxlive/edit_panel.py",
"retrieved_chunk": " def delete_selection(self) -> None:\n selection = list(self.graph_scene.selected_vertices)\n selected_edges = list(self.graph_scene.selected_edges)\n if not selection and not selected_edges: return\n ... | remove_id(self.graph_scene.vertex_map[v]) |
{
"list": [
{
"filename": "zxlive/graphscene.py",
"retrieved_chunk": " \"\"\"Update the PyZX graph for the scene.\n This will update the scene to match the given graph. It will\n try to reuse existing QGraphicsItem's as much as possible.\n The selection is carried over to t... | from dataclasses import dataclass, field
from fractions import Fraction
from typing import Optional, Iterable, Set, Union, List, Any
import copy
from PySide6.QtCore import QItemSelection, QModelIndex, QItemSelectionModel, \
QSignalBlocker
from PySide6.QtGui import QUndoCommand
from PySide6.QtWidgets import QListVi... |
@dataclass
class SetGraph(BaseCommand):
"""Replaces the current graph with an entirely new graph."""
new_g: GraphT
old_g: Optional[GraphT] = field(default=None, init=False)
def undo(self) -> None:
assert self.old_g is not None
self.graph_view.set_graph(self.old_g)
def redo(self)... | {
"context_start_lineno": 0,
"file": "zxlive/commands.py",
"groundtruth_start_lineno": 45,
"repository": "Quantomatic-zxlive-c7b5c28",
"right_context_start_lineno": 46,
"task_id": "project_cc_python/414"
} | {
"list": [
{
"filename": "zxlive/graphscene.py",
"retrieved_chunk": " v_item = self.vertex_map[v]\n if v_item.phase_item:\n self.removeItem(v_item.phase_item)\n for anim in v_item.active_animations.copy():\n anim.stop()\n for e... | update_graph(self.g, select_new) |
{
"list": [
{
"filename": "zxlive/graphscene.py",
"retrieved_chunk": " # otherwise it doesn't work for some reason...\n vertex_added = Signal(object, object) # Actual types: float, float\n edge_added = Signal(object, object) # Actual types: VT, VT\n # Currently selected edge type for pre... | import itertools
import random
from typing import Optional, Callable
from PySide6.QtCore import QEasingCurve, QPointF, QAbstractAnimation, \
QParallelAnimationGroup
from PySide6.QtGui import QUndoStack, QUndoCommand
from .common import VT, GraphT, pos_to_view
from .graphscene import GraphScene
from .vitem import ... |
anim.setEasingCurve(ease)
return anim
def move(it: VItem, target: QPointF, duration: int, ease: QEasingCurve, start: Optional[QPointF] = None) -> VItemAnimation:
anim = VItemAnimation(it, VItem.Properties.Position, refresh=True)
anim.setDuration(duration)
anim.setStartValue(start or it.pos())
... | {
"context_start_lineno": 0,
"file": "zxlive/animations.py",
"groundtruth_start_lineno": 69,
"repository": "Quantomatic-zxlive-c7b5c28",
"right_context_start_lineno": 70,
"task_id": "project_cc_python/405"
} | {
"list": [
{
"filename": "zxlive/graphscene.py",
"retrieved_chunk": " super().__init__()\n self.curr_ety = EdgeType.SIMPLE\n self.curr_tool = ToolType.SELECT\n self._drag = None\n self._is_dragging = False\n self._is_mouse_pressed = False\n def mousePressE... | setEndValue(float(target)) |
{
"list": [
{
"filename": "zxlive/edit_panel.py",
"retrieved_chunk": " return\n cmd = ChangePhase(self.graph_view, v, new_phase)\n self.undo_stack.push(cmd)\n def paste_graph(self, graph: GraphT) -> None:\n if graph is None: return\n new_g = copy.deepcopy(self... | from dataclasses import dataclass, field
from fractions import Fraction
from typing import Optional, Iterable, Set, Union, List, Any
import copy
from PySide6.QtCore import QItemSelection, QModelIndex, QItemSelectionModel, \
QSignalBlocker
from PySide6.QtGui import QUndoCommand
from PySide6.QtWidgets import QListVi... |
def redo(self) -> None:
self.old_g = self.graph_view.graph_scene.g
self.graph_view.set_graph(self.new_g)
@dataclass
class UpdateGraph(BaseCommand):
"""Updates the current graph with a modified one.
It will try to reuse existing QGraphicsItem's as much as possible."""
new_g: GraphT
... | {
"context_start_lineno": 0,
"file": "zxlive/commands.py",
"groundtruth_start_lineno": 56,
"repository": "Quantomatic-zxlive-c7b5c28",
"right_context_start_lineno": 57,
"task_id": "project_cc_python/415"
} | {
"list": [
{
"filename": "zxlive/edit_panel.py",
"retrieved_chunk": " def delete_selection(self) -> None:\n selection = list(self.graph_scene.selected_vertices)\n selected_edges = list(self.graph_scene.selected_edges)\n if not selection and not selected_edges: return\n ... | set_graph(self.old_g) |
{
"list": [
{
"filename": "zxlive/proof_actions.py",
"retrieved_chunk": " print('To do: animate ' + self.name)\n panel.undo_stack.push(cmd)\n elif self.name == operations['rem_id']['text']:\n anim = anims.remove_id(panel.graph_scene.vertex_map[verts[0]])\n ... | import itertools
import random
from typing import Optional, Callable
from PySide6.QtCore import QEasingCurve, QPointF, QAbstractAnimation, \
QParallelAnimationGroup
from PySide6.QtGui import QUndoStack, QUndoCommand
from .common import VT, GraphT, pos_to_view
from .graphscene import GraphScene
from .vitem import ... |
anim.setStartValue(start or it.scale())
# Important: end value must be a float, otherwise the animation doesn't work because
# start and end have different types
anim.setEndValue(float(target))
anim.setEasingCurve(ease)
return anim
def move(it: VItem, target: QPointF, duration: int, ease: QEa... | {
"context_start_lineno": 0,
"file": "zxlive/animations.py",
"groundtruth_start_lineno": 65,
"repository": "Quantomatic-zxlive-c7b5c28",
"right_context_start_lineno": 66,
"task_id": "project_cc_python/403"
} | {
"list": [
{
"filename": "zxlive/proof_actions.py",
"retrieved_chunk": " elif self.name == operations['pauli']['text']:\n print('To do: animate ' + self.name)\n panel.undo_stack.push(cmd)\n elif self.name == operations['bialgebra']['text']:\n anim = anim... | setDuration(duration) |
{
"list": [
{
"filename": "zxlive/vitem.py",
"retrieved_chunk": " def _on_state_changed(self, state: QAbstractAnimation.State) -> None:\n if state == QAbstractAnimation.State.Running and self not in self.it.active_animations:\n # Stop all animations that target the same property\n... | import itertools
import random
from typing import Optional, Callable
from PySide6.QtCore import QEasingCurve, QPointF, QAbstractAnimation, \
QParallelAnimationGroup
from PySide6.QtGui import QUndoStack, QUndoCommand
from .common import VT, GraphT, pos_to_view
from .graphscene import GraphScene
from .vitem import ... |
anim.stateChanged.connect(state_changed)
anim.start()
def anticipate_fuse(it: VItem) -> None:
"""Animation that is played when a fuseable spider is dragged onto a vertex."""
scale(it, target=1.25, duration=100, ease=QEasingCurve(QEasingCurve.Type.OutInQuad)).start()
def fuse(dragged: VItem, target:... | {
"context_start_lineno": 0,
"file": "zxlive/animations.py",
"groundtruth_start_lineno": 125,
"repository": "Quantomatic-zxlive-c7b5c28",
"right_context_start_lineno": 126,
"task_id": "project_cc_python/408"
} | {
"list": [
{
"filename": "zxlive/vitem.py",
"retrieved_chunk": " # TODO: Once we use pausing, we should decide what to do here.\n # Note that we cannot just remove ourselves from the set since the garbage\n # collector will eat us in that case. We'll probably need... | currentLoopChanged.connect(set_random_params) |
{
"list": [
{
"filename": "zxlive/proof_actions.py",
"retrieved_chunk": " elif self.name == operations['pauli']['text']:\n print('To do: animate ' + self.name)\n panel.undo_stack.push(cmd)\n elif self.name == operations['bialgebra']['text']:\n anim = anim... | import itertools
import random
from typing import Optional, Callable
from PySide6.QtCore import QEasingCurve, QPointF, QAbstractAnimation, \
QParallelAnimationGroup
from PySide6.QtGui import QUndoStack, QUndoCommand
from .common import VT, GraphT, pos_to_view
from .graphscene import GraphScene
from .vitem import ... |
anim.setDuration(duration)
anim.setStartValue(start or it.scale())
# Important: end value must be a float, otherwise the animation doesn't work because
# start and end have different types
anim.setEndValue(float(target))
anim.setEasingCurve(ease)
return anim
def move(it: VItem, target: QP... | {
"context_start_lineno": 0,
"file": "zxlive/animations.py",
"groundtruth_start_lineno": 64,
"repository": "Quantomatic-zxlive-c7b5c28",
"right_context_start_lineno": 65,
"task_id": "project_cc_python/402"
} | {
"list": [
{
"filename": "zxlive/proof_actions.py",
"retrieved_chunk": " matches = self.matcher(g, lambda v: v in verts)\n else:\n matches = self.matcher(g, lambda e: e in edges)\n if self.button is None: return\n if matches:\n self.button.setEnab... | Properties.Scale) |
{
"list": [
{
"filename": "zxlive/edit_panel.py",
"retrieved_chunk": " return\n cmd = ChangePhase(self.graph_view, v, new_phase)\n self.undo_stack.push(cmd)\n def paste_graph(self, graph: GraphT) -> None:\n if graph is None: return\n new_g = copy.deepcopy(self... | from __future__ import annotations
import copy
from typing import Iterator, Union, cast
import pyzx
from PySide6.QtCore import QPointF, QPersistentModelIndex, Qt, \
QModelIndex, QItemSelection, QRect, QSize
from PySide6.QtGui import QVector2D, QFont, QColor, QPainter, QPen, QFontMetrics, QIcon
from PySide6.QtWidg... |
cmd = AddRewriteStep(self.graph_view, new_g, self.step_view, "remove identity")
self.undo_stack.push(cmd, anim_after=anim)
return True
def _magic_slice(self, trace: WandTrace) -> bool:
def cross(a: QPointF, b: QPointF) -> float:
return a.y() * b.x() - a.x() * b.y()
... | {
"context_start_lineno": 0,
"file": "zxlive/proof_panel.py",
"groundtruth_start_lineno": 174,
"repository": "Quantomatic-zxlive-c7b5c28",
"right_context_start_lineno": 175,
"task_id": "project_cc_python/399"
} | {
"list": [
{
"filename": "zxlive/edit_panel.py",
"retrieved_chunk": " def delete_selection(self) -> None:\n selection = list(self.graph_scene.selected_vertices)\n selected_edges = list(self.graph_scene.selected_edges)\n if not selection and not selected_edges: return\n ... | add_id(v, self.graph_scene) |
{
"list": [
{
"filename": "zxlive/edit_panel.py",
"retrieved_chunk": " return\n cmd = ChangePhase(self.graph_view, v, new_phase)\n self.undo_stack.push(cmd)\n def paste_graph(self, graph: GraphT) -> None:\n if graph is None: return\n new_g = copy.deepcopy(self... | from __future__ import annotations
import copy
from typing import Iterator, Union, cast
import pyzx
from PySide6.QtCore import QPointF, QPersistentModelIndex, Qt, \
QModelIndex, QItemSelection, QRect, QSize
from PySide6.QtGui import QVector2D, QFont, QColor, QPainter, QPen, QFontMetrics, QIcon
from PySide6.QtWidg... |
cmd = AddRewriteStep(self.graph_view, new_g, self.step_view, "unfuse")
self.undo_stack.push(cmd, anim_after=anim)
def _vert_double_clicked(self, v: VT) -> None:
if self.graph.type(v) == VertexType.BOUNDARY:
return
new_g = copy.deepcopy(self.graph)
basicrules.co... | {
"context_start_lineno": 0,
"file": "zxlive/proof_panel.py",
"groundtruth_start_lineno": 275,
"repository": "Quantomatic-zxlive-c7b5c28",
"right_context_start_lineno": 276,
"task_id": "project_cc_python/401"
} | {
"list": [
{
"filename": "zxlive/edit_panel.py",
"retrieved_chunk": " def delete_selection(self) -> None:\n selection = list(self.graph_scene.selected_vertices)\n selected_edges = list(self.graph_scene.selected_edges)\n if not selection and not selected_edges: return\n ... | unfuse(self.graph, new_g, v, self.graph_scene) |
{
"list": [
{
"filename": "zxlive/proof_panel.py",
"retrieved_chunk": " self._remove_id(vertex)\n return True\n start = trace.hit[item][0]\n end = trace.hit[item][-1]\n if start.y() > end.y():\n start, end = end, start\n pos = QPointF(*pos_t... | import itertools
import random
from typing import Optional, Callable
from PySide6.QtCore import QEasingCurve, QPointF, QAbstractAnimation, \
QParallelAnimationGroup
from PySide6.QtGui import QUndoStack, QUndoCommand
from .common import VT, GraphT, pos_to_view
from .graphscene import GraphScene
from .vitem import ... |
anim.setEasingCurve(QEasingCurve.Type.InOutExpo)
anim.setDuration(duration)
def set_random_params() -> None:
dx = (2 * random.random() - 1) * amount
dy = (2 * random.random() - 1) * amount
anim.setStartValue(it.pos())
anim.setEndValue(QPointF(center.x() + dx, center.y() + d... | {
"context_start_lineno": 0,
"file": "zxlive/animations.py",
"groundtruth_start_lineno": 110,
"repository": "Quantomatic-zxlive-c7b5c28",
"right_context_start_lineno": 111,
"task_id": "project_cc_python/407"
} | {
"list": [
{
"filename": "zxlive/proof_panel.py",
"retrieved_chunk": " # Compute whether each neighbor is inside the entry and exit points\n i1 = cross(start - pos, npos - pos) * cross(start - pos, end - pos) >= 0\n i2 = cross(end - pos, npos - pos) * cross(end - pos,... | setLoopCount(-1) # Infinite looping |
{
"list": [
{
"filename": "zxlive/commands.py",
"retrieved_chunk": " _new_vert: Optional[VT] = field(default=None, init=False)\n def undo(self) -> None:\n u, v, w = self.u, self.v, self._new_vert\n assert w is not None\n g = self.g\n et = g.edge_type(g.edge(v, w))\n ... | from __future__ import annotations
import copy
from typing import Iterator, Union, cast
import pyzx
from PySide6.QtCore import QPointF, QPersistentModelIndex, Qt, \
QModelIndex, QItemSelection, QRect, QSize
from PySide6.QtGui import QVector2D, QFont, QColor, QPainter, QPen, QFontMetrics, QIcon
from PySide6.QtWidg... |
def _vertex_dropped_onto(self, v: VT, w: VT) -> None:
if pyzx.basicrules.check_fuse(self.graph, v, w):
g = copy.deepcopy(self.graph)
pyzx.basicrules.fuse(g, w, v)
anim = anims.fuse(self.graph_scene.vertex_map[v], self.graph_scene.vertex_map[w])
cmd = AddRewr... | {
"context_start_lineno": 0,
"file": "zxlive/proof_panel.py",
"groundtruth_start_lineno": 129,
"repository": "Quantomatic-zxlive-c7b5c28",
"right_context_start_lineno": 130,
"task_id": "project_cc_python/396"
} | {
"list": [
{
"filename": "zxlive/commands.py",
"retrieved_chunk": " self.update_graph_view()\n def redo(self) -> None:\n u, v = self.u, self.v\n g = self.g\n uv = g.edge(u, v)\n r = 0.5 * (g.row(u) + g.row(v))\n q = 0.5 * (g.qubit(u) + g.qubit(v))\n ... | back_to_default(self.graph_scene.vertex_map[w]) |
{
"list": [
{
"filename": "zxlive/mainwindow.py",
"retrieved_chunk": " if isinstance(self.active_panel, GraphEditPanel):\n self.active_panel.delete_selection()\n def new_graph(self, graph:Optional[GraphT] = None, name:Optional[str]=None) -> None:\n graph = graph or Graph()\... | import copy
from dataclasses import dataclass, field, replace
from typing import Callable, Literal, List, Optional, TYPE_CHECKING
import networkx as nx
from networkx.algorithms.isomorphism import GraphMatcher, categorical_node_match
import numpy as np
import pyzx
from pyzx.utils import VertexType, EdgeType
from shapel... |
panel.undo_stack.push(cmd, anim_before=anim)
elif self.name == operations['copy']['text']:
anim = anims.strong_comp(panel.graph, g, verts[0], panel.graph_scene)
panel.undo_stack.push(cmd, anim_after=anim)
# print('To do: animate ' + self.name)
# panel... | {
"context_start_lineno": 0,
"file": "zxlive/proof_actions.py",
"groundtruth_start_lineno": 68,
"repository": "Quantomatic-zxlive-c7b5c28",
"right_context_start_lineno": 69,
"task_id": "project_cc_python/418"
} | {
"list": [
{
"filename": "zxlive/proof_panel.py",
"retrieved_chunk": " def _wand_trace_finished(self, trace: WandTrace) -> None:\n if self._magic_slice(trace):\n return\n elif self._magic_identity(trace):\n return\n def _magic_identity(self, trace: WandTrace)... | remove_id(panel.graph_scene.vertex_map[verts[0]]) |
{
"list": [
{
"filename": "zxlive/proof_panel.py",
"retrieved_chunk": " pyzx.basicrules.fuse(g, w, v)\n anim = anims.fuse(self.graph_scene.vertex_map[v], self.graph_scene.vertex_map[w])\n cmd = AddRewriteStep(self.graph_view, g, self.step_view, \"fuse spiders\")\n ... | import copy
from dataclasses import dataclass, field, replace
from typing import Callable, Literal, List, Optional, TYPE_CHECKING
import networkx as nx
from networkx.algorithms.isomorphism import GraphMatcher, categorical_node_match
import numpy as np
import pyzx
from pyzx.utils import VertexType, EdgeType
from shapel... |
panel.undo_stack.push(cmd, anim_after=anim)
# print('To do: animate ' + self.name)
# panel.undo_stack.push(cmd)
elif self.name == operations['pauli']['text']:
print('To do: animate ' + self.name)
panel.undo_stack.push(cmd)
elif self.name == op... | {
"context_start_lineno": 0,
"file": "zxlive/proof_actions.py",
"groundtruth_start_lineno": 71,
"repository": "Quantomatic-zxlive-c7b5c28",
"right_context_start_lineno": 72,
"task_id": "project_cc_python/419"
} | {
"list": [
{
"filename": "zxlive/proof_panel.py",
"retrieved_chunk": " def _wand_trace_finished(self, trace: WandTrace) -> None:\n if self._magic_slice(trace):\n return\n elif self._magic_identity(trace):\n return\n def _magic_identity(self, trace: WandTrace)... | strong_comp(panel.graph, g, verts[0], panel.graph_scene) |
{
"list": [
{
"filename": "zxlive/dialogs.py",
"retrieved_chunk": "from zxlive.proof import ProofModel\nfrom .common import VT,ET, GraphT, Graph\nclass FileFormat(Enum):\n \"\"\"Supported formats for importing/exporting diagrams.\"\"\"\n All = \"zxg *.json *.qasm *.tikz *.zxp\", \"All Supported ... | import json
from typing import NamedTuple, Union, Any
from PySide6.QtCore import QAbstractListModel, QModelIndex, QPersistentModelIndex, Qt
from PySide6.QtGui import QFont
from pyzx.graph import GraphDiff
from zxlive.common import GraphT
class Rewrite(NamedTuple):
"""A rewrite turns a graph into another graph."... |
assert isinstance(initial_graph, GraphT)
model = ProofModel(initial_graph)
for step in d["proof_steps"]:
rewrite = Rewrite.from_json(step)
rewritten_graph = rewrite.diff.apply_diff(model.graphs[-1])
assert isinstance(rewritten_graph, GraphT)
model... | {
"context_start_lineno": 0,
"file": "zxlive/proof.py",
"groundtruth_start_lineno": 133,
"repository": "Quantomatic-zxlive-c7b5c28",
"right_context_start_lineno": 134,
"task_id": "project_cc_python/416"
} | {
"list": [
{
"filename": "zxlive/dialogs.py",
"retrieved_chunk": " _value_: str\n def __new__(cls, *args, **kwds): # type: ignore\n obj = object.__new__(cls)\n obj._value_ = args[0] # Use extension as `_value_`\n return obj\n def __init__(self, _extension: str, name: s... | from_tikz(d["initial_graph"]) |
{
"list": [
{
"filename": "zxlive/proof_panel.py",
"retrieved_chunk": " pyzx.basicrules.fuse(g, w, v)\n anim = anims.fuse(self.graph_scene.vertex_map[v], self.graph_scene.vertex_map[w])\n cmd = AddRewriteStep(self.graph_view, g, self.step_view, \"fuse spiders\")\n ... | import copy
from dataclasses import dataclass, field, replace
from typing import Callable, Literal, List, Optional, TYPE_CHECKING
import networkx as nx
from networkx.algorithms.isomorphism import GraphMatcher, categorical_node_match
import numpy as np
import pyzx
from pyzx.utils import VertexType, EdgeType
from shapel... |
panel.undo_stack.push(cmd, anim_before=anim)
elif self.name == operations['to_z']['text']:
print('To do: animate ' + self.name)
panel.undo_stack.push(cmd)
elif self.name == operations['to_x']['text']:
print('To do: animate ' + self.name)
panel... | {
"context_start_lineno": 0,
"file": "zxlive/proof_actions.py",
"groundtruth_start_lineno": 59,
"repository": "Quantomatic-zxlive-c7b5c28",
"right_context_start_lineno": 60,
"task_id": "project_cc_python/417"
} | {
"list": [
{
"filename": "zxlive/proof_panel.py",
"retrieved_chunk": " def _wand_trace_finished(self, trace: WandTrace) -> None:\n if self._magic_slice(trace):\n return\n elif self._magic_identity(trace):\n return\n def _magic_identity(self, trace: WandTrace)... | fuse(panel.graph_scene.vertex_map[verts[0]], panel.graph_scene.vertex_map[verts[1]]) |
{
"list": [
{
"filename": "llm_utils.py",
"retrieved_chunk": " data = load_jsonl(input_file_or_data)\n os.makedirs(os.path.dirname(output_file), exist_ok=True)\n with open(output_file, 'w') as fo:\n for x, a in zip(data, y_pred):\n if x.get(task_key) is None:\n ... | import os
import sys
import random
import ujson as json
import numpy as np
import cjjpy as cjj
sys.path.append('..')
from gpt3_helper import prompt_gpt3, calc_cost_w_prompt
from utils import load_jsonl, rel2text, chunks_list_first
from llm_utils import examples_to_text
np.random.seed(42)
random.seed(42)
boolqg_instru... |
return y_pred
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--input_file', '-i', type=str, required=True)
parser.add_argument('--model_name', '-m', type=str, required=True)
parser.add_argument('--output_file', '-o', type=str, required=... | {
"context_start_lineno": 0,
"file": "boolqa/llm_boolqg.py",
"groundtruth_start_lineno": 93,
"repository": "jiangjiechen-uncommongen-7d1c76e",
"right_context_start_lineno": 94,
"task_id": "project_cc_python/428"
} | {
"list": [
{
"filename": "llm_utils.py",
"retrieved_chunk": " data = load_jsonl(input_file_or_data)\n os.makedirs(os.path.dirname(output_file), exist_ok=True)\n with open(output_file, 'w') as fo:\n for x, a in zip(data, y_pred):\n if x.get(task_key) is None:\n ... | lark(f"This run has cost you {round(money, 2)}$: {model_key}.") |
{
"list": [
{
"filename": "preprocessing/calculate_cooccurrence.py",
"retrieved_chunk": " fw.write(json.dumps(x) + '\\n')\nif __name__ == \"__main__\":\n sents = load_sentences()\n with open(f'{os.environ[\"PJ_HOME\"]}/data/probe_datasets/true-neg-llm_test.clean.jsonl') as f:\n data = ... | import os
import re
import ujson as json
import cjjpy as cjj
REL_TO_BOOLQ_TEMPLATE = {
"IsA": "is [w1] a type of [w2]?",
'CapableOf': "can [w1] [w2]?",
'UsedFor': "is [w1] used for [w2]?",
"MadeOf": "is [w1] made of [w2]?",
'HasProperty': "does [w1] has the property of [w2]?",
'HasSubevent': "... |
weight_threshold = cw_tuple[int(top_percentage * len(cw_dict))]
return cw_dict, weight_threshold[-1]
def load_jsonl(jsl_or_path):
if isinstance(jsl_or_path, str):
with open(jsl_or_path) as f:
data = [json.loads(line) for line in f]
else:
data = jsl_or_path
return data
... | {
"context_start_lineno": 0,
"file": "utils.py",
"groundtruth_start_lineno": 138,
"repository": "jiangjiechen-uncommongen-7d1c76e",
"right_context_start_lineno": 139,
"task_id": "project_cc_python/423"
} | {
"list": [
{
"filename": "preprocessing/calculate_cooccurrence.py",
"retrieved_chunk": " js = json.loads(line)\n p.apply_async(cooccur_cnt, (js,), callback=callback)\n p.close()\n p.join()\n fw.close()",
"score": 45.96142515574183
},
{
"filename": "preproces... | SortDict(cw_dict) |
{
"list": [
{
"filename": "downstream/speechglue/data_prep.py",
"retrieved_chunk": " default=\"cuda\",\n choices=[\"cuda\", \"cpu\"],\n help=\"Pytorch device\",\n )\n parser.add_argument(\n \"--num-workers\",\n type=int,\n default=1,\n help=\"Numb... | # Copyleft (c), Speech Lab, NTU, Taiwan
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
# This code changes to load speechGLUE data based on the following code (and some code formatting).
# https://github.com/huggingface/transformers/blob/7378726df60b9cf399aacfe372fea629c1c4c7d3/examples/pytorch/text-classi... |
return d
def __len__(self):
return len(self.X)
def __getitem__(self, index):
# Load acoustic feature and pad
wav_batch = [self._load_wav(x_file).numpy() for x_file in self.X[index]]
label_batch = [y.numpy() for y in self.Y[index]]
filename_batch = [self._parse_... | {
"context_start_lineno": 0,
"file": "downstream/speechglue_asr/dataset.py",
"groundtruth_start_lineno": 152,
"repository": "ashi-ta-speechGLUE-724cf40",
"right_context_start_lineno": 153,
"task_id": "project_cc_python/466"
} | {
"list": [
{
"filename": "downstream/speechglue_asr/mk_char_dict.py",
"retrieved_chunk": " char_counts.items(), key=lambda char: char[1], reverse=True\n ):\n f.write(x[0] + \" \" + str(x[1]) + \"\\n\")\nif __name__ == \"__main__\":\n main()",
"score":... | finalize(threshold=threshold, nwords=nwords, padding_factor=padding_factor) |
{
"list": [
{
"filename": "src/models/DistMult.py",
"retrieved_chunk": " rel_embedding = self._w_relation(etype_id)\n rel_mask = (etypes == etype_id)\n graph.edata[\"dot_prod\"][rel_mask] *= rel_embedding\n check_mask[rel_mask] = True\n ... | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import dgl
import dgl.function as fn
import tqdm
from collections import deque
import time
from functools import cached_property
import warnings
from .DistMult import DistMultDecoder
class BaseLinkEncoderDecoder(nn.Module):
'''
... |
def decoder_mat(self, uh, vh, etypes=None):
'''
Get link prediction scores from embeddings of source and destination nodes.
Parameters:
----------
uh: torch.Tensor
Embeddings of source nodes
vh: torch.Tensor
Embeddings of des... | {
"context_start_lineno": 0,
"file": "src/models/BaseModules.py",
"groundtruth_start_lineno": 271,
"repository": "amazon-science-random-tma-43df305",
"right_context_start_lineno": 272,
"task_id": "project_cc_python/420"
} | {
"list": [
{
"filename": "src/models/DistMult.py",
"retrieved_chunk": " else:\n return score\n def decoder_mat(self, uh, vh, etypes):\n '''\n Overrides `BaseLinkEncoderDecoder.decoder_mat`.\n '''\n h = uh * vh\n check_mask = torch.zeros_like(ety... | decoder(z, graph, neg_graph) |
{
"list": [
{
"filename": "downstream/speechglue_asr/mk_char_dict.py",
"retrieved_chunk": " char_counts.items(), key=lambda char: char[1], reverse=True\n ):\n f.write(x[0] + \" \" + str(x[1]) + \"\\n\")\nif __name__ == \"__main__\":\n main()",
"score":... | # Copyleft (c), Speech Lab, NTU, Taiwan
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
# This code changes to load speechGLUE data based on the following code (and some code formatting).
# https://github.com/huggingface/transformers/blob/7378726df60b9cf399aacfe372fea629c1c4c7d3/examples/pytorch/text-classi... |
d.finalize(threshold=threshold, nwords=nwords, padding_factor=padding_factor)
return d
def __len__(self):
return len(self.X)
def __getitem__(self, index):
# Load acoustic feature and pad
wav_batch = [self._load_wav(x_file).numpy() for x_file in self.X[index]]
l... | {
"context_start_lineno": 0,
"file": "downstream/speechglue_asr/dataset.py",
"groundtruth_start_lineno": 151,
"repository": "ashi-ta-speechGLUE-724cf40",
"right_context_start_lineno": 152,
"task_id": "project_cc_python/465"
} | {
"list": [
{
"filename": "downstream/speechglue_asr/mk_char_dict.py",
"retrieved_chunk": " char_counts.items(), key=lambda char: char[1], reverse=True\n ):\n f.write(x[0] + \" \" + str(x[1]) + \"\\n\")\nif __name__ == \"__main__\":\n main()",
"score":... | add_transcripts_to_dictionary(transcript_list, d, workers) |
{
"list": [
{
"filename": "multigrid/utils/enum.py",
"retrieved_chunk": " name : str\n Name of the new enum item\n value : Any\n Value of the new enum item\n \"\"\"\n enum.extend_enum(cls, name, value)\n _enum_array.cache_clear()\n _enum_... | import enum
import numpy as np
from numpy.typing import NDArray as ndarray
from ..utils.enum import IndexedEnum
#: Tile size for rendering grid cell
TILE_PIXELS = 32
COLORS = {
'red': np.array([255, 0, 0]),
'green': np.array([0, 255, 0]),
'blue': np.array([0, 0, 255]),
'purple': np.array([112, 39, ... |
COLORS[name] = np.asarray(rgb, dtype=np.uint8)
@staticmethod
def cycle(n: int) -> tuple['Color', ...]:
"""
Return a cycle of ``n`` colors.
"""
return tuple(Color.from_index(i % len(Color)) for i in range(int(n)))
def rgb(self) -> ndarray[np.uint8]:
"""
... | {
"context_start_lineno": 0,
"file": "multigrid/core/constants.py",
"groundtruth_start_lineno": 73,
"repository": "ini-multigrid-01ee811",
"right_context_start_lineno": 74,
"task_id": "project_cc_python/504"
} | {
"list": [
{
"filename": "multigrid/utils/enum.py",
"retrieved_chunk": " \"\"\"\n Return the enum item corresponding to the given index.\n Also supports vector inputs.\n Parameters\n ----------\n index : int or ArrayLike[int]\n Enum index (or array... | add_item(name, name) |
{
"list": [
{
"filename": "multigrid/core/agent.py",
"retrieved_chunk": " obj = np.zeros(dims + (cls.dim,), dtype=int).view(cls)\n # Set default values\n obj[..., AgentState.TYPE] = Type.agent\n obj[..., AgentState.COLOR].flat = Color.cycle(np.prod(dims))\n obj[..., ... | import enum
import numpy as np
from numpy.typing import NDArray as ndarray
from ..utils.enum import IndexedEnum
#: Tile size for rendering grid cell
TILE_PIXELS = 32
COLORS = {
'red': np.array([255, 0, 0]),
'green': np.array([0, 255, 0]),
'blue': np.array([0, 0, 255]),
'purple': np.array([112, 39, ... |
def rgb(self) -> ndarray[np.uint8]:
"""
Return the RGB value of this ``Color``.
"""
return COLORS[self]
class State(str, IndexedEnum):
"""
Enumeration of object states.
"""
open = 'open'
closed = 'closed'
locked = 'locked'
class Direction(enum.IntEnum):
... | {
"context_start_lineno": 0,
"file": "multigrid/core/constants.py",
"groundtruth_start_lineno": 81,
"repository": "ini-multigrid-01ee811",
"right_context_start_lineno": 82,
"task_id": "project_cc_python/505"
} | {
"list": [
{
"filename": "multigrid/utils/enum.py",
"retrieved_chunk": " \"\"\"\n Return the enum item corresponding to the given index.\n Also supports vector inputs.\n Parameters\n ----------\n index : int or ArrayLike[int]\n Enum index (or array... | from_index(i % len(Color)) for i in range(int(n))) |
{
"list": [
{
"filename": "multigrid/envs/empty.py",
"retrieved_chunk": " **kwargs,\n )\n def _gen_grid(self, width, height):\n \"\"\"\n :meta private:\n \"\"\"\n # Create an empty grid\n self.grid = Grid(width, height)\n # Generate the su... | from __future__ import annotations
from multigrid import MultiGridEnv
from multigrid.core import Action, Grid, MissionSpace
from multigrid.core.constants import Color
from multigrid.core.world_object import Door
class RedBlueDoorsEnv(MultiGridEnv):
"""
.. image:: https://i.imgur.com/usbavAh.gif
:wid... |
# Add a red door at a random position in the left wall
x = room_top[0]
y = self._rand_int(1, height - 1)
self.red_door = Door(Color.red)
self.grid.set(x, y, self.red_door)
# Add a blue door at a random position in the right wall
x = room_top[0] + room_size[0] -... | {
"context_start_lineno": 0,
"file": "multigrid/envs/redbluedoors.py",
"groundtruth_start_lineno": 155,
"repository": "ini-multigrid-01ee811",
"right_context_start_lineno": 156,
"task_id": "project_cc_python/471"
} | {
"list": [
{
"filename": "multigrid/envs/empty.py",
"retrieved_chunk": " # Place a goal square in the bottom-right corner\n self.put_obj(Goal(), width - 2, height - 2)\n # Place the agent\n for agent in self.agents:\n if self.agent_start_pos is not None and self... | place_agent(agent, top=room_top, size=room_size) |
{
"list": [
{
"filename": "multigrid/envs/empty.py",
"retrieved_chunk": " agent_start_dir : Direction, default=Direction.right\n Starting direction of the agents (random if None)\n max_steps : int, optional\n Maximum number of steps per episode\n joint_reward... | from __future__ import annotations
from multigrid import MultiGridEnv
from multigrid.core import Action, Grid, MissionSpace
from multigrid.core.constants import Color
from multigrid.core.world_object import Door
class RedBlueDoorsEnv(MultiGridEnv):
"""
.. image:: https://i.imgur.com/usbavAh.gif
:wid... |
super().__init__(
mission_space=mission_space,
width=(2 * size),
height=size,
max_steps=max_steps or (20 * size**2),
joint_reward=joint_reward,
success_termination_mode=success_termination_mode,
failure_termination_mode=failure... | {
"context_start_lineno": 0,
"file": "multigrid/envs/redbluedoors.py",
"groundtruth_start_lineno": 128,
"repository": "ini-multigrid-01ee811",
"right_context_start_lineno": 129,
"task_id": "project_cc_python/468"
} | {
"list": [
{
"filename": "multigrid/envs/empty.py",
"retrieved_chunk": " See :attr:`multigrid.base.MultiGridEnv.__init__`\n \"\"\"\n self.agent_start_pos = agent_start_pos\n self.agent_start_dir = agent_start_dir\n super().__init__(\n mission_space=\"... | from_string("open the red door then the blue door") |
{
"list": [
{
"filename": "multigrid/core/roomgrid.py",
"retrieved_chunk": " # Create rooms\n for row in range(self.num_rows):\n for col in range(self.num_cols):\n room = Room(\n (col * (self.room_size - 1), row * (self.room_size - 1)),\n ... | from __future__ import annotations
from multigrid import MultiGridEnv
from multigrid.core import Action, Grid, MissionSpace
from multigrid.core.constants import Color
from multigrid.core.world_object import Door
class RedBlueDoorsEnv(MultiGridEnv):
"""
.. image:: https://i.imgur.com/usbavAh.gif
:wid... |
self.red_door = Door(Color.red)
self.grid.set(x, y, self.red_door)
# Add a blue door at a random position in the right wall
x = room_top[0] + room_size[0] - 1
y = self._rand_int(1, height - 1)
self.blue_door = Door(Color.blue)
self.grid.set(x, y, self.blue_door)... | {
"context_start_lineno": 0,
"file": "multigrid/envs/redbluedoors.py",
"groundtruth_start_lineno": 159,
"repository": "ini-multigrid-01ee811",
"right_context_start_lineno": 160,
"task_id": "project_cc_python/472"
} | {
"list": [
{
"filename": "multigrid/core/grid.py",
"retrieved_chunk": " Width of rectangle\n h : int\n Height of rectangle\n \"\"\"\n self.horz_wall(x, y, w)\n self.horz_wall(x, y + h - 1, w)\n self.vert_wall(x, y, h)\n self.vert_wall(x ... | _rand_int(1, height - 1) |
{
"list": [
{
"filename": "falcontune/data.py",
"retrieved_chunk": " )\n return {\n \"input_ids\": result[\"input_ids\"][:-1],\n \"attention_mask\": result[\"attention_mask\"][:-1],\n }\n def prepare_data(self, use_eos_token=True, **kwa... | import re
import torch
import warnings
from peft.tuners import lora
from peft.tuners.lora import Linear, LoraLayer
from peft import PeftModel, get_peft_model
from peft.utils import _get_submodules, PeftType
from transformers.pytorch_utils import Conv1D
from falcontune.backend.base import QuantLinearBase
class Linea... |
expected_dtype = result.dtype
if x.dtype != torch.float32:
x = x.float()
output = (
self.lora_B[self.active_adapter](
self.lora_A[self.active_adapter](self.lora_dropout[self.active_adapter](x))
... | {
"context_start_lineno": 0,
"file": "falcontune/model/lora.py",
"groundtruth_start_lineno": 58,
"repository": "rmihaylov-falcontune-6bd029e",
"right_context_start_lineno": 59,
"task_id": "project_cc_python/517"
} | {
"list": [
{
"filename": "falcontune/data.py",
"retrieved_chunk": " self.val_data = train_val[\"test\"].shuffle().map(lambda x: self.generate_and_tokenize_prompt(x, use_eos_token=use_eos_token))\n else:\n self.train_data = data[\"train\"].shuffle().map(lambda x: self.gene... | is_autocast_enabled(): |
{
"list": [
{
"filename": "multigrid/core/grid.py",
"retrieved_chunk": " def wall_rect(self, x: int, y: int, w: int, h: int):\n \"\"\"\n Create a walled rectangle.\n Parameters\n ----------\n x : int\n X-coordinate of top-left corner\n y : int\n ... | from __future__ import annotations
from multigrid import MultiGridEnv
from multigrid.core import Action, Grid, MissionSpace
from multigrid.core.constants import Color
from multigrid.core.world_object import Door
class RedBlueDoorsEnv(MultiGridEnv):
"""
.. image:: https://i.imgur.com/usbavAh.gif
:wid... |
# Add a blue door at a random position in the right wall
x = room_top[0] + room_size[0] - 1
y = self._rand_int(1, height - 1)
self.blue_door = Door(Color.blue)
self.grid.set(x, y, self.blue_door)
def step(self, actions):
"""
:meta private:
"""
... | {
"context_start_lineno": 0,
"file": "multigrid/envs/redbluedoors.py",
"groundtruth_start_lineno": 161,
"repository": "ini-multigrid-01ee811",
"right_context_start_lineno": 162,
"task_id": "project_cc_python/474"
} | {
"list": [
{
"filename": "multigrid/core/roomgrid.py",
"retrieved_chunk": " if dir == Direction.right:\n if random:\n self.door_pos[dir] = (right, random.integers(top + 1, bottom))\n else:\n self.door_pos[dir] = (right, (top + bottom) // 2)\n... | set(x, y, self.red_door) |
{
"list": [
{
"filename": "falcontune/finetune.py",
"retrieved_chunk": " self.ddp = self.world_size != 1\n self.device_map = \"auto\" if not self.ddp else {\"\": self.local_rank}\n if self.ddp:\n self.gradient_accumulation_steps = self.gradient_accumulation_steps // sel... | from abc import ABC, abstractmethod
from typing import Dict, Any
import torch
from datasets import Dataset, load_dataset
from transformers.utils import logging
logger = logging.get_logger("transformers")
class TrainDataBase(ABC):
"""
"""
@abstractmethod
def __init__(self, dataset: str, val_set_size:... |
# ignore bos
newline_tokens = self.tokenizer("\n", return_tensors="pt")["input_ids"][0, 1:]
out = {"labels": [], "attention_mask": []}
for i, (prompt, response) in enumerate(zip(examples["prompt"], examples["response"])):
input_tokens = self.tokenizer(prompt, truncation=Tru... | {
"context_start_lineno": 0,
"file": "falcontune/data.py",
"groundtruth_start_lineno": 47,
"repository": "rmihaylov-falcontune-6bd029e",
"right_context_start_lineno": 48,
"task_id": "project_cc_python/509"
} | {
"list": [
{
"filename": "falcontune/finetune.py",
"retrieved_chunk": " f\"{self.gradient_checkpointing=}\\n{self.gradient_checkpointing_ratio=}\\n\" + \\\n f\"{self.warmup_steps=}\\n{self.save_steps=}\\n{self.save_total_limit=}\\n\" + \\\n f\"{self.logging_steps=}\\n... | full((len(examples["prompt"]), max_length), self.tokenizer.pad_token_id) |
{
"list": [
{
"filename": "falcontune/model/falcon/model.py",
"retrieved_chunk": " use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ... | from abc import ABC, abstractmethod
from typing import Dict, Any
import torch
from datasets import Dataset, load_dataset
from transformers.utils import logging
logger = logging.get_logger("transformers")
class TrainDataBase(ABC):
"""
"""
@abstractmethod
def __init__(self, dataset: str, val_set_size:... |
return out
def prepare_data(self, **kwargs) -> None:
dataset = load_dataset("json", data_files=self.dataset)
self.val_data = None
if self.val_set_size > 0:
dataset = dataset["train"].train_test_split(
test_size=self.val_set_size, shuffle=True, seed=42 ... | {
"context_start_lineno": 0,
"file": "falcontune/data.py",
"groundtruth_start_lineno": 89,
"repository": "rmihaylov-falcontune-6bd029e",
"right_context_start_lineno": 90,
"task_id": "project_cc_python/510"
} | {
"list": [
{
"filename": "falcontune/model/falcon/model.py",
"retrieved_chunk": " are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`\n \"\"\"\n if deprecated_arguments.pop(\"position_ids\", False) is not False:\n # `position... | stack(v) if isinstance(v, list) else v for k, v in out.items()} |
{
"list": [
{
"filename": "falcontune/backend/cuda/quantlinear.py",
"retrieved_chunk": " self.qzeros, self.g_idx, self.bits, self.maxq)\n else:\n out_shape = x.shape[:-1] + (self.outfeatures,)\n x = x.reshape(-1, x.shape[-1])\n out = torch.zeros((... | import torch
from torch.cuda.amp import custom_bwd, custom_fwd
import quant_cuda
# Global Buffer
buffer_mat_dic = {}
cache_buffer = True
def get_buffer(shape_of_qweight, dtype=torch.float16, device='cuda'):
if not cache_buffer:
return torch.zeros((shape_of_qweight[0] * 8, shape_of_qweight[1]), dtype=dt... |
return output
class AutogradMatmul(torch.autograd.Function):
@staticmethod
@custom_fwd(cast_inputs=torch.float16)
def forward(ctx, x, qweight, scales, zeros, g_idx, bits, maxq):
if bits not in [4]:
raise NotImplemented('bits in [4]')
ctx.save_for_backward(qweight, scales,... | {
"context_start_lineno": 0,
"file": "falcontune/backend/cuda/autograd.py",
"groundtruth_start_lineno": 30,
"repository": "rmihaylov-falcontune-6bd029e",
"right_context_start_lineno": 31,
"task_id": "project_cc_python/513"
} | {
"list": [
{
"filename": "falcontune/backend/cuda/quantlinear.py",
"retrieved_chunk": " quant_cuda.vecquant4matmul(x.float(), self.qweight, out, self.scales.float(), self.qzeros, self.g_idx)\n elif self.bits == 8:\n quant_cuda.vecquant8matmul(x.float(), self.q... | matmul(x, buffer) if not transpose else torch.matmul(x, buffer.T) |
{
"list": [
{
"filename": "peachdb/backends/numpy_backend.py",
"retrieved_chunk": " elif query_embed.ndim == 2:\n if query_embed.shape[0] != 1:\n raise ValueError(\"query_embed should be a vector or a matrix with one row\")\n else:\n raise ValueError(\"query_embed should... | from typing import Tuple
import hnswlib # type: ignore
import numpy as np
from rich import print
from peachdb.backends.backend_base import BackendBase, BackendConfig
from peachdb.embedder.utils import Modality
class HNSWBackend(BackendBase):
def __init__(
self,
backend_config: BackendConfig,
... |
self._max_elements = self._embeddings.shape[0]
# initialise index.
# TODO: fix to support multiple upserts. (#multiple-upserts)
self._hnsw_index.init_index(
max_elements=self._max_elements,
ef_construction=min(200, self._embeddings.shape[0]), # default param
... | {
"context_start_lineno": 0,
"file": "peachdb/backends/hnsw_backend.py",
"groundtruth_start_lineno": 23,
"repository": "peach-db-peachdb-0fb089b",
"right_context_start_lineno": 24,
"task_id": "project_cc_python/525"
} | {
"list": [
{
"filename": "peachdb/backends/numpy_backend.py",
"retrieved_chunk": " Calculate l2 distance between a query embedding and a set of embeddings.\n \"\"\"\n query_embed, embeds = _check_dims(query_embed, embeds)\n return np.linalg.norm(query_embed - embeds, axis=1)\ndef cosine(q... | _distance_metric, dim=self._dim) |
{
"list": [
{
"filename": "deploy_api.py",
"retrieved_chunk": " try:\n ids, distances, metadata = peach_db.query(query_input=text, modality=\"text\", namespace=namespace, top_k=top_k)\n except EmptyNamespace:\n return Response(content=\"Empty namespace.\", status_code=400)\n res... | import dotenv
dotenv.load_dotenv()
import shelve
import tempfile
from typing import Iterator, Optional, Union
from uuid import uuid4
import openai
import pandas as pd
from peachdb import PeachDB
from peachdb.constants import BOTS_DB, CONVERSATIONS_DB, SHELVE_DB
class ConversationNotFoundError(ValueError):
pas... |
assert "texts" in context_metadata
contextual_query = "Use the below snippets to answer the subsequent questions. If the answer can't be found, write \"I don't know.\""
for text in context_metadata["texts"]:
contextual_query += f"\n\nSnippet:\n{text}"
contextual_query += f"... | {
"context_start_lineno": 0,
"file": "peachdb/bots/qa.py",
"groundtruth_start_lineno": 212,
"repository": "peach-db-peachdb-0fb089b",
"right_context_start_lineno": 213,
"task_id": "project_cc_python/522"
} | {
"list": [
{
"filename": "peachdb/embedder/__init__.py",
"retrieved_chunk": " assert not is_s3_uri(self._csv_path)\n assert self._modality == Modality.TEXT\n for idx, chunk in enumerate(chunks):\n embeddings_dict = {}\n embeddings_dict[\"... | query(query, top_k=top_k, modality="text") |
{
"list": [
{
"filename": "test/test_loop_analysis.py",
"retrieved_chunk": "print(f'End: {a} {b}')\n\"\"\"\nclass MutatedVarTest(unittest.TestCase):\n def test_simple_loop(self):\n tree, id_gen = singleline.analysis.preprocess(SIMP_LOOP_MUT)\n singleline.analysis.control_flow_pass(tre... | import ast
import unittest
import networkx as nx
from .context import singleline
from .utils import plot_graph
SIMPLE_FUNC = """
a = int(input())
a = a + 1
if a == 2:
a += 2
elif a == 3:
assert 2 == 1, 'nope'
b = 3
print(a, b)
"""
COMPLEX_FUNC = """
def foo():
a = a + 1
if a == 2:
c = 2
... |
singleline.analysis.control_flow_pass(tree)
graph = tree.graph
common = singleline.misc.get_all_convergence(graph, tree)
for i, ans in zip(common[-1].bundle, ['b=3', 'print(a,b)']):
self.assertEqual(ast.unparse(i).replace(' ', ''), ans)
def test_complex_func(self):
... | {
"context_start_lineno": 0,
"file": "test/test_cfg.py",
"groundtruth_start_lineno": 42,
"repository": "davidmaamoaix-singleline-311d35f",
"right_context_start_lineno": 43,
"task_id": "project_cc_python/547"
} | {
"list": [
{
"filename": "test/test_loop_analysis.py",
"retrieved_chunk": "print(f'End: {a} {b}')\n\"\"\"\nclass MutatedVarTest(unittest.TestCase):\n def test_simple_loop(self):\n tree, id_gen = singleline.analysis.preprocess(SIMP_LOOP_MUT)\n singleline.analysis.control_flow_pass(tre... | analysis.preprocess(SIMPLE_FUNC) |
{
"list": [
{
"filename": "singleline/transform/transpiler.py",
"retrieved_chunk": " This class is responsible for transpiling a sub-graph into a single-line\n code, as well as keep track of the session/environment of each syntax\n construct (e.g., through `ContextManager`).\n \"\"\"\n ... | from _ast import AsyncFor, AsyncFunctionDef
import ast
from typing import Any, Tuple
from ..misc import IdentifierGenerator, get_params
from ..misc.types import VRet
def preprocess(program: str) -> Tuple[ast.AST, IdentifierGenerator]:
tree = ast.parse(program)
collector = InfoCollector()
collector.visit... |
return self.generic_visit(node)
def visit_FunctionDef(self, node: ast.FunctionDef) -> Any:
self.id_gen.add_used(node.name)
for name in get_params(node):
self.id_gen.add_used(name)
return self.generic_visit(node)
def visit_ClassDef(self, node: ast.ClassDef) ->... | {
"context_start_lineno": 0,
"file": "singleline/analysis/preprocessor.py",
"groundtruth_start_lineno": 35,
"repository": "davidmaamoaix-singleline-311d35f",
"right_context_start_lineno": 36,
"task_id": "project_cc_python/552"
} | {
"list": [
{
"filename": "singleline/transform/transpiler.py",
"retrieved_chunk": " \"\"\"\n Transpiles a code given a node in the CFG.\n \"\"\"\n assert node in self.graph\n ctx = ScopedExprManager()\n sep = get_all_convergence(self.graph, node, stop)\n ... | add_used(node.id) |
{
"list": [
{
"filename": "tests/test_lanczos/test_tridiagonal_full_reortho.py",
"retrieved_chunk": " offdiag1 = linalg.diagonal_matrix(e, 1)\n offdiag2 = linalg.diagonal_matrix(e, -1)\n return diag + offdiag1 + offdiag2",
"score": 77.2270938938557
},
{
"filename": "matfre... | """Stochastic Lanczos quadrature."""
from matfree import decomp, lanczos, montecarlo
from matfree.backend import func, linalg, np
def logdet_spd(*args, **kwargs):
"""Estimate the log-determinant of a symmetric, positive definite matrix."""
return trace_of_matfun_spd(np.log, *args, **kwargs)
def trace_of_ma... |
# Since Q orthogonal (orthonormal) to v0, Q v = Q[0],
# and therefore (Q v)^T f(D) (Qv) = Q[0] * f(diag) * Q[0]
(dim,) = v0.shape
fx_eigvals = func.vmap(matfun)(eigvals)
return dim * linalg.vecdot(eigvecs[0, :], fx_eigvals * eigvecs[0, :])
return quadform
def logdet_pro... | {
"context_start_lineno": 0,
"file": "matfree/slq.py",
"groundtruth_start_lineno": 35,
"repository": "pnkraemer-matfree-9b88279",
"right_context_start_lineno": 36,
"task_id": "project_cc_python/451"
} | {
"list": [
{
"filename": "tests/test_lanczos/test_tridiagonal_full_reortho.py",
"retrieved_chunk": " offdiag1 = linalg.diagonal_matrix(e, 1)\n offdiag2 = linalg.diagonal_matrix(e, -1)\n return diag + offdiag1 + offdiag2",
"score": 77.2270938938557
},
{
"filename": "matfre... | eigh(dense_matrix) |
{
"list": [
{
"filename": "test/test_cfg.py",
"retrieved_chunk": "foo()\n\"\"\"\nclass ControlFlowGraphTest(unittest.TestCase):\n def test_simple_linear(self):\n tree, id_gen = singleline.analysis.preprocess(SIMPLE_FUNC)\n singleline.analysis.control_flow_pass(tree)\n graph = t... | import ast
import unittest
from .context import singleline
SIMP_LOOP_MUT = """
a = 0
b = 3
while a < 20:
print(a)
a += 1
b = b * a + 1
print(f'End: {a} {b}')
"""
class MutatedVarTest(unittest.TestCase):
def test_simple_loop(self):
tree, id_gen = singleline. |
singleline.analysis.control_flow_pass(tree)
singleline.transform.init_loop_mutations(tree.body[2])
self.assertEqual(tree.body[2].mutated_vars, {'a', 'b'})
| {
"context_start_lineno": 0,
"file": "test/test_loop_analysis.py",
"groundtruth_start_lineno": 21,
"repository": "davidmaamoaix-singleline-311d35f",
"right_context_start_lineno": 22,
"task_id": "project_cc_python/550"
} | {
"list": [
{
"filename": "test/test_cfg.py",
"retrieved_chunk": " def test_complex_func(self):\n tree, id_gen = singleline.analysis.preprocess(COMPLEX_FUNC)\n singleline.analysis.control_flow_pass(tree)\n graph: nx.classes.DiGraph = tree.body[0].graph\n common = singlel... | analysis.preprocess(SIMP_LOOP_MUT) |
{
"list": [
{
"filename": "matfree/hutchinson.py",
"retrieved_chunk": " Matrix-vector product function.\n **kwargs:\n Keyword-arguments to be passed to\n [montecarlo.estimate()][matfree.montecarlo.estimate].\n \"\"\"\n def quadform(vec):\n return vec * Av(vec)\n ... | """Lanczos-style algorithms."""
from matfree.backend import containers, control_flow, linalg, np
from matfree.backend.typing import Array, Callable, Tuple
class _Alg(containers.NamedTuple):
"""Matrix decomposition algorithm."""
init: Callable
"""Initialise the state of the algorithm. Usually, this invol... |
vec, (coeff, _) = _gram_schmidt_orthogonalise_set(vec, basis_vectors_previous)
diag = diag.at[i].set(coeff)
offdiag = offdiag.at[i - 1].set(length)
return State(i + 1, basis, (diag, offdiag), vec)
def extract(state: State, /):
_, basis, (diag, offdiag), _ = state
r... | {
"context_start_lineno": 0,
"file": "matfree/lanczos.py",
"groundtruth_start_lineno": 71,
"repository": "pnkraemer-matfree-9b88279",
"right_context_start_lineno": 72,
"task_id": "project_cc_python/442"
} | {
"list": [
{
"filename": "matfree/hutchinson.py",
"retrieved_chunk": " ----------\n Av:\n Matrix-vector product function.\n moments:\n Which moments to compute. For example, selection `moments=(1,2)` computes\n the first and second moment.\n **kwargs:\n Keyword... | asarray([basis[i], basis[i - 1]]) |
{
"list": [
{
"filename": "test/test_cfg.py",
"retrieved_chunk": "foo()\n\"\"\"\nclass ControlFlowGraphTest(unittest.TestCase):\n def test_simple_linear(self):\n tree, id_gen = singleline.analysis.preprocess(SIMPLE_FUNC)\n singleline.analysis.control_flow_pass(tree)\n graph = t... | import ast
import unittest
from .context import singleline
SIMP_LOOP_MUT = """
a = 0
b = 3
while a < 20:
print(a)
a += 1
b = b * a + 1
print(f'End: {a} {b}')
"""
class MutatedVarTest(unittest.TestCase):
def test_simple_loop(self):
tree, id_gen = singleline.analysis.preprocess(SIMP_LOOP_MU... |
self.assertEqual(tree.body[2].mutated_vars, {'a', 'b'})
| {
"context_start_lineno": 0,
"file": "test/test_loop_analysis.py",
"groundtruth_start_lineno": 24,
"repository": "davidmaamoaix-singleline-311d35f",
"right_context_start_lineno": 25,
"task_id": "project_cc_python/551"
} | {
"list": [
{
"filename": "test/test_cfg.py",
"retrieved_chunk": " def test_complex_func(self):\n tree, id_gen = singleline.analysis.preprocess(COMPLEX_FUNC)\n singleline.analysis.control_flow_pass(tree)\n graph: nx.classes.DiGraph = tree.body[0].graph\n common = singlel... | transform.init_loop_mutations(tree.body[2]) |
{
"list": [
{
"filename": "test/test_loop_analysis.py",
"retrieved_chunk": "print(f'End: {a} {b}')\n\"\"\"\nclass MutatedVarTest(unittest.TestCase):\n def test_simple_loop(self):\n tree, id_gen = singleline.analysis.preprocess(SIMP_LOOP_MUT)\n singleline.analysis.control_flow_pass(tre... | import ast
import unittest
import networkx as nx
from .context import singleline
from .utils import plot_graph
SIMPLE_FUNC = """
a = int(input())
a = a + 1
if a == 2:
a += 2
elif a == 3:
assert 2 == 1, 'nope'
b = 3
print(a, b)
"""
COMPLEX_FUNC = """
def foo():
a = a + 1
if a == 2:
c = 2
... |
for i, ans in zip(common[-1].bundle, ['b=3', 'print(a,b)']):
self.assertEqual(ast.unparse(i).replace(' ', ''), ans)
def test_complex_func(self):
tree, id_gen = singleline.analysis.preprocess(COMPLEX_FUNC)
singleline.analysis.control_flow_pass(tree)
graph: nx.classes.Di... | {
"context_start_lineno": 0,
"file": "test/test_cfg.py",
"groundtruth_start_lineno": 47,
"repository": "davidmaamoaix-singleline-311d35f",
"right_context_start_lineno": 48,
"task_id": "project_cc_python/548"
} | {
"list": [
{
"filename": "test/test_loop_analysis.py",
"retrieved_chunk": "print(f'End: {a} {b}')\n\"\"\"\nclass MutatedVarTest(unittest.TestCase):\n def test_simple_loop(self):\n tree, id_gen = singleline.analysis.preprocess(SIMP_LOOP_MUT)\n singleline.analysis.control_flow_pass(tre... | misc.get_all_convergence(graph, tree) |
{
"list": [
{
"filename": "tests/test_lanczos/test_tridiagonal_full_reortho.py",
"retrieved_chunk": " v0 = prng.normal(key, shape=(n,))\n alg = lanczos.tridiagonal_full_reortho(order)\n Q, tridiag = decomp.decompose_fori_loop(v0, lambda v: A @ v, algorithm=alg)\n (d_m, e_m) = tridiag\n ... | """Stochastic Lanczos quadrature."""
from matfree import decomp, lanczos, montecarlo
from matfree.backend import func, linalg, np
def logdet_spd(*args, **kwargs):
"""Estimate the log-determinant of a symmetric, positive definite matrix."""
return trace_of_matfun_spd(np.log, *args, **kwargs)
def trace_of_ma... |
offdiag1 = linalg.diagonal_matrix(off_diag, -1)
offdiag2 = linalg.diagonal_matrix(off_diag, 1)
dense_matrix = diag + offdiag1 + offdiag2
eigvals, eigvecs = linalg.eigh(dense_matrix)
# Since Q orthogonal (orthonormal) to v0, Q v = Q[0],
# and therefore (Q v)^T f(D) (Qv) ... | {
"context_start_lineno": 0,
"file": "matfree/slq.py",
"groundtruth_start_lineno": 31,
"repository": "pnkraemer-matfree-9b88279",
"right_context_start_lineno": 32,
"task_id": "project_cc_python/450"
} | {
"list": [
{
"filename": "tests/test_lanczos/test_tridiagonal_full_reortho.py",
"retrieved_chunk": " QAQt = Q @ A @ Q.T\n assert np.shape(T) == (order + 1, order + 1)\n # Fail early if the (off)diagonals don't coincide\n assert np.allclose(linalg.diagonal(QAQt), d_m, **tols_decomp)\n a... | diagonal_matrix(diag) |
{
"list": [
{
"filename": "matfree/decomp.py",
"retrieved_chunk": " for _ in range(lower, upper):\n state = step(state, *matvec_funs)\n return extract(state)\n ```\n but the implementation uses JAX' fori_loop.\n \"\"\"\n # todo: turn the \"practically equivalent\" ... | """Lanczos-style algorithms."""
from matfree.backend import containers, control_flow, linalg, np
from matfree.backend.typing import Array, Callable, Tuple
class _Alg(containers.NamedTuple):
"""Matrix decomposition algorithm."""
init: Callable
"""Initialise the state of the algorithm. Usually, this invol... |
return vec / length, length
def _gram_schmidt_orthogonalise_set(vec, vectors): # Gram-Schmidt
vec, coeffs = control_flow.scan(_gram_schmidt_orthogonalise, vec, xs=vectors)
return vec, coeffs
def _gram_schmidt_orthogonalise(vec1, vec2):
coeff = linalg.vecdot(vec1, vec2)
vec_ortho = vec1 - coeff... | {
"context_start_lineno": 0,
"file": "matfree/lanczos.py",
"groundtruth_start_lineno": 148,
"repository": "pnkraemer-matfree-9b88279",
"right_context_start_lineno": 149,
"task_id": "project_cc_python/443"
} | {
"list": [
{
"filename": "matfree/decomp.py",
"retrieved_chunk": " return step(s, *matvec_funs)\n result = control_flow.fori_loop(lower, upper, body_fun=body_fun, init_val=init_val)\n return extract(result)",
"score": 49.72174156572452
},
{
"filename": "matfree/decomp... | vector_norm(vec) |
{
"list": [
{
"filename": "plugins/ping_plugin.py",
"retrieved_chunk": " if (\n \"decoded\" in packet\n and \"portnum\" in packet[\"decoded\"]\n and packet[\"decoded\"][\"portnum\"] == \"TEXT_MESSAGE_APP\"\n and \"text\" in packet[\"decoded\"]\n ... | import json
import io
import re
import matplotlib.pyplot as plt
from PIL import Image
from datetime import datetime, timedelta
from plugins.base_plugin import BasePlugin
class Plugin(BasePlugin):
plugin_name = "telemetry"
max_data_rows_per_node = 50
def commands(self):
return ["batteryLevel", "v... |
if data:
telemetry_data = data
packet_data = packet["decoded"]["telemetry"]
telemetry_data.append(
{
"time": packet_data["time"],
"batteryLevel": packet_data["deviceMetrics"]["batteryLevel"],
... | {
"context_start_lineno": 0,
"file": "plugins/telemetry_plugin.py",
"groundtruth_start_lineno": 45,
"repository": "geoffwhittington-meshtastic-matrix-relay-ffe969f",
"right_context_start_lineno": 46,
"task_id": "project_cc_python/571"
} | {
"list": [
{
"filename": "plugins/ping_plugin.py",
"retrieved_chunk": " from meshtastic_utils import connect_meshtastic\n meshtastic_client = connect_meshtastic()\n meshtastic_client.sendText(text=\"pong!\", destinationId=packet[\"fromId\"])\n return True\n... | get_node_data(meshtastic_id=packet["fromId"]) |
{
"list": [
{
"filename": "tests/test_decomp/test_svd.py",
"retrieved_chunk": " depth = min(nrows, ncols) - 1\n def Av(v):\n return A @ v\n def vA(v):\n return v @ A\n v0 = np.ones((ncols,))\n U, S, Vt = decomp.svd(v0, depth, Av, vA, matrix_shape=np.shape(A))\n U_, S_, ... | """Test utilities."""
from matfree.backend import linalg, np
def symmetric_matrix_from_eigenvalues(eigvals, /):
"""Generate a symmetric matrix with prescribed eigenvalues."""
assert np.array_min(eigvals) > 0
(n,) = eigvals.shape
# Need _some_ matrix to start with
A = np.reshape(np.arange(1.0, n*... | {
"context_start_lineno": 0,
"file": "matfree/test_util.py",
"groundtruth_start_lineno": 31,
"repository": "pnkraemer-matfree-9b88279",
"right_context_start_lineno": 32,
"task_id": "project_cc_python/438"
} | {
"list": [
{
"filename": "matfree/slq.py",
"retrieved_chunk": " fx_eigvals = func.vmap(matfun)(eigvals)\n return ncols * linalg.vecdot(eigvecs[0, :], fx_eigvals * eigvecs[0, :])\n return quadform\ndef _bidiagonal_dense(d, e):\n diag = linalg.diagonal_matrix(d)\n offdiag = linal... | diagonal(vals) @ Vt | |
{
"list": [
{
"filename": "tests/test_lanczos/test_tridiagonal_full_reortho.py",
"retrieved_chunk": " v0 = prng.normal(key, shape=(n,))\n alg = lanczos.tridiagonal_full_reortho(order)\n Q, tridiag = decomp.decompose_fori_loop(v0, lambda v: A @ v, algorithm=alg)\n (d_m, e_m) = tridiag\n ... | """Stochastic Lanczos quadrature."""
from matfree import decomp, lanczos, montecarlo
from matfree.backend import func, linalg, np
def logdet_spd(*args, **kwargs):
"""Estimate the log-determinant of a symmetric, positive definite matrix."""
return trace_of_matfun_spd(np.log, *args, **kwargs)
def trace_of_ma... |
(diag, off_diag) = tridiag
# todo: once jax supports eigh_tridiagonal(eigvals_only=False),
# use it here. Until then: an eigen-decomposition of size (order + 1)
# does not hurt too much...
diag = linalg.diagonal_matrix(diag)
offdiag1 = linalg.diagonal_matrix(off_diag,... | {
"context_start_lineno": 0,
"file": "matfree/slq.py",
"groundtruth_start_lineno": 25,
"repository": "pnkraemer-matfree-9b88279",
"right_context_start_lineno": 26,
"task_id": "project_cc_python/449"
} | {
"list": [
{
"filename": "matfree/hutchinson.py",
"retrieved_chunk": " ----------\n Av:\n Matrix-vector product function.\n moments:\n Which moments to compute. For example, selection `moments=(1,2)` computes\n the first and second moment.\n **kwargs:\n Keyword... | decompose_fori_loop(v0, Av, algorithm=algorithm) |
{
"list": [
{
"filename": "matfree/hutchinson.py",
"retrieved_chunk": " def quadform(vec):\n return linalg.vecdot(vec, Av(vec))\n def moment(x, axis, *, power):\n return np.mean(x**power, axis=axis)\n statistics_batch = [func.partial(moment, power=m) for m in moments]\n stati... | """Lanczos-style algorithms."""
from matfree.backend import containers, control_flow, linalg, np
from matfree.backend.typing import Array, Callable, Tuple
class _Alg(containers.NamedTuple):
"""Matrix decomposition algorithm."""
init: Callable
"""Initialise the state of the algorithm. Usually, this invol... |
vec_ortho = vec1 - coeff * vec2
return vec_ortho, coeff
| {
"context_start_lineno": 0,
"file": "matfree/lanczos.py",
"groundtruth_start_lineno": 158,
"repository": "pnkraemer-matfree-9b88279",
"right_context_start_lineno": 159,
"task_id": "project_cc_python/445"
} | {
"list": [
{
"filename": "matfree/hutchinson.py",
"retrieved_chunk": " **kwargs,\n )\ndef frobeniusnorm_squared(Av: Callable, /, **kwargs) -> Array:\n r\"\"\"Estimate the squared Frobenius norm of a matrix stochastically.\n The Frobenius norm of a matrix $A$ is defined as\n $$\n ... | vecdot(vec1, vec2) |
{
"list": [
{
"filename": "examples/constraints.py",
"retrieved_chunk": " # random choices, as it will only be executed\n # one time, before inference begins.\n def __init__(self, prompt, can_follow):\n super().__init__()\n self.context = self.new_context(prompt)\n self.c... | import llamppl as llp
import numpy as np
class Infilling(llp.Model):
def __init__(self, words):
super().__init__()
self.s = words.pop(0)
self.ctx = self.new_context(self.s)
self.remaining_segments = [self.llama.tokenize(w) for w in words]
def start(self):
self.step(... |
# Observe the next tokens
for token in self.remaining_segments.pop(0):
self.s += self.observe(llp.Transformer(self.ctx), token)
# Check if done
if len(self.remaining_segments) == 0:
self.observe(llp.Transformer(self.ctx), llp.EOS)
self.finish()
# Cre... | {
"context_start_lineno": 0,
"file": "examples/infilling.py",
"groundtruth_start_lineno": 17,
"repository": "probcomp-LLaMPPL-56ef219",
"right_context_start_lineno": 18,
"task_id": "project_cc_python/567"
} | {
"list": [
{
"filename": "examples/constraints.py",
"retrieved_chunk": " # random choices, as it will only be executed\n # one time, before inference begins.\n def __init__(self, prompt, can_follow):\n super().__init__()\n self.context = self.new_context(prompt)\n self.c... | Transformer(self.ctx)) |
{
"list": [
{
"filename": "tests/test_lanczos/test_tridiagonal_full_reortho.py",
"retrieved_chunk": " offdiag1 = linalg.diagonal_matrix(e, 1)\n offdiag2 = linalg.diagonal_matrix(e, -1)\n return diag + offdiag1 + offdiag2",
"score": 76.48263416252263
},
{
"filename": "matfr... | """Stochastic Lanczos quadrature."""
from matfree import decomp, lanczos, montecarlo
from matfree.backend import func, linalg, np
def logdet_spd(*args, **kwargs):
"""Estimate the log-determinant of a symmetric, positive definite matrix."""
return trace_of_matfun_spd(np.log, *args, **kwargs)
def trace_of_ma... |
return dim * linalg.vecdot(eigvecs[0, :], fx_eigvals * eigvecs[0, :])
return quadform
def logdet_product(*args, **kwargs):
r"""Compute the log-determinant of a product of matrices.
Here, "product" refers to $X = A^\top A$.
"""
return trace_of_matfun_product(np.log, *args, **kwargs)
de... | {
"context_start_lineno": 0,
"file": "matfree/slq.py",
"groundtruth_start_lineno": 41,
"repository": "pnkraemer-matfree-9b88279",
"right_context_start_lineno": 42,
"task_id": "project_cc_python/452"
} | {
"list": [
{
"filename": "tests/test_lanczos/test_tridiagonal_full_reortho.py",
"retrieved_chunk": " offdiag1 = linalg.diagonal_matrix(e, 1)\n offdiag2 = linalg.diagonal_matrix(e, -1)\n return diag + offdiag1 + offdiag2",
"score": 76.48263416252263
},
{
"filename": "matfr... | vmap(matfun)(eigvals) |
{
"list": [
{
"filename": "matfree/hutchinson.py",
"retrieved_chunk": " init: Array,\n /,\n *,\n key: Array,\n sample_fun: Callable,\n num_levels: int,\n num_batches_per_level: int = 1,\n num_samples_per_batch: int = 1,\n) -> Array:\n \"\"\"Estimate the diagonal in a multile... | """Lanczos-style algorithms."""
from matfree.backend import containers, control_flow, linalg, np
from matfree.backend.typing import Array, Callable, Tuple
class _Alg(containers.NamedTuple):
"""Matrix decomposition algorithm."""
init: Callable
"""Initialise the state of the algorithm. Usually, this invol... |
offdiag = np.zeros((depth,))
basis = np.zeros((depth + 1, ncols))
return State(0, basis, (diag, offdiag), init_vec)
def apply(state: State, Av: Callable) -> State:
i, basis, (diag, offdiag), vec = state
# Re-orthogonalise against ALL basis elements before storing.
... | {
"context_start_lineno": 0,
"file": "matfree/lanczos.py",
"groundtruth_start_lineno": 45,
"repository": "pnkraemer-matfree-9b88279",
"right_context_start_lineno": 46,
"task_id": "project_cc_python/441"
} | {
"list": [
{
"filename": "matfree/hutchinson.py",
"retrieved_chunk": " The general idea is that a diagonal estimate serves as a control variate\n for the next step's diagonal estimate.\n Parameters\n ----------\n Av:\n Matrix-vector product function.\n init:\n Initial ... | zeros((depth + 1,)) |
{
"list": [
{
"filename": "examples/constraints.py",
"retrieved_chunk": " logits = self.context.logits()\n # Compute locally optimal proposal\n mask = np.array([0.0 if self.can_follow(self.s, v) else float('-inf') for v in self.vocab()])\n q_logprobs = llp.lognormalize(logi... | import llamppl as llp
import numpy as np
class Infilling(llp.Model):
def __init__(self, words):
super().__init__()
self.s = words.pop(0)
self.ctx = self.new_context(self.s)
self.remaining_segments = [self.llama.tokenize(w) for w in words]
def start(self):
self.step(... |
print(f"Particle {i}: {p} (weight {p.weight})")
| {
"context_start_lineno": 0,
"file": "examples/infilling.py",
"groundtruth_start_lineno": 30,
"repository": "probcomp-LLaMPPL-56ef219",
"right_context_start_lineno": 31,
"task_id": "project_cc_python/570"
} | {
"list": [
{
"filename": "examples/constraints.py",
"retrieved_chunk": " print(f\"Particle {i}: {p} (weight {p.weight})\")",
"score": 59.13714686005883
},
{
"filename": "examples/prompt_intersection.py",
"retrieved_chunk": "prompts = [\" My favorite writer is probably\", ... | smc_steer(model, 4,4)): |
{
"list": [
{
"filename": "tests/test_lanczos/test_tridiagonal_full_reortho.py",
"retrieved_chunk": " offdiag1 = linalg.diagonal_matrix(e, 1)\n offdiag2 = linalg.diagonal_matrix(e, -1)\n return diag + offdiag1 + offdiag2",
"score": 63.071489210478475
},
{
"filename": "matf... | """Stochastic Lanczos quadrature."""
from matfree import decomp, lanczos, montecarlo
from matfree.backend import func, linalg, np
def logdet_spd(*args, **kwargs):
"""Estimate the log-determinant of a symmetric, positive definite matrix."""
return trace_of_matfun_spd(np.log, *args, **kwargs)
def trace_of_ma... |
return quadform
def logdet_product(*args, **kwargs):
r"""Compute the log-determinant of a product of matrices.
Here, "product" refers to $X = A^\top A$.
"""
return trace_of_matfun_product(np.log, *args, **kwargs)
def schatten_norm(*args, power, **kwargs):
r"""Compute the Schatten-p norm o... | {
"context_start_lineno": 0,
"file": "matfree/slq.py",
"groundtruth_start_lineno": 42,
"repository": "pnkraemer-matfree-9b88279",
"right_context_start_lineno": 43,
"task_id": "project_cc_python/453"
} | {
"list": [
{
"filename": "tests/test_lanczos/test_tridiagonal_full_reortho.py",
"retrieved_chunk": " offdiag1 = linalg.diagonal_matrix(e, 1)\n offdiag2 = linalg.diagonal_matrix(e, -1)\n return diag + offdiag1 + offdiag2",
"score": 78.2840654860067
},
{
"filename": "matfre... | vecdot(eigvecs[0, :], fx_eigvals * eigvecs[0, :]) |
{
"list": [
{
"filename": "plugins/nodes_plugin.py",
"retrieved_chunk": " snr = f\"{info['snr']} dB\"\n else:\n snr = \"\"\n voltage = \"?V\"\n battery = \"?%\"\n if \"deviceMetrics\" in info:\n if \"voltage\" in ... | import json
import io
import re
import matplotlib.pyplot as plt
from PIL import Image
from datetime import datetime, timedelta
from plugins.base_plugin import BasePlugin
class Plugin(BasePlugin):
plugin_name = "telemetry"
max_data_rows_per_node = 50
def commands(self):
return ["batteryLevel", "v... |
return False
def get_matrix_commands(self):
return ["batteryLevel", "voltage", "airUtilTx"]
def get_mesh_commands(self):
return []
def matches(self, payload):
from matrix_utils import bot_command
if type(payload) == str:
for option in ["batteryLev... | {
"context_start_lineno": 0,
"file": "plugins/telemetry_plugin.py",
"groundtruth_start_lineno": 58,
"repository": "geoffwhittington-meshtastic-matrix-relay-ffe969f",
"right_context_start_lineno": 59,
"task_id": "project_cc_python/572"
} | {
"list": [
{
"filename": "plugins/nodes_plugin.py",
"retrieved_chunk": " response += f\"{info['user']['shortName']} {info['user']['longName']} / {info['user']['hwModel']} / {battery} {voltage} / {snr} / {get_relative_time(info['lastHeard'])}\\n\"\n return response\n async def han... | set_node_data(meshtastic_id=packet["fromId"], node_data=telemetry_data) |
{
"list": [
{
"filename": "gui/config_editor.py",
"retrieved_chunk": "matrix_frame.pack(padx=10, pady=10, fill=\"x\", expand=\"yes\")\nmatrix_keys = [\"homeserver\", \"bot_user_id\", \"access_token\"]\nmatrix_vars = {}\nfor i, key in enumerate(matrix_keys):\n label = tk.Label(matrix_frame, text=key... | import json
import io
import re
import matplotlib.pyplot as plt
from PIL import Image
from datetime import datetime, timedelta
from plugins.base_plugin import BasePlugin
class Plugin(BasePlugin):
plugin_name = "telemetry"
max_data_rows_per_node = 50
def commands(self):
return ["batteryLevel", "v... |
node_data_rows = json.loads(node_data_json[0])
calculate_averages(node_data_rows)
# Compute the final hourly averages
final_averages = {}
for i, interval in enumerate(hourly_intervals[:-1]):
if i in hourly_averages:
final_averages[int... | {
"context_start_lineno": 0,
"file": "plugins/telemetry_plugin.py",
"groundtruth_start_lineno": 117,
"repository": "geoffwhittington-meshtastic-matrix-relay-ffe969f",
"right_context_start_lineno": 118,
"task_id": "project_cc_python/573"
} | {
"list": [
{
"filename": "gui/config_editor.py",
"retrieved_chunk": "# Add instruction label\ninstruction_label = tk.Label(matrix_frame, text=\"For instructions on where to find your access token, visit:\")\ninstruction_label.grid(row=3, column=0, columnspan=2, sticky=\"ew\")\n# Add hyperlink label\n... | get_data(): |
{
"list": [
{
"filename": "plugin_loader.py",
"retrieved_chunk": " for plugin in plugins:\n if plugin.config[\"active\"]:\n plugin.priority = (\n plugin.config[\"priority\"]\n if \"priority\" in plugin.config\n else plugin.priority\n ... | import re
from plugins.base_plugin import BasePlugin
from plugin_loader import load_plugins
class Plugin(BasePlugin):
plugin_name = "help"
@property
def description(self):
return f"List supported relay commands"
async def handle_meshtastic_message(
self, packet, formatted_message, l... |
return True
| {
"context_start_lineno": 0,
"file": "plugins/help_plugin.py",
"groundtruth_start_lineno": 49,
"repository": "geoffwhittington-meshtastic-matrix-relay-ffe969f",
"right_context_start_lineno": 50,
"task_id": "project_cc_python/577"
} | {
"list": [
{
"filename": "plugin_loader.py",
"retrieved_chunk": " return sorted_active_plugins",
"score": 37.007015241988
},
{
"filename": "matrix_utils.py",
"retrieved_chunk": " meshtastic_logger.info(\n f\"Relaying message from {full_display_na... | send_matrix_message(room.room_id, reply) |
{
"list": [
{
"filename": "examples/constraints.py",
"retrieved_chunk": " return True\n if len(str_so_far) == 0:\n return True # First token, can be alphanumeric\n words = str_so_far.split()\n if len(words) >= 1 and len(words[-1]) + len(s) <= 5:\n return True\n else:\n... | import llamppl as llp
import numpy as np
class Infilling(llp.Model):
def __init__(self, words):
super().__init__()
self.s = words.pop(0)
self.ctx = self.new_context(self.s)
self.remaining_segments = [self.llama.tokenize(w) for w in words]
def start(self):
self.step(... |
for _ in range(n):
self.s += self.sample(llp.Transformer(self.ctx))
# Observe the next tokens
for token in self.remaining_segments.pop(0):
self.s += self.observe(llp.Transformer(self.ctx), token)
# Check if done
if len(self.remaining_segments) == 0:
... | {
"context_start_lineno": 0,
"file": "examples/infilling.py",
"groundtruth_start_lineno": 15,
"repository": "probcomp-LLaMPPL-56ef219",
"right_context_start_lineno": 16,
"task_id": "project_cc_python/566"
} | {
"list": [
{
"filename": "examples/constraints.py",
"retrieved_chunk": " # Condition on constraint\n self.condition(self.can_follow(self.s, token))\n # Check if done\n if token == llp.EOS:\n self.finish()\n return\n # Update generated string\n ... | Geometric(0.5)) + 1 |
{
"list": [
{
"filename": "matfree/backend/control_flow.py",
"retrieved_chunk": "def fori_loop(lower, upper, body_fun, init_val):\n return jax.lax.fori_loop(lower, upper, body_fun, init_val)\ndef while_loop(cond_fun, body_fun, init_val):\n return jax.lax.while_loop(cond_fun, body_fun, init_val)\... | """Matrix decomposition algorithms."""
from matfree import lanczos
from matfree.backend import containers, control_flow, linalg
from matfree.backend.typing import Array, Callable, Tuple
def svd(
v0: Array, depth: int, Av: Callable, vA: Callable, matrix_shape: Tuple[int, ...]
):
"""Approximate singular value ... |
return extract(result)
| {
"context_start_lineno": 0,
"file": "matfree/decomp.py",
"groundtruth_start_lineno": 96,
"repository": "pnkraemer-matfree-9b88279",
"right_context_start_lineno": 97,
"task_id": "project_cc_python/460"
} | {
"list": [
{
"filename": "matfree/backend/control_flow.py",
"retrieved_chunk": "def fori_loop(lower, upper, body_fun, init_val):\n return jax.lax.fori_loop(lower, upper, body_fun, init_val)\ndef while_loop(cond_fun, body_fun, init_val):\n return jax.lax.while_loop(cond_fun, body_fun, init_val)\... | fori_loop(lower, upper, body_fun=body_fun, init_val=init_val) |
{
"list": [
{
"filename": "matfree/decomp.py",
"retrieved_chunk": " for _ in range(lower, upper):\n state = step(state, *matvec_funs)\n return extract(state)\n ```\n but the implementation uses JAX' fori_loop.\n \"\"\"\n # todo: turn the \"practically equivalent\" ... | """Lanczos-style algorithms."""
from matfree.backend import containers, control_flow, linalg, np
from matfree.backend.typing import Array, Callable, Tuple
class _Alg(containers.NamedTuple):
"""Matrix decomposition algorithm."""
init: Callable
"""Initialise the state of the algorithm. Usually, this invol... |
return vec, coeffs
def _gram_schmidt_orthogonalise(vec1, vec2):
coeff = linalg.vecdot(vec1, vec2)
vec_ortho = vec1 - coeff * vec2
return vec_ortho, coeff
| {
"context_start_lineno": 0,
"file": "matfree/lanczos.py",
"groundtruth_start_lineno": 153,
"repository": "pnkraemer-matfree-9b88279",
"right_context_start_lineno": 154,
"task_id": "project_cc_python/444"
} | {
"list": [
{
"filename": "matfree/decomp.py",
"retrieved_chunk": " return step(s, *matvec_funs)\n result = control_flow.fori_loop(lower, upper, body_fun=body_fun, init_val=init_val)\n return extract(result)",
"score": 45.52473916311069
},
{
"filename": "matfree/hutchi... | scan(_gram_schmidt_orthogonalise, vec, xs=vectors) |
{
"list": [
{
"filename": "llamppl/context.py",
"retrieved_chunk": " self.llama.reset()\n self.trie = self.llama.trie\n self.current_index = 1\n self.current_mask = [0.0]\n self.kv_index = 0\n def extend_mask(self):\n if self.kv_index < self.llama.kv_index:... | from .context import ActiveLLaMA, LLaMAContext
class Model:
def __init__(self):
self.weight = 0.0
self.finished = False
self.llama = ActiveLLaMA()
self.mode = "sample"
self.beam_idx = 0
self.force_eos = False
self.s = ""
def reset(self):
self.wei... |
return ctx
def finish(self):
self.finished = True
def done_stepping(self):
return self.finished
def step(self):
if not self.done_stepping():
raise NotImplementedError("Model.step() must be implemented by subclasses")
def __str__(self):
ret... | {
"context_start_lineno": 0,
"file": "llamppl/model.py",
"groundtruth_start_lineno": 24,
"repository": "probcomp-LLaMPPL-56ef219",
"right_context_start_lineno": 25,
"task_id": "project_cc_python/563"
} | {
"list": [
{
"filename": "llamppl/context.py",
"retrieved_chunk": " self.llama.reset()\n self.trie = self.llama.trie\n self.current_index = 1\n self.current_mask = [0.0]\n self.kv_index = 0\n def extend_mask(self):\n if self.kv_index < self.llama.kv_index:... | prompt(prompt) |
{
"list": [
{
"filename": "plugins/base_plugin.py",
"retrieved_chunk": " self.logger.debug(f\"Scheduled with priority={self.priority}\")\n def background_job(self):\n pass\n def strip_raw(self, data):\n if type(data) is not dict:\n return data\n if \"raw\" ... | import json
import io
import re
import base64
import json
from typing import List
from meshtastic import mesh_pb2
from plugins.base_plugin import BasePlugin
from config import relay_config
matrix_rooms: List[dict] = relay_config["matrix_rooms"]
class Plugin(BasePlugin):
plugin_name = "mesh_relay"
max_data_r... |
def process(self, packet):
packet = self.normalize(packet)
if "decoded" in packet and "payload" in packet["decoded"]:
if type(packet["decoded"]["payload"]) is bytes:
text = packet["decoded"]["payload"]
packet["decoded"]["payload"] = base64.b64encode(
... | {
"context_start_lineno": 0,
"file": "plugins/mesh_relay_plugin.py",
"groundtruth_start_lineno": 28,
"repository": "geoffwhittington-meshtastic-matrix-relay-ffe969f",
"right_context_start_lineno": 29,
"task_id": "project_cc_python/578"
} | {
"list": [
{
"filename": "plugins/base_plugin.py",
"retrieved_chunk": " return data\n def get_matrix_commands(self):\n return [self.plugin_name]\n async def send_matrix_message(self, room_id, message, formatted=True):\n from matrix_utils import connect_matrix\n matri... | strip_raw(dict_obj) |
{
"list": [
{
"filename": "code/JDDB/jddb/processor/basic_processors/normalization_processor.py",
"retrieved_chunk": "from .. import BaseProcessor, Signal\nimport numpy as np\nclass NormalizationProcessor(BaseProcessor):\n def __init__(self, std: float, mean: float):\n super().__init__()\n ... | from .. import BaseProcessor, Signal
from copy import deepcopy
import numpy as np
class ClipProcessor(BaseProcessor):
def __init__(self, start_time: float, end_time: float = None, end_time_label: str = None):
super().__init__()
self._start_time = start_time
self._end_time_label = end_time_... |
if self._end_time is None:
self._end_time = signal.time[-1]
if self._start_time > self._end_time:
raise ValueError('Down time is earlier than start time.')
clipped_data = signal.data[(self._start_time <= signal.time) & (signal.time <= self._end_time)]
clipped_att... | {
"context_start_lineno": 0,
"file": "code/JDDB/jddb/processor/basic_processors/clip_processor.py",
"groundtruth_start_lineno": 22,
"repository": "jtext-103-jddb-077b729",
"right_context_start_lineno": 23,
"task_id": "project_cc_python/521"
} | {
"list": [
{
"filename": "code/JDDB/jddb/processor/basic_processors/normalization_processor.py",
"retrieved_chunk": " Note:\n The result of the normalized to signal will be clipped to [-10, 10] if beyond the range.\n Args:\n signal: The signal to be normalized.\n ... | params[self._end_time_label] |
{
"list": [
{
"filename": "plugins/telemetry_plugin.py",
"retrieved_chunk": " return False\n telemetry_option = match.group(1)\n node = match.group(2)\n hourly_intervals = self._generate_timeperiods()\n from matrix_utils import connect_matrix\n matrix_clie... | import staticmaps
import s2sphere
import math
import random
import io
import re
from PIL import Image
from nio import AsyncClient, UploadResponse
from plugins.base_plugin import BasePlugin
class TextLabel(staticmaps.Object):
def __init__(self, latlng: s2sphere.LatLng, text: str, fontSize: int = 12) -> None:
... |
if zoom < 0 or zoom > 30:
zoom = 8
try:
image_size = (int(image_size[0]), int(image_size[1]))
except:
image_size = (
self.config["image_width"] if "image_width" in self.config else 1000,
self.config["image_height"] if "image_... | {
"context_start_lineno": 0,
"file": "plugins/map_plugin.py",
"groundtruth_start_lineno": 261,
"repository": "geoffwhittington-meshtastic-matrix-relay-ffe969f",
"right_context_start_lineno": 262,
"task_id": "project_cc_python/581"
} | {
"list": [
{
"filename": "plugins/help_plugin.py",
"retrieved_chunk": " else:\n commands = []\n for plugin in plugins:\n commands.extend(plugin.get_matrix_commands())\n reply = \"Available commands: \" + \", \".join(commands)\n response = ... | config["zoom"] if "zoom" in self.config else 8 |
{
"list": [
{
"filename": "plugins/help_plugin.py",
"retrieved_chunk": " ):\n return False\n def get_matrix_commands(self):\n return [self.plugin_name]\n def get_mesh_commands(self):\n return []\n async def handle_room_message(self, room, event, full_message):\n ... | import re
from plugins.base_plugin import BasePlugin
class Plugin(BasePlugin):
plugin_name = "ping"
@property
def description(self):
return f"Check connectivity with the relay"
async def handle_meshtastic_message(
self, packet, formatted_message, longname, meshnet_name
):
... |
return True
| {
"context_start_lineno": 0,
"file": "plugins/ping_plugin.py",
"groundtruth_start_lineno": 43,
"repository": "geoffwhittington-meshtastic-matrix-relay-ffe969f",
"right_context_start_lineno": 44,
"task_id": "project_cc_python/583"
} | {
"list": [
{
"filename": "plugins/help_plugin.py",
"retrieved_chunk": " command = None\n match = re.match(r\"^.*: !help\\s+(.+)$\", full_message)\n if match:\n command = match.group(1)\n plugins = load_plugins()\n if command:\n reply = f\"No su... | send_matrix_message(room.room_id, "pong!") |
{
"list": [
{
"filename": "src/experiments/check_psnr.py",
"retrieved_chunk": "Over 60 means there was little loss in the conversion process.\n\"\"\"\nall_names = GPT2.model_names() + Pythia.model_names()\nparser = argparse.ArgumentParser(description='Load a CoreML modelpackage and generate some text.... | from src.ml_ane_transformers.ane_gpt2 import GPT as AneGPT
from src.utils.model_proxy import MLModelProxy
from transformers import AutoTokenizer
import torch
import torch.nn.functional as F
import numpy as np
import coremltools as ct
from stopwatch import Stopwatch
from models.gpt2 import GPT as GPT2
from models.pythia... |
for n in sorted(names, key=len):
if model_path.startswith(n):
return tokenizer_lookup[n]
print(f"No tokenizer found for {model_path}")
print(f"Model name must start with one of:")
print(names)
return None
tokenizer_name = get_tokenizer_name(args.model_path)
if tokenizer_name is... | {
"context_start_lineno": 0,
"file": "generate.py",
"groundtruth_start_lineno": 62,
"repository": "smpanaro-more-ane-transformers-d5aec6f",
"right_context_start_lineno": 63,
"task_id": "project_cc_python/529"
} | {
"list": [
{
"filename": "src/experiments/diff_chunked_models.py",
"retrieved_chunk": "# if os.path.exists(pipeline_path.replace('.mlpackage', '.mlmodelc')):\n# pipeline_path = pipeline_path.replace('.mlpackage', '.mlmodelc')\n# if os.path.exists(model_path.replace('.mlpackage', '.mlmodelc')):\n#... | tokenizer_by_name(), **Pythia.tokenizer_by_name()} |
{
"list": [
{
"filename": "tap_titans/utils/base.py",
"retrieved_chunk": " # This is so jank, but it seems Enums do not convert to json unless passed through pydantics json encoder\n # Pydantics json encoder also seems to be a lambda x: x, so I really don't know what is going on\n ... | import json
from aiohttp.test_utils import TestCase
from tap_titans.models import models
class ModelTest(TestCase):
def test_raid_unsub_clan(self):
models.ClanRemoved(**json.loads(_clan_unsub))
def test_raid_attack(self):
models.RaidAttack(**json.loads(_raid_attack))
# Waiting for an a... |
def test_raid_target(self):
models.RaidTarget(**json.loads(_raid_target))
_clan_unsub = '''{
"clan_code": "string",
"namespace": "string",
"token": "b5507016-7da2-4777-a161-1e8042a6a377"
}'''
_raid_attack = '''{"attack_log": {"attack_datetime": "2023-06-25T12:04:20Z", "cards_damage": [
... | {
"context_start_lineno": 0,
"file": "tap_titans/tests/models.py",
"groundtruth_start_lineno": 31,
"repository": "SilicalNZ-TapTitans2py-0d5409d",
"right_context_start_lineno": 32,
"task_id": "project_cc_python/599"
} | {
"list": [
{
"filename": "tap_titans/utils/base.py",
"retrieved_chunk": " # This is so jank, but it seems Enums do not convert to json unless passed through pydantics json encoder\n # Pydantics json encoder also seems to be a lambda x: x, so I really don't know what is going on\n ... | ClanAddedRaidCycleReset(**json.loads(_sub_cycle)) |
{
"list": [
{
"filename": "models/gpt2.py",
"retrieved_chunk": " logits = logits[:, -1, :] / temperature\n # optionally crop the logits to only the top k options\n if top_k is not None:\n v, _ = torch.topk(logits, min(top_k, logits.size(-1)))\n ... | from src.ml_ane_transformers.ane_gpt2 import GPT as AneGPT
from src.utils.model_proxy import MLModelProxy
from transformers import AutoTokenizer
import torch
import torch.nn.functional as F
import numpy as np
import coremltools as ct
from stopwatch import Stopwatch
from models.gpt2 import GPT as GPT2
from models.pythia... |
vprint("Generated initial inputs:")
vprint({k: v.shape for k,v in ane_inputs.items()})
vprint({k: v.dtype for k,v in ane_inputs.items()})
# vprint({k: v.__class__ for k,v in ane_inputs.items()})
def get_start_idx(ids):
ids = ids.tolist()[0]
if tok.pad_token_id in ids:
return ids.index(tok.pad_token_id... | {
"context_start_lineno": 0,
"file": "generate.py",
"groundtruth_start_lineno": 140,
"repository": "smpanaro-more-ane-transformers-d5aec6f",
"right_context_start_lineno": 141,
"task_id": "project_cc_python/531"
} | {
"list": [
{
"filename": "models/gpt2.py",
"retrieved_chunk": " idx = torch.cat((idx, idx_next), dim=1)\n return idx\nif __name__ == \"__main__\":\n import numpy as np\n def build_kv_mask(output_mask, seqlen=512, hidden_size=768):\n kv_mask = torch.ones(1, seqlen, hidde... | build_inputs(inputs['input_ids'], pad_to_length=512, pad_token_id=tok.pad_token_id) |
{
"list": [
{
"filename": "tap_titans/utils/base.py",
"retrieved_chunk": " # This is so jank, but it seems Enums do not convert to json unless passed through pydantics json encoder\n # Pydantics json encoder also seems to be a lambda x: x, so I really don't know what is going on\n ... | import json
from aiohttp.test_utils import TestCase
from tap_titans.models import models
class ModelTest(TestCase):
def test_raid_unsub_clan(self):
models.ClanRemoved(**json.loads(_clan_unsub))
def test_raid_attack(self):
models.RaidAttack(**json.loads(_raid_attack))
# Waiting for an a... |
def test_raid_end(self):
models.RaidEnd(**json.loads(_raid_end))
def test_raid_retire(self):
models.RaidRetire(**json.loads(_raid_retire))
def test_raid_cycle_reset(self):
models.RaidCycleReset(**json.loads(_raid_cycle_reset))
def test_raid_sub_cycle(self):
models.Cl... | {
"context_start_lineno": 0,
"file": "tap_titans/tests/models.py",
"groundtruth_start_lineno": 19,
"repository": "SilicalNZ-TapTitans2py-0d5409d",
"right_context_start_lineno": 20,
"task_id": "project_cc_python/595"
} | {
"list": [
{
"filename": "tap_titans/utils/base.py",
"retrieved_chunk": " # This is so jank, but it seems Enums do not convert to json unless passed through pydantics json encoder\n # Pydantics json encoder also seems to be a lambda x: x, so I really don't know what is going on\n ... | RaidStart(**json.loads(_raid_sub_start)) |
{
"list": [
{
"filename": "src/ml_ane_transformers/ane/kahan_layer_norm.py",
"retrieved_chunk": " # print(\"kahan mean\", s / inputs.size(1))\n return (s / inputs.size(1)) + (c / inputs.size(1))\n @staticmethod\n def stable_mean(inputs, size: int = 4):\n assert inputs.size(1... | import torch
from torch import nn
import numpy as np
from src.ml_ane_transformers.ane.layer_norm import LayerNormANE as LayerNorm
from src.ml_ane_transformers.ane.kahan_layer_norm import KahanLayerNormANE as KahanLayerNorm
import coremltools as ct
from src.utils.psnr import compute_psnr
from coremltools.converters.mil ... |
hm = x.to("mps").half().mean(dim=1, keepdim=True).float().cpu()
m = x.to("mps").float().mean(dim=1, keepdim=True).float().cpu()
dm = x.double().mean(dim=1, keepdim=True)
print("mean vs kahan mean half\n----")
print_stats(m, km)
print_stats(m, hm)
# print("kahan", km)
# print("exactly:", m)
with torch.no_... | {
"context_start_lineno": 0,
"file": "src/experiments/kahan_layer_norm.py",
"groundtruth_start_lineno": 49,
"repository": "smpanaro-more-ane-transformers-d5aec6f",
"right_context_start_lineno": 50,
"task_id": "project_cc_python/533"
} | {
"list": [
{
"filename": "src/ml_ane_transformers/ane/kahan_layer_norm.py",
"retrieved_chunk": " # print(\"stable mean\", m)\n return m\n def forward(self, inputs):\n input_rank = len(inputs.size())\n # Principle 1: Picking the Right Data Format (machinelearning.apple.c... | kahan_mean(x.to("mps").half(), 4).float().cpu() |
{
"list": [
{
"filename": "tests/model/test_collection_model.py",
"retrieved_chunk": "Session = sessionmaker(bind=engine)\nclass TestCollectionModel(unittest.TestCase):\n def setUp(self):\n Base.metadata.create_all(engine)\n self.session = Session()\n def tearDown(self):\n s... | # -*- coding: utf-8 -*-
# embedin - A vector database that empowers AI with persistent memory,
# (C) 2023 EmbedInAI
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.o... |
self.assertEqual(len(self.session.query(EmbeddingModel).all()), 2)
self.assertEqual(
self.session.query(EmbeddingModel).filter_by(id="id1").first().text,
"some text",
)
self.assertEqual(
self.session.query(EmbeddingModel).filter_by(id="id2").first().... | {
"context_start_lineno": 0,
"file": "tests/repository/test_embedding_repository.py",
"groundtruth_start_lineno": 66,
"repository": "EmbedInAI-EmbedInDB-b2d7852",
"right_context_start_lineno": 67,
"task_id": "project_cc_python/611"
} | {
"list": [
{
"filename": "tests/model/test_collection_model.py",
"retrieved_chunk": " # Create a new collection\n collection = CollectionModel(id=\"1\", name=\"test\")\n self.session.add(collection)\n self.session.commit()\n # Retrieve the collection from the databa... | _add_rows_one_by_one(self.embeddings) |
{
"list": [
{
"filename": "tests/model/test_embedding_model.py",
"retrieved_chunk": " Base.metadata.drop_all(engine)\n def test_embedding_model(self):\n embedding = self.session.query(EmbeddingModel).first()\n self.assertIsNotNone(embedding)\n self.assertEqual(embedding.... | # -*- coding: utf-8 -*-
# embedin - A vector database that empowers AI with persistent memory,
# (C) 2023 EmbedInAI
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.o... |
# Test adding duplicate embeddings
duplicate_embeddings = [
EmbeddingModel(
id="id3",
collection_id="collection1",
text="some text",
embedding_data=[1.0, 2.0, 3.0],
meta_data={"key1": "value1"},
... | {
"context_start_lineno": 0,
"file": "tests/repository/test_embedding_repository.py",
"groundtruth_start_lineno": 79,
"repository": "EmbedInAI-EmbedInDB-b2d7852",
"right_context_start_lineno": 80,
"task_id": "project_cc_python/612"
} | {
"list": [
{
"filename": "tests/model/test_embedding_model.py",
"retrieved_chunk": " self.assertIsInstance(embedding.created_at, datetime)\n # Try to add another embedding model with the same hash (should fail due to unique constraint)\n duplicate_embedding = EmbeddingModel(\n ... | add_all(self.embeddings_dict) |
{
"list": [
{
"filename": "embedin/repository/collection_repository.py",
"retrieved_chunk": " Returns:\n --------\n collection: dict\n The collection with the given name,\n \"\"\"\n collection = self.session.query(CollectionModel).filter_by(name=name).firs... | # -*- coding: utf-8 -*-
# embedin - A vector database that empowers AI with persistent memory,
# (C) 2023 EmbedInAI
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.o... |
# Verify that the query was executed with the correct arguments
self.session_mock.query.assert_called_once_with(CollectionModel)
self.session_mock.query.return_value.filter_by.assert_called_once_with(
name="test_collection"
)
self.session_mock.query.return_value.fil... | {
"context_start_lineno": 0,
"file": "tests/repository/test_collection_repository.py",
"groundtruth_start_lineno": 37,
"repository": "EmbedInAI-EmbedInDB-b2d7852",
"right_context_start_lineno": 38,
"task_id": "project_cc_python/616"
} | {
"list": [
{
"filename": "tests/service/test_collection_service.py",
"retrieved_chunk": " # Call the function being tested\n actual_rows = self.service.get_by_name(name)\n # Check the result\n self.assertEqual(actual_rows, expected_rows)\n self.service.collection_re... | to_dict()) |
{
"list": [
{
"filename": "embedin/index/flat_index.py",
"retrieved_chunk": " Updates the index with new embeddings.\n Parameters:\n ----------\n embeddings: A list of embeddings, where each embedding is a list\n or array of floats.\n \"\"\"\n if no... | # -*- coding: utf-8 -*-
# embedin - A vector database that empowers AI with persistent memory,
# (C) 2023 EmbedInAI
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.o... |
self.index.resize_index(new_index_size)
self.index.add_items(embeddings)
self.embeddings = np.concatenate((self.embeddings, embeddings), axis=0)
def _search_index(self, query_embeddings, top_k):
"""
Searches the index for the top K nearest embeddings to the given query embe... | {
"context_start_lineno": 0,
"file": "embedin/index/hnsw_index.py",
"groundtruth_start_lineno": 67,
"repository": "EmbedInAI-EmbedInDB-b2d7852",
"right_context_start_lineno": 68,
"task_id": "project_cc_python/603"
} | {
"list": [
{
"filename": "embedin/index/flat_index.py",
"retrieved_chunk": " xb_normalized = embeddings / xb_norm\n self.index.add(xb_normalized)\n self.embeddings = np.concatenate((self.embeddings, embeddings), axis=0)\n def _search_index(self, query_embeddings, top_k):\n ... | index.get_current_count() + embeddings.shape[0] |
{
"list": [
{
"filename": "dln/template.py",
"retrieved_chunk": " template: str\n stop_tokens: List[str] = None\n version: int = \"latest\"\n description: str = None\n message: str = None\n message_alternatives: List[str] = None\n def render(self, **kwargs):\n if kwargs.get... | import pytest
from dln.template import DLNTemplate, Templates, load_template
def test_DLNTemplate_render():
template = DLNTemplate(template="{{ message }}")
rendered = template.render(message="Foo bar!")
assert rendered == "Foo bar!"
def test_DLNTemplate_render_default_message():
template = DLNTemp... |
assert suffix_forward.template == "{{ input }}\n\n{{ prompt }}"
def test_template_template_not_found():
with pytest.raises(KeyError):
Templates.get("foo")
def test_load_template():
template = load_template("suffix_forward")
rendered = template.render(input="input test", prompt="prompt test"... | {
"context_start_lineno": 0,
"file": "tests/test_dln_templates.py",
"groundtruth_start_lineno": 18,
"repository": "microsoft-deep-language-networks-e7accd0",
"right_context_start_lineno": 19,
"task_id": "project_cc_python/642"
} | {
"list": [
{
"filename": "dln/template.py",
"retrieved_chunk": "class Templates:\n _instance = None\n def __init__(self):\n self._data = {}\n template_directory = os.path.join(os.path.dirname(__file__), 'templates/')\n for filename in glob.glob(f\"{template_directory}/*.yam... | get("suffix_forward") |
{
"list": [
{
"filename": "dln/dataset.py",
"retrieved_chunk": " }\n assert dataset_id in dataset_location, f\"Dataset {dataset_id} not found\"\n dataset = Dataset(dataset_location[dataset_id], dataset_id, seed)\n val_examples = {\"hyperbaton\": 300}.get(dataset_id, -1)\n protos = {\n ... | import numpy as np
from dln.loss import ZeroOneLoss
def test_zero_one_loss():
y = ["a", "b", "c", "a", "b", "c"]
y_hat = ["a", "a", "a", "b", "b", "c"]
zero_one_loss = ZeroOneLoss(lambda x: x)
losses = zero_one_loss(y, y_hat)
np.testing.assert_array_equal(losses, [0.0, 1.0, 1.0, 1.0, 0.0, 0.0])
... |
zero_one_loss = ZeroOneLoss()
assert zero_one_loss.postproc("abc") == "abc"
| {
"context_start_lineno": 0,
"file": "tests/test_dln_losses.py",
"groundtruth_start_lineno": 31,
"repository": "microsoft-deep-language-networks-e7accd0",
"right_context_start_lineno": 32,
"task_id": "project_cc_python/640"
} | {
"list": [
{
"filename": "dln/dataset.py",
"retrieved_chunk": " \"b|B\",\n \"c|C\",\n \"d|D\",\n \"e|E\",\n \"f|F\",\n \"g|G\",\n ],\n }.get(dataset_id, list(dataset.label_mapping.values()))\n output_classes = OutputClasse... | postproc("abc") == "ABC" |
{
"list": [
{
"filename": "dln/template.py",
"retrieved_chunk": " else:\n template = [\n t for t in templates if t.version == pkg_version.parse(version)\n ][0]\n logging.info(f\"Loaded template {template_name} v{template.version}\")\n return te... | import pytest
from dln.template import DLNTemplate, Templates, load_template
def test_DLNTemplate_render():
template = DLNTemplate(template="{{ message }}")
rendered = template.render(message="Foo bar!")
assert rendered == "Foo bar!"
def test_DLNTemplate_render_default_message():
template = DLNTemp... |
assert rendered == ("""input test\n\nprompt test""")
| {
"context_start_lineno": 0,
"file": "tests/test_dln_templates.py",
"groundtruth_start_lineno": 29,
"repository": "microsoft-deep-language-networks-e7accd0",
"right_context_start_lineno": 30,
"task_id": "project_cc_python/643"
} | {
"list": [
{
"filename": "tests/test_dln_postprocessing.py",
"retrieved_chunk": " ],\n)\ndef test_remove_extra_spaces_and_replace_new_lines(input, expected):\n assert remove_extra_spaces(input, True) == expected\n@pytest.mark.parametrize(\n \"input,expected\",\n [\n (\"foo@bar\", \... | render(input="input test", prompt="prompt test") |
{
"list": [
{
"filename": "tests/service/test_embedding_service.py",
"retrieved_chunk": "from embedin.repository.embedding_repository import EmbeddingRepository\nfrom embedin.service.embedding_service import EmbeddingService\nclass TestEmbeddingService(unittest.TestCase):\n def setUp(self):\n ... | # -*- coding: utf-8 -*-
# embedin - A vector database that empowers AI with persistent memory,
# (C) 2023 EmbedInAI
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.o... |
# Call the function being tested
actual_rows = self.service.get_by_name(name)
# Check the result
self.assertEqual(actual_rows, expected_rows)
self.service.collection_repo.get_by_name.assert_called_once_with(name)
def test_create(self):
# Define mock data
n... | {
"context_start_lineno": 0,
"file": "tests/service/test_collection_service.py",
"groundtruth_start_lineno": 33,
"repository": "EmbedInAI-EmbedInDB-b2d7852",
"right_context_start_lineno": 34,
"task_id": "project_cc_python/632"
} | {
"list": [
{
"filename": "tests/service/test_embedding_service.py",
"retrieved_chunk": " collection_id = \"test_collection\"\n embeddings = [[1, 2, 3], [4, 5, 6], [1, 2, 3]]\n texts = [\"test_text_1\", \"test_text_2\", \"test_text_1\"]\n metadata_list = [{\"meta1\": \"valu... | collection_repo.get_by_name = Mock(return_value=expected_rows) |
{
"list": [
{
"filename": "tests/embedding/__init__.py",
"retrieved_chunk": "# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See t... | # -*- coding: utf-8 -*-
# embedin - A vector database that empowers AI with persistent memory,
# (C) 2023 EmbedInAI
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.o... |
self.assertTrue((embedding(text) == expected_output).all())
def test_embedding_multiple_texts(self):
embedding = SentenceTransformerEmbedding()
texts = ["This is a test sentence.", "This is another test sentence."]
expected_output = embedding.model.encode(texts, convert_to_numpy=Tr... | {
"context_start_lineno": 0,
"file": "tests/embedding/test_sentence_transformer_embedding.py",
"groundtruth_start_lineno": 25,
"repository": "EmbedInAI-EmbedInDB-b2d7852",
"right_context_start_lineno": 26,
"task_id": "project_cc_python/639"
} | {
"list": [
{
"filename": "tests/embedding/__init__.py",
"retrieved_chunk": " api_key = \"my_secret_api_key\"\n embedding = Embedding.create_embedding(model_type, api_key)\n self.assertIsInstance(embedding, OpenAIEmbedding)\n def test_create_openai_embedding_without_api_key(sel... | model.encode([text], convert_to_numpy=True) |
{
"list": [
{
"filename": "thoughttree/LabeledLabel.py",
"retrieved_chunk": "import tkinter as tk\nclass LabeledLabel(tk.Frame):\n def __init__(self, master, label_text=None, entry_width=3, textvariable=None, validatecommand=None, *args, **kw):\n super().__init__(master, *args, **kw, bg=\"li... | import tkinter as tk
from tkinter import IntVar, DoubleVar, W, E, X, LEFT, BOTTOM, SUNKEN
from LabeledLabel import LabeledLabel
class StatusBar(tk.Frame):
def __init__(self, master, small_text="", message_text="", note_text="", model_text="", **kw):
super().__init__(master, bd=1, relief=SUNKEN, **kw)
... |
def set_temperature_var(self, var: DoubleVar):
self.temperature_label.entry.config(textvariable=var)
@property
def message(self):
return self.message_label.cget('text')
@message.setter
def message(self, text):
self.message_label.config(text=text)
@property
def n... | {
"context_start_lineno": 0,
"file": "thoughttree/StatusBar.py",
"groundtruth_start_lineno": 54,
"repository": "vsiegel-thoughttree-84b1498",
"right_context_start_lineno": 55,
"task_id": "project_cc_python/669"
} | {
"list": [
{
"filename": "thoughttree/ModelParameterUi.py",
"retrieved_chunk": " def get_parameter_editor(self):\n self.temperature_label = LabeledLabel(self, \"Temp.:\", entry_width=3, validatecommand=self.validate, **self.defaults)",
"score": 121.59366590421939
},
{
"f... | entry.config(textvariable=var) |
{
"list": [
{
"filename": "thoughttree/Sheet.py",
"retrieved_chunk": " self.window_create(index, window=notebook)\n self.delete(index + \"+1char\", END)\n else:\n notebook = parent\n sheet = Sheet(notebook, scrollbar=True)\n notebook.add(sheet, tex... | import tkinter as tk
from Notebook import Notebook
from ResizingText import ResizingText
class ForkableText(tk.Frame):
def __init__(self, parent):
super().__init__(parent)
self.sheet = ResizingText(self)
self.sheet.insert(tk.END, "This is a test\n" * 4)
self.notebook = Notebook(s... |
current_tab.update_idletasks()
self.notebook.configure(height=current_tab.winfo_reqheight())
text_tab1 = ForkableText(self.notebook)
text_tab2 = ForkableText(self.notebook)
self.notebook.add(text_tab1, text="Tab 1")
self.notebook.add(text_tab2, text="Tab 2")
... | {
"context_start_lineno": 0,
"file": "thoughttree/ForkableText.py",
"groundtruth_start_lineno": 22,
"repository": "vsiegel-thoughttree-84b1498",
"right_context_start_lineno": 23,
"task_id": "project_cc_python/684"
} | {
"list": [
{
"filename": "thoughttree/Scrollable.py",
"retrieved_chunk": "if __name__ == \"__main__\":\n ScrollableTest()",
"score": 76.35725675632699
},
{
"filename": "thoughttree/Sheet.py",
"retrieved_chunk": " parent = self.master\n while parent and type(... | nametowidget(self.notebook.select()) |
{
"list": [
{
"filename": "thoughttree/MainMenu.py",
"retrieved_chunk": "class MainMenu(Menu):\n def __init__(self, thoughttree, new_window_callback):\n super().__init__(thoughttree, menu_help=menu_help)\n self.new_window_callback = new_window_callback\n self.ui = thoughttree\n... | import tkinter as tk
from Menu import Menu
from menu_help import menu_help
class ModelsMenu(Menu):
def __init__(self, parent, thoughttree, label):
super().__init__(parent, label, menu_help=menu_help)
self.ui = thoughttree
self.fixed_model_menu_items = -1
self.add_separator()
... |
for i, model_name in enumerate(self.ui.model.get_available_models()):
key = None
if model_name == "gpt-4":
key = "<Control-Alt-Key-4>"
elif model_name == "gpt-3.5-turbo":
key = "<Control-Alt-Key-3>"
if key:
command... | {
"context_start_lineno": 0,
"file": "thoughttree/ModelsMenu.py",
"groundtruth_start_lineno": 30,
"repository": "vsiegel-thoughttree-84b1498",
"right_context_start_lineno": 31,
"task_id": "project_cc_python/673"
} | {
"list": [
{
"filename": "thoughttree/MainMenu.py",
"retrieved_chunk": " widget = self.ui.focus_get()\n if isinstance(widget, Sheet) or isinstance(widget, Console):\n return widget\n def create_menu(self):\n def save(save_dialog, status_bar_label):\n file... | delete(0, present_items - self.fixed_model_menu_items - 1) |
{
"list": [
{
"filename": "thoughttree/MainMenu.py",
"retrieved_chunk": "class MainMenu(Menu):\n def __init__(self, thoughttree, new_window_callback):\n super().__init__(thoughttree, menu_help=menu_help)\n self.new_window_callback = new_window_callback\n self.ui = thoughttree\n... | import tkinter as tk
from Menu import Menu
from menu_help import menu_help
class ModelsMenu(Menu):
def __init__(self, parent, thoughttree, label):
super().__init__(parent, label, menu_help=menu_help)
self.ui = thoughttree
self.fixed_model_menu_items = -1
self.add_separator()
... |
present_items = self.index(tk.END) + 1
if present_items > self.fixed_model_menu_items:
self.delete(0, present_items - self.fixed_model_menu_items - 1)
for i, model_name in enumerate(self.ui.model.get_available_models()):
key = None
if model_name == "gpt-4":
... | {
"context_start_lineno": 0,
"file": "thoughttree/ModelsMenu.py",
"groundtruth_start_lineno": 27,
"repository": "vsiegel-thoughttree-84b1498",
"right_context_start_lineno": 28,
"task_id": "project_cc_python/672"
} | {
"list": [
{
"filename": "thoughttree/MainMenu.py",
"retrieved_chunk": " widget = self.ui.focus_get()\n if isinstance(widget, Sheet) or isinstance(widget, Console):\n return widget\n def create_menu(self):\n def save(save_dialog, status_bar_label):\n file... | index(tk.END) + 1 |
{
"list": [
{
"filename": "thoughttree/MultiTextboxLabel.py",
"retrieved_chunk": "import tkinter as tk\nfrom tkinter import LEFT, SUNKEN, X, TOP, W\nfrom Sheet import Sheet\nclass MultiTextboxLabel(tk.Label):\n def __init__(self, parent=None, sheet=None, **kw):\n super().__init__(parent, bor... | import tkinter as tk
from tkinter import IntVar, DoubleVar, W, E, X, LEFT, BOTTOM, SUNKEN
from LabeledLabel import LabeledLabel
class StatusBar(tk.Frame):
def __init__(self, master, small_text="", message_text="", note_text="", model_text="", **kw):
super().__init__(master, bd=1, relief=SUNKEN, **kw)
... |
self.temperature_label = LabeledLabel(self, "Temp.:", entry_width=3, validatecommand=validate_temperature, **defaults)
self.temperature_label.pack(side=LEFT, padx=(5, 0))
self.model_label = tk.Label(self, **defaults, width=20, text=model_text, anchor=E)
self.model_label.pack(side=LEFT... | {
"context_start_lineno": 0,
"file": "thoughttree/StatusBar.py",
"groundtruth_start_lineno": 44,
"repository": "vsiegel-thoughttree-84b1498",
"right_context_start_lineno": 45,
"task_id": "project_cc_python/668"
} | {
"list": [
{
"filename": "thoughttree/MultiTextboxLabel.py",
"retrieved_chunk": "import tkinter as tk\nfrom tkinter import LEFT, SUNKEN, X, TOP, W\nfrom Sheet import Sheet\nclass MultiTextboxLabel(tk.Label):\n def __init__(self, parent=None, sheet=None, **kw):\n super().__init__(parent, bor... | pack(side=LEFT, padx=(5, 0)) |
{
"list": [
{
"filename": "thoughttree/ForkableText.py",
"retrieved_chunk": "import tkinter as tk\nfrom Notebook import Notebook\nfrom ResizingText import ResizingText\nclass ForkableText(tk.Frame):\n def __init__(self, parent):\n super().__init__(parent)\n self.sheet = ResizingText(s... | import tkinter as tk
from tkinter import CURRENT, END, INSERT, SEL, WORD, X, SEL_FIRST, SEL_LAST
from tkinter import scrolledtext
from typing import Union
from Cursorline import Cursorline
from FinishReasonIcon import FinishReasonIcon
from Notebook import Notebook
from ThoughttreeConfig import conf
class Sheet(tk.sc... |
self.window_create(index, window=notebook)
self.delete(index + "+1char", END)
else:
notebook = parent
sheet = Sheet(notebook, scrollbar=True)
notebook.add(sheet, text=new_sibling(notebook))
notebook.select(len(notebook.tabs()) - 1)
sheet.focu... | {
"context_start_lineno": 0,
"file": "thoughttree/Sheet.py",
"groundtruth_start_lineno": 173,
"repository": "vsiegel-thoughttree-84b1498",
"right_context_start_lineno": 174,
"task_id": "project_cc_python/676"
} | {
"list": [
{
"filename": "thoughttree/ForkableText.py",
"retrieved_chunk": " self.sheet.pack(fill=\"both\", expand=True)\n self.notebook.pack(fill=\"both\", expand=True)\n def fork(self, event=None):\n def update_notebook_height(event):\n current_tab = self.notebook... | add(sheet, text=new_child(parent)) |
{
"list": [
{
"filename": "thoughttree/Sheet.py",
"retrieved_chunk": " self.window_create(index, window=notebook)\n self.delete(index + \"+1char\", END)\n else:\n notebook = parent\n sheet = Sheet(notebook, scrollbar=True)\n notebook.add(sheet, tex... | import tkinter as tk
from Notebook import Notebook
from ResizingText import ResizingText
class ForkableText(tk.Frame):
def __init__(self, parent):
super().__init__(parent)
self.sheet = ResizingText(self)
self.sheet.insert(tk.END, "This is a test\n" * 4)
self.notebook = Notebook(s... |
return "break"
| {
"context_start_lineno": 0,
"file": "thoughttree/ForkableText.py",
"groundtruth_start_lineno": 30,
"repository": "vsiegel-thoughttree-84b1498",
"right_context_start_lineno": 31,
"task_id": "project_cc_python/688"
} | {
"list": [
{
"filename": "thoughttree/Sheet.py",
"retrieved_chunk": " parent = self.master\n while parent and type(parent) != parentType:\n parent = parent.master\n return parent\n def history_from_path(self, history=None) :\n parentText: Sheet = self.find_pa... | bind("<<NotebookTabChanged>>", update_notebook_height) |
{
"list": [
{
"filename": "thoughttree/Sheet.py",
"retrieved_chunk": " self.window_create(index, window=notebook)\n self.delete(index + \"+1char\", END)\n else:\n notebook = parent\n sheet = Sheet(notebook, scrollbar=True)\n notebook.add(sheet, tex... | import tkinter as tk
from Notebook import Notebook
from ResizingText import ResizingText
class ForkableText(tk.Frame):
def __init__(self, parent):
super().__init__(parent)
self.sheet = ResizingText(self)
self.sheet.insert(tk.END, "This is a test\n" * 4)
self.notebook = Notebook(s... |
text_tab1 = ForkableText(self.notebook)
text_tab2 = ForkableText(self.notebook)
self.notebook.add(text_tab1, text="Tab 1")
self.notebook.add(text_tab2, text="Tab 2")
self.notebook.bind("<<NotebookTabChanged>>", update_notebook_height)
return "break"
| {
"context_start_lineno": 0,
"file": "thoughttree/ForkableText.py",
"groundtruth_start_lineno": 24,
"repository": "vsiegel-thoughttree-84b1498",
"right_context_start_lineno": 25,
"task_id": "project_cc_python/686"
} | {
"list": [
{
"filename": "thoughttree/Sheet.py",
"retrieved_chunk": " parent = self.master\n while parent and type(parent) != parentType:\n parent = parent.master\n return parent\n def history_from_path(self, history=None) :\n parentText: Sheet = self.find_pa... | configure(height=current_tab.winfo_reqheight()) |
{
"list": [
{
"filename": "backend/tests/apps/forms/test_tasks.py",
"retrieved_chunk": "from tests.apis.factories import SubmitFactory, AnswerFactory, ChoiceFactory, UserFactory\n@pytest.mark.django_db\ndef test_get_dataframe():\n start_date = datetime.combine(timezone.now().replace(day=1), time.mi... | from datetime import datetime, time
import pytest
from dateutil.relativedelta import relativedelta
from django.utils import timezone
from apps.forms.models import Component
from tests.apis.factories import ComponentFactory
from tests.apis.factories import FormFactory
@pytest.fixture
def form():
start_date = dat... |
return component
@pytest.fixture()
def component_select(form):
component: Component = ComponentFactory(form=form, type=Component.SELECT, is_required=True)
return component
@pytest.fixture()
def component_checkbox(form):
component: Component = ComponentFactory(form=form, type=Component.CHECKBOX, is_... | {
"context_start_lineno": 0,
"file": "backend/tests/apis/v1/forms/conftest.py",
"groundtruth_start_lineno": 29,
"repository": "taptorestart-forms-40b1a91",
"right_context_start_lineno": 30,
"task_id": "project_cc_python/657"
} | {
"list": [
{
"filename": "backend/tests/apps/forms/test_tasks.py",
"retrieved_chunk": " choice1 = ChoiceFactory(component=component_select, text=\"1.\")\n choice2 = ChoiceFactory(component=component_select, text=\"2.\")\n created_at = datetime(year=2023, month=5, day=1)\n submit = SubmitF... | RADIO, is_required=True) |
{
"list": [
{
"filename": "backend/tests/apis/v1/forms/test_views.py",
"retrieved_chunk": " response = client_anonymous.post(path=path, data=data, format=\"json\")\n assert response.status_code == status.HTTP_201_CREATED\n def test_submit_staff_201(self, client_staff, form, component_... | import pytest
from apis.v1.forms.serializers import SubmitSerializer, FormSerializer
from apps.forms.models import Choice
from apps.forms.models import Component
from tests.apis.factories import ChoiceFactory
from tests.apis.factories import ComponentFactory
class TestFormSerializer:
def test_validate_end_date_i... |
assert SubmitSerializer(data=data).is_valid() is True
def test_validate_answers_choice_invalid(self, form, component_radio, component_text):
choice: Choice = ChoiceFactory(component=component_radio)
data = {"form": form.id, "answers": [{"component": component_text.id, "choice": choice.id}]... | {
"context_start_lineno": 0,
"file": "backend/tests/apis/v1/forms/test_serializers.py",
"groundtruth_start_lineno": 28,
"repository": "taptorestart-forms-40b1a91",
"right_context_start_lineno": 29,
"task_id": "project_cc_python/663"
} | {
"list": [
{
"filename": "backend/tests/apis/v1/forms/test_views.py",
"retrieved_chunk": " assert response.status_code == status.HTTP_201_CREATED\n@pytest.mark.urls(urls=\"apis.v1.urls\")\n@pytest.mark.django_db\nclass TestComponentViewSet:\n VIEW_LIST = \"component-list\"\n VIEW_DETAIL ... | id}]} |
{
"list": [
{
"filename": "backend/tests/apis/v1/forms/test_serializers.py",
"retrieved_chunk": " \"form\": form.id,\n \"answers\": [\n {\"component\": component_radio.id, \"choice\": choice1.id},\n {\"component\": component_radio.id, \"choice\": cho... | import datetime
from datetime import datetime, time
import pytest
from dateutil.relativedelta import relativedelta
from django.contrib.auth.models import User
from django.utils import timezone
from apps.forms.models import Component
from apps.forms.tasks import get_dataframe
from tests.apis.factories import Component... |
AnswerFactory(submit_id=submit.id, component=component_select, choice=choice1, choice_text="1.")
AnswerFactory(submit_id=submit.id, component=component_select, choice=choice2, choice_text="2.")
df = get_dataframe(slug="test")
assert df.columns[2] == "select"
assert df.columns[3] == "text"
ass... | {
"context_start_lineno": 0,
"file": "backend/tests/apps/forms/test_tasks.py",
"groundtruth_start_lineno": 30,
"repository": "taptorestart-forms-40b1a91",
"right_context_start_lineno": 31,
"task_id": "project_cc_python/654"
} | {
"list": [
{
"filename": "backend/tests/apis/v1/forms/conftest.py",
"retrieved_chunk": " return component\n@pytest.fixture()\ndef component_text(form):\n component: Component = ComponentFactory(form=form, type=Component.TEXT, is_required=True)\n return component",
"score": 57.574411474... | id, component=component_text, answer="answer") |
{
"list": [
{
"filename": "thoughttree/Sheet.py",
"retrieved_chunk": " self.window_create(index, window=notebook)\n self.delete(index + \"+1char\", END)\n else:\n notebook = parent\n sheet = Sheet(notebook, scrollbar=True)\n notebook.add(sheet, tex... | import tkinter as tk
from Notebook import Notebook
from ResizingText import ResizingText
class ForkableText(tk.Frame):
def __init__(self, parent):
super().__init__(parent)
self.sheet = ResizingText(self)
self.sheet.insert(tk.END, "This is a test\n" * 4)
self.notebook = Notebook(s... |
self.notebook.add(text_tab2, text="Tab 2")
self.notebook.bind("<<NotebookTabChanged>>", update_notebook_height)
return "break"
| {
"context_start_lineno": 0,
"file": "thoughttree/ForkableText.py",
"groundtruth_start_lineno": 28,
"repository": "vsiegel-thoughttree-84b1498",
"right_context_start_lineno": 29,
"task_id": "project_cc_python/687"
} | {
"list": [
{
"filename": "thoughttree/Sheet.py",
"retrieved_chunk": " parent = self.master\n while parent and type(parent) != parentType:\n parent = parent.master\n return parent\n def history_from_path(self, history=None) :\n parentText: Sheet = self.find_pa... | add(text_tab1, text="Tab 1") |
{
"list": [
{
"filename": "backend/apps/forms/tasks.py",
"retrieved_chunk": " for submit in submit_qs:\n answers = submit.answer_set.all().prefetch_related(\"component\")\n row = {0: submit.created_at.strftime(\"%Y-%m-%d %H:%M:%S\"), 1: submit.user.username if submit.user else None}\n... | import datetime
from datetime import datetime, time
import pytest
from dateutil.relativedelta import relativedelta
from django.contrib.auth.models import User
from django.utils import timezone
from apps.forms.models import Component
from apps.forms.tasks import get_dataframe
from tests.apis.factories import Component... |
assert df.iloc[0][1] == "staff"
assert df.iloc[0][2] == "1.\n2."
assert df.iloc[0][3] == "answer"
| {
"context_start_lineno": 0,
"file": "backend/tests/apps/forms/test_tasks.py",
"groundtruth_start_lineno": 38,
"repository": "taptorestart-forms-40b1a91",
"right_context_start_lineno": 39,
"task_id": "project_cc_python/656"
} | {
"list": [
{
"filename": "backend/apps/forms/tasks.py",
"retrieved_chunk": " if column_index not in row:\n row[column_index] = answer_text\n else:\n row[column_index] += \"\\n\" + answer_text\n rows.append(row)\n for row in rows:\n ... | iloc[0][0] == "2023-05-01 00:00:00" |
{
"list": [
{
"filename": "backend/apps/forms/tasks.py",
"retrieved_chunk": "@dataclass\nclass Column:\n index: int\n name: str\n component_id: Optional[int]\ndef get_dataframe(slug: str) -> DataFrame:\n form = Form.objects.get(slug=slug)\n component_qs = Component.objects.filter(form=f... | from celery.result import AsyncResult
from django.contrib import admin
from django.http import Http404, JsonResponse, FileResponse
from django.urls import path
from django.utils.safestring import mark_safe
from rest_framework import status
from apps.forms.models import Form, Component, Choice, Submit
from apps.forms.t... |
obj.order = max(order_list) + 1 if order_list else 1
super().save_model(request, obj, form, change)
@admin.register(Choice)
class ChoiceAdmin(admin.ModelAdmin):
list_display = (
"id",
"component_title",
"text",
"order",
"updated_by",
"created_at... | {
"context_start_lineno": 0,
"file": "backend/apps/forms/admin.py",
"groundtruth_start_lineno": 66,
"repository": "taptorestart-forms-40b1a91",
"right_context_start_lineno": 67,
"task_id": "project_cc_python/644"
} | {
"list": [
{
"filename": "backend/apis/v1/forms/views.py",
"retrieved_chunk": " answer_list.append(\n Answer(\n submit=submit,\n component=answer.get(\"component\"),\n question_title=answer.get(\"component\").title if ... | objects.filter(form_id=obj.form_id).values_list("order", flat=True) |
{
"list": [
{
"filename": "thoughttree/ScrollableForkableSheet.py",
"retrieved_chunk": " print(f\"{event.width} x {event.height}\")\n self.canvas.itemconfigure(self.frame_id, width=event.width)\n # self.canvas.configure(scrollregion=self.canvas.bbox(\"all\"))\n # self.canva... | import tkinter as tk
from tkinter import ttk, BOTH, LEFT, RIGHT, VERTICAL, NW, Y
from ForkableText import ForkableText
class Scrollable(tk.Frame):
def __init__(self, parent):
super().__init__(parent)
self.canvas = tk.Canvas(self, bg="#fbfbfb", highlightthickness=0, bd=0)
self.scrollbar =... |
self.root.geometry("500x500")
self.scrollable = Scrollable(self.root)
self.forkable_text = ForkableText(self.scrollable.frame)
self.scrollable.pack(fill="both", expand=True)
self.forkable_text.pack(fill="both", expand=False)
self.mainloop()
if __name__ == "__main__":... | {
"context_start_lineno": 0,
"file": "thoughttree/Scrollable.py",
"groundtruth_start_lineno": 35,
"repository": "vsiegel-thoughttree-84b1498",
"right_context_start_lineno": 36,
"task_id": "project_cc_python/689"
} | {
"list": [
{
"filename": "thoughttree/ScrollableForkableSheet.py",
"retrieved_chunk": " # ui.root.geometry(\"500x500\")\n scrollable = ScrollableForkableSheet(ui.root)\n scrollable.pack(fill=\"both\", expand=True)\n scrollable.sheet.sheet.focus()\n ui.root.mainloop()",
"score": 1... | root.title("Forkable Text") |
{
"list": [
{
"filename": "backend/apps/forms/tasks.py",
"retrieved_chunk": " for submit in submit_qs:\n answers = submit.answer_set.all().prefetch_related(\"component\")\n row = {0: submit.created_at.strftime(\"%Y-%m-%d %H:%M:%S\"), 1: submit.user.username if submit.user else None}\n... | import datetime
from datetime import datetime, time
import pytest
from dateutil.relativedelta import relativedelta
from django.contrib.auth.models import User
from django.utils import timezone
from apps.forms.models import Component
from apps.forms.tasks import get_dataframe
from tests.apis.factories import Component... |
assert df.columns[3] == "text"
assert df.iloc[0][0] == "2023-05-01 00:00:00"
assert df.iloc[0][1] == "staff"
assert df.iloc[0][2] == "1.\n2."
assert df.iloc[0][3] == "answer"
| {
"context_start_lineno": 0,
"file": "backend/tests/apps/forms/test_tasks.py",
"groundtruth_start_lineno": 36,
"repository": "taptorestart-forms-40b1a91",
"right_context_start_lineno": 37,
"task_id": "project_cc_python/655"
} | {
"list": [
{
"filename": "backend/tests/apis/v1/forms/test_serializers.py",
"retrieved_chunk": " data = {\n \"form\": form.id,\n \"answers\": [\n {\"component\": component_select.id, \"choice\": choice1.id},\n {\"component\": component_select... | columns[2] == "select" |
{
"list": [
{
"filename": "thoughttree/Sheet.py",
"retrieved_chunk": " self.bind('<Prior>', jump_to_limit)\n self.bind('<Next>', jump_to_limit)\n self.pack(pady=0, fill=X, expand=True)\n name, size = self.cget(\"font\").rsplit(None, 1)\n self.tag_configure('bold', fo... | import tkinter as tk
import webbrowser
from datetime import datetime
from tkinter import font as tkfont, NONE, WORD, SEL, END, INSERT
from AboutDialog import AboutDialog
from Files import Files
from Imports import Menu, ModelsMenu, WindowsMenu
from Sheet import Sheet
from Console import Console
from menu_help import m... |
return
dumped = self.it.dump("insert - 1 char", window=True)
# print(f'{ dumped=}')
if dumped and dumped[0][1].endswith("label"):
dumped_win = dumped[0][1]
dumped_win_pos = dumped[0][2]
print(f'{dumped_win=}')
... | {
"context_start_lineno": 0,
"file": "thoughttree/MainMenu.py",
"groundtruth_start_lineno": 116,
"repository": "vsiegel-thoughttree-84b1498",
"right_context_start_lineno": 117,
"task_id": "project_cc_python/697"
} | {
"list": [
{
"filename": "thoughttree/Sheet.py",
"retrieved_chunk": " self.edit_separator()\n def bold(self):\n self.tag_selection('bold')\n def strikethrough(self):\n self.tag_selection('strikethrough')\n def tag_selection(self, tag):\n def min_index(i1, i2):\n ... | focus_get()=}") |
{
"list": [
{
"filename": "thoughttree/ScrollableForkableSheet.py",
"retrieved_chunk": " # ui.root.geometry(\"500x500\")\n scrollable = ScrollableForkableSheet(ui.root)\n scrollable.pack(fill=\"both\", expand=True)\n scrollable.sheet.sheet.focus()\n ui.root.mainloop()",
"score": 9... | import tkinter as tk
from tkinter import ttk, BOTH, LEFT, RIGHT, VERTICAL, NW, Y
from ForkableText import ForkableText
class Scrollable(tk.Frame):
def __init__(self, parent):
super().__init__(parent)
self.canvas = tk.Canvas(self, bg="#fbfbfb", highlightthickness=0, bd=0)
self.scrollbar =... |
self.mainloop()
if __name__ == "__main__":
ScrollableTest()
| {
"context_start_lineno": 0,
"file": "thoughttree/Scrollable.py",
"groundtruth_start_lineno": 42,
"repository": "vsiegel-thoughttree-84b1498",
"right_context_start_lineno": 43,
"task_id": "project_cc_python/690"
} | {
"list": [
{
"filename": "thoughttree/ScrollableForkableSheet.py",
"retrieved_chunk": " # ui.root.geometry(\"500x500\")\n scrollable = ScrollableForkableSheet(ui.root)\n scrollable.pack(fill=\"both\", expand=True)\n scrollable.sheet.sheet.focus()\n ui.root.mainloop()",
"score": 7... | pack(fill="both", expand=False) |
{
"list": [
{
"filename": "thoughttree/ModelsMenu.py",
"retrieved_chunk": "import tkinter as tk\nfrom Menu import Menu\nfrom menu_help import menu_help\nclass ModelsMenu(Menu):\n def __init__(self, parent, thoughttree, label):\n super().__init__(parent, label, menu_help=menu_help)\n s... | import tkinter as tk
from Menu import Menu
from Ui import Ui
from menu_help import menu_help
class WindowsMenu(Menu):
def __init__(self, parent, label):
super().__init__(parent, label, menu_help=None, postcommand=self.create_current_window_items)
def create_current_window_items(self, event=None):
... | {
"context_start_lineno": 0,
"file": "thoughttree/WindowsMenu.py",
"groundtruth_start_lineno": 19,
"repository": "vsiegel-thoughttree-84b1498",
"right_context_start_lineno": 20,
"task_id": "project_cc_python/708"
} | {
"list": [
{
"filename": "thoughttree/ModelsMenu.py",
"retrieved_chunk": " self.item(\"API Key...\", \"\", None)\n self.selected_model = tk.StringVar()\n def on_model_selected(name, index, mode):\n self.ui.set_model(self.selected_model.get())\n self.selected_mod... | item(title, None, command) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.