prefix
stringlengths
82
32.6k
middle
stringlengths
5
470
suffix
stringlengths
0
81.2k
file_path
stringlengths
6
168
repo_name
stringlengths
16
77
context
listlengths
5
5
lang
stringclasses
4 values
ground_truth
stringlengths
5
470
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...
graph, v, w):
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...
zxlive/proof_panel.py
Quantomatic-zxlive-c7b5c28
[ { "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) -> None:\n cmd ...
python
graph, v, w):
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...
splitter.addWidget(self.step_view)
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...
zxlive/proof_panel.py
Quantomatic-zxlive-c7b5c28
[ { "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.clearSelection()\n self....
python
splitter.addWidget(self.step_view)
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...
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_dropped_onto(self, v: VT, w: VT) -> None: if pyzx.basicrules.check_...
zxlive/proof_panel.py
Quantomatic-zxlive-c7b5c28
[ { "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) -> None:\n cmd ...
python
anticipate_fuse(self.graph_scene.vertex_map[w])
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...
fuse(self.graph_scene.vertex_map[v], self.graph_scene.vertex_map[w])
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...
zxlive/proof_panel.py
Quantomatic-zxlive-c7b5c28
[ { "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 g.remove_edg...
python
fuse(self.graph_scene.vertex_map[v], self.graph_scene.vertex_map[w])
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...
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_dropped_onto(self, v: VT, w: VT) -> None: if pyzx.basicrules.check_...
zxlive/proof_panel.py
Quantomatic-zxlive-c7b5c28
[ { "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) -> None:\n cmd ...
python
vertex_map[w])
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 ...
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: QEasingCurve, start: Optional[QPointF] = None) ...
zxlive/animations.py
Quantomatic-zxlive-c7b5c28
[ { "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 panel.undo_s...
python
setStartValue(start or it.scale())
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...
remove_id(self.graph_scene.vertex_map[v])
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...
zxlive/proof_panel.py
Quantomatic-zxlive-c7b5c28
[ { "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.graph_scene.g)\n ...
python
remove_id(self.graph_scene.vertex_map[v])
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...
update_graph(self.g, select_new)
@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)...
zxlive/commands.py
Quantomatic-zxlive-c7b5c28
[ { "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 the updated graph.\...
python
update_graph(self.g, select_new)
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 ...
setEndValue(float(target))
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()) ...
zxlive/animations.py
Quantomatic-zxlive-c7b5c28
[ { "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 preview when dragging...
python
setEndValue(float(target))
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...
set_graph(self.old_g)
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 ...
zxlive/commands.py
Quantomatic-zxlive-c7b5c28
[ { "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.graph_scene.g)\n ...
python
set_graph(self.old_g)
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 ...
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: QPointF, duration: int, ease: QEa...
zxlive/animations.py
Quantomatic-zxlive-c7b5c28
[ { "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 panel.undo_s...
python
setDuration(duration)
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 ...
currentLoopChanged.connect(set_random_params)
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:...
zxlive/animations.py
Quantomatic-zxlive-c7b5c28
[ { "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 for an...
python
currentLoopChanged.connect(set_random_params)
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 ...
Properties.Scale)
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...
zxlive/animations.py
Quantomatic-zxlive-c7b5c28
[ { "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 = anims.strong_comp(pane...
python
Properties.Scale)
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...
add_id(v, self.graph_scene)
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() ...
zxlive/proof_panel.py
Quantomatic-zxlive-c7b5c28
[ { "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.graph_scene.g)\n ...
python
add_id(v, self.graph_scene)
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...
unfuse(self.graph, new_g, v, self.graph_scene)
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...
zxlive/proof_panel.py
Quantomatic-zxlive-c7b5c28
[ { "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.graph_scene.g)\n ...
python
unfuse(self.graph, new_g, v, self.graph_scene)
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 ...
setLoopCount(-1) # Infinite looping
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...
zxlive/animations.py
Quantomatic-zxlive-c7b5c28
[ { "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_to_view(self.graph....
python
setLoopCount(-1) # Infinite looping
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...
back_to_default(self.graph_scene.vertex_map[w])
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...
zxlive/proof_panel.py
Quantomatic-zxlive-c7b5c28
[ { "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 g.remove_edg...
python
back_to_default(self.graph_scene.vertex_map[w])
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...
remove_id(panel.graph_scene.vertex_map[verts[0]])
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...
zxlive/proof_actions.py
Quantomatic-zxlive-c7b5c28
[ { "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()\n panel = G...
python
remove_id(panel.graph_scene.vertex_map[verts[0]])
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...
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.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...
zxlive/proof_actions.py
Quantomatic-zxlive-c7b5c28
[ { "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 self.undo_s...
python
strong_comp(panel.graph, g, verts[0], panel.graph_scene)
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."...
from_tikz(d["initial_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...
zxlive/proof.py
Quantomatic-zxlive-c7b5c28
[ { "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 Formats\"\n QGr...
python
from_tikz(d["initial_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...
fuse(panel.graph_scene.vertex_map[verts[0]], panel.graph_scene.vertex_map[verts[1]])
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...
zxlive/proof_actions.py
Quantomatic-zxlive-c7b5c28
[ { "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 self.undo_s...
python
fuse(panel.graph_scene.vertex_map[verts[0]], panel.graph_scene.vertex_map[verts[1]])
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...
lark(f"This run has cost you {round(money, 2)}$: {model_key}.")
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=...
boolqa/llm_boolqg.py
jiangjiechen-uncommongen-7d1c76e
[ { "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 x[task_key] = {m...
python
lark(f"This run has cost you {round(money, 2)}$: {model_key}.")
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': "...
SortDict(cw_dict)
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 ...
utils.py
jiangjiechen-uncommongen-7d1c76e
[ { "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 = f.readlines()\n ...
python
SortDict(cw_dict)
# 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...
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]] label_batch = [y.numpy() for y in self.Y[index]] filename_batch = [self._parse_...
downstream/speechglue_asr/dataset.py
ashi-ta-speechGLUE-724cf40
[ { "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=\"Number of workers for ...
python
finalize(threshold=threshold, nwords=nwords, padding_factor=padding_factor)
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): ''' ...
decoder(z, graph, neg_graph)
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...
src/models/BaseModules.py
amazon-science-random-tma-43df305
[ { "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 self.tra...
python
decoder(z, graph, neg_graph)
# 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...
add_transcripts_to_dictionary(transcript_list, d, workers)
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...
downstream/speechglue_asr/dataset.py
ashi-ta-speechGLUE-724cf40
[ { "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": 26.30016703498182 ...
python
add_transcripts_to_dictionary(transcript_list, d, workers)
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, ...
add_item(name, name)
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]: """ ...
multigrid/core/constants.py
ini-multigrid-01ee811
[ { "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_index.cache_clear(...
python
add_item(name, name)
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, ...
from_index(i % len(Color)) for i in range(int(n)))
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): ...
multigrid/core/constants.py
ini-multigrid-01ee811
[ { "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[..., AgentState.DIR] = ...
python
from_index(i % len(Color)) for i in range(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...
place_agent(agent, top=room_top, size=room_size)
# 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] -...
multigrid/envs/redbluedoors.py
ini-multigrid-01ee811
[ { "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 surrounding walls\n ...
python
place_agent(agent, top=room_top, size=room_size)
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...
from_string("open the red door then the blue door")
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...
multigrid/envs/redbluedoors.py
ini-multigrid-01ee811
[ { "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 : bool, default=T...
python
from_string("open the red door then the blue door")
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...
_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] - 1 y = self._rand_int(1, height - 1) self.blue_door = Door(Color.blue) self.grid.set(x, y, self.blue_door)...
multigrid/envs/redbluedoors.py
ini-multigrid-01ee811
[ { "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 (se...
python
_rand_int(1, height - 1)
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...
is_autocast_enabled():
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)) ...
falcontune/model/lora.py
rmihaylov-falcontune-6bd029e
[ { "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, **kwargs) -> None:\n ...
python
is_autocast_enabled():
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...
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) def step(self, actions): """ :meta private: """ ...
multigrid/envs/redbluedoors.py
ini-multigrid-01ee811
[ { "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 Y-coord...
python
set(x, y, self.red_door)
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:...
full((len(examples["prompt"]), max_length), self.tokenizer.pad_token_id)
# 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...
falcontune/data.py
rmihaylov-falcontune-6bd029e
[ { "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 // self.world_size\n ...
python
full((len(examples["prompt"]), max_length), self.tokenizer.pad_token_id)
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:...
stack(v) if isinstance(v, list) else v for k, v in out.items()}
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 ...
falcontune/data.py
rmihaylov-falcontune-6bd029e
[ { "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 **deprecated_argu...
python
stack(v) if isinstance(v, list) else v for k, v in out.items()}
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...
matmul(x, buffer) if not transpose else torch.matmul(x, buffer.T)
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,...
falcontune/backend/cuda/autograd.py
rmihaylov-falcontune-6bd029e
[ { "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((x.shape[0], self.o...
python
matmul(x, buffer) if not transpose else torch.matmul(x, buffer.T)
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, ...
_distance_metric, dim=self._dim)
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 ...
peachdb/backends/hnsw_backend.py
peach-db-peachdb-0fb089b
[ { "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 be a vector or a ...
python
_distance_metric, dim=self._dim)
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...
query(query, top_k=top_k, modality="text")
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"...
peachdb/bots/qa.py
peach-db-peachdb-0fb089b
[ { "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 result = []\n # TO...
python
query(query, top_k=top_k, modality="text")
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 ...
analysis.preprocess(SIMPLE_FUNC)
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): ...
test/test_cfg.py
davidmaamoaix-singleline-311d35f
[ { "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(tree)\n single...
python
analysis.preprocess(SIMPLE_FUNC)
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...
add_used(node.id)
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) ->...
singleline/analysis/preprocessor.py
davidmaamoaix-singleline-311d35f
[ { "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 id_gen: Identifier...
python
add_used(node.id)
"""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...
eigh(dense_matrix)
# 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...
matfree/slq.py
pnkraemer-matfree-9b88279
[ { "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": "matfree/decomp.py", "retriev...
python
eigh(dense_matrix)
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_MUT)
singleline.analysis.control_flow_pass(tree) singleline.transform.init_loop_mutations(tree.body[2]) self.assertEqual(tree.body[2].mutated_vars, {'a', 'b'})
test/test_loop_analysis.py
davidmaamoaix-singleline-311d35f
[ { "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 = tree.graph\n ...
python
analysis.preprocess(SIMP_LOOP_MUT)
"""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...
asarray([basis[i], basis[i - 1]])
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...
matfree/lanczos.py
pnkraemer-matfree-9b88279
[ { "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 return montecarlo...
python
asarray([basis[i], basis[i - 1]])
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...
transform.init_loop_mutations(tree.body[2])
self.assertEqual(tree.body[2].mutated_vars, {'a', 'b'})
test/test_loop_analysis.py
davidmaamoaix-singleline-311d35f
[ { "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 = tree.graph\n ...
python
transform.init_loop_mutations(tree.body[2])
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 ...
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): tree, id_gen = singleline.analysis.preprocess(COMPLEX_FUNC) singleline.analysis.control_flow_pass(tree) graph: nx.classes.Di...
test/test_cfg.py
davidmaamoaix-singleline-311d35f
[ { "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(tree)\n single...
python
misc.get_all_convergence(graph, tree)
"""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...
diagonal_matrix(diag)
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) ...
matfree/slq.py
pnkraemer-matfree-9b88279
[ { "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 # Lanczos is not s...
python
diagonal_matrix(diag)
"""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...
vector_norm(vec)
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...
matfree/lanczos.py
pnkraemer-matfree-9b88279
[ { "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\" bit above into a d...
python
vector_norm(vec)
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...
get_node_data(meshtastic_id=packet["fromId"])
if data: telemetry_data = data packet_data = packet["decoded"]["telemetry"] telemetry_data.append( { "time": packet_data["time"], "batteryLevel": packet_data["deviceMetrics"]["batteryLevel"], ...
plugins/telemetry_plugin.py
geoffwhittington-meshtastic-matrix-relay-ffe969f
[ { "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 ):\n ...
python
get_node_data(meshtastic_id=packet["fromId"])
"""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*...
diagonal(vals) @ Vt
matfree/test_util.py
pnkraemer-matfree-9b88279
[ { "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_, Vt_ = linalg.svd(A...
python
diagonal(vals) @ Vt
"""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...
decompose_fori_loop(v0, Av, algorithm=algorithm)
(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,...
matfree/slq.py
pnkraemer-matfree-9b88279
[ { "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 # Lanczos is not s...
python
decompose_fori_loop(v0, Av, algorithm=algorithm)
"""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...
vecdot(vec1, vec2)
vec_ortho = vec1 - coeff * vec2 return vec_ortho, coeff
matfree/lanczos.py
pnkraemer-matfree-9b88279
[ { "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 statistics_combine = [n...
python
vecdot(vec1, vec2)
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(...
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: self.observe(llp.Transformer(self.ctx), llp.EOS) self.finish() # Cre...
examples/infilling.py
probcomp-LLaMPPL-56ef219
[ { "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.can_follow = can_fo...
python
Transformer(self.ctx))
"""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...
vmap(matfun)(eigvals)
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...
matfree/slq.py
pnkraemer-matfree-9b88279
[ { "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": "matfree/test_util.py", "ret...
python
vmap(matfun)(eigvals)
"""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...
zeros((depth + 1,))
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. ...
matfree/lanczos.py
pnkraemer-matfree-9b88279
[ { "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 multilevel framework.", ...
python
zeros((depth + 1,))
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(...
smc_steer(model, 4,4)):
print(f"Particle {i}: {p} (weight {p.weight})")
examples/infilling.py
probcomp-LLaMPPL-56ef219
[ { "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(logits + mask)\n ...
python
smc_steer(model, 4,4)):
"""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...
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) def schatten_norm(*args, power, **kwargs): r"""Compute the Schatten-p norm o...
matfree/slq.py
pnkraemer-matfree-9b88279
[ { "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": "matfree/test_util.py", "re...
python
vecdot(eigvecs[0, :], fx_eigvals * eigvecs[0, :])
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...
set_node_data(meshtastic_id=packet["fromId"], node_data=telemetry_data)
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...
plugins/telemetry_plugin.py
geoffwhittington-meshtastic-matrix-relay-ffe969f
[ { "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 info[\"deviceMetri...
python
set_node_data(meshtastic_id=packet["fromId"], node_data=telemetry_data)
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...
get_data():
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...
plugins/telemetry_plugin.py
geoffwhittington-meshtastic-matrix-relay-ffe969f
[ { "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)\n label.grid(...
python
get_data():
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...
send_matrix_message(room.room_id, reply)
return True
plugins/help_plugin.py
geoffwhittington-meshtastic-matrix-relay-ffe969f
[ { "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 )\n ...
python
send_matrix_message(room.room_id, reply)
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(...
Geometric(0.5)) + 1
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: ...
examples/infilling.py
probcomp-LLaMPPL-56ef219
[ { "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 return Fal...
python
Geometric(0.5)) + 1
"""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 ...
fori_loop(lower, upper, body_fun=body_fun, init_val=init_val)
return extract(result)
matfree/decomp.py
pnkraemer-matfree-9b88279
[ { "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)\ndef array_map(fun...
python
fori_loop(lower, upper, body_fun=body_fun, init_val=init_val)
"""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...
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 * vec2 return vec_ortho, coeff
matfree/lanczos.py
pnkraemer-matfree-9b88279
[ { "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\" bit above into a d...
python
scan(_gram_schmidt_orthogonalise, vec, xs=vectors)
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...
prompt(prompt)
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...
llamppl/model.py
probcomp-LLaMPPL-56ef219
[ { "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:\n self...
python
prompt(prompt)
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...
strip_raw(dict_obj)
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( ...
plugins/mesh_relay_plugin.py
geoffwhittington-meshtastic-matrix-relay-ffe969f
[ { "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\" in data:\n ...
python
strip_raw(dict_obj)
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_...
params[self._end_time_label]
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...
code/JDDB/jddb/processor/basic_processors/clip_processor.py
jtext-103-jddb-077b729
[ { "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 self._std = ...
python
params[self._end_time_label]
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: ...
config["zoom"] if "zoom" in self.config else 8
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_...
plugins/map_plugin.py
geoffwhittington-meshtastic-matrix-relay-ffe969f
[ { "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_client = await connect...
python
config["zoom"] if "zoom" in self.config else 8
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 ): ...
send_matrix_message(room.room_id, "pong!")
return True
plugins/ping_plugin.py
geoffwhittington-meshtastic-matrix-relay-ffe969f
[ { "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 full_message = fu...
python
send_matrix_message(room.room_id, "pong!")
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...
tokenizer_by_name(), **Pythia.tokenizer_by_name()}
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...
generate.py
smpanaro-more-ane-transformers-d5aec6f
[ { "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.')\nparser.add_arg...
python
tokenizer_by_name(), **Pythia.tokenizer_by_name()}
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...
ClanAddedRaidCycleReset(**json.loads(_sub_cycle))
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": [ ...
tap_titans/tests/models.py
SilicalNZ-TapTitans2py-0d5409d
[ { "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 # Python is just ...
python
ClanAddedRaidCycleReset(**json.loads(_sub_cycle))
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...
build_inputs(inputs['input_ids'], pad_to_length=512, pad_token_id=tok.pad_token_id)
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...
generate.py
smpanaro-more-ane-transformers-d5aec6f
[ { "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 logits[logit...
python
build_inputs(inputs['input_ids'], pad_to_length=512, pad_token_id=tok.pad_token_id)
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...
RaidStart(**json.loads(_raid_sub_start))
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...
tap_titans/tests/models.py
SilicalNZ-TapTitans2py-0d5409d
[ { "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 # Python is just ...
python
RaidStart(**json.loads(_raid_sub_start))
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 ...
kahan_mean(x.to("mps").half(), 4).float().cpu()
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_...
src/experiments/kahan_layer_norm.py
smpanaro-more-ane-transformers-d5aec6f
[ { "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) % size == 0, \"B...
python
kahan_mean(x.to("mps").half(), 4).float().cpu()
# -*- 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...
_add_rows_one_by_one(self.embeddings)
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()....
tests/repository/test_embedding_repository.py
EmbedInAI-EmbedInDB-b2d7852
[ { "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 self.session.rollba...
python
_add_rows_one_by_one(self.embeddings)
# -*- 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...
add_all(self.embeddings_dict)
# 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"}, ...
tests/repository/test_embedding_repository.py
EmbedInAI-EmbedInDB-b2d7852
[ { "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.id, \"123\")\n ...
python
add_all(self.embeddings_dict)
# -*- 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...
to_dict())
# 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...
tests/repository/test_collection_repository.py
EmbedInAI-EmbedInDB-b2d7852
[ { "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).first()\n colle...
python
to_dict())
# -*- 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...
index.get_current_count() + embeddings.shape[0]
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...
embedin/index/hnsw_index.py
EmbedInAI-EmbedInDB-b2d7852
[ { "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 not embeddings:\n ...
python
index.get_current_count() + embeddings.shape[0]
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...
get("suffix_forward")
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"...
tests/test_dln_templates.py
microsoft-deep-language-networks-e7accd0
[ { "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(\"message\") is N...
python
get("suffix_forward")
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]) ...
postproc("abc") == "ABC"
zero_one_loss = ZeroOneLoss() assert zero_one_loss.postproc("abc") == "abc"
tests/test_dln_losses.py
microsoft-deep-language-networks-e7accd0
[ { "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 \"hyperbaton...
python
postproc("abc") == "ABC"
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...
render(input="input test", prompt="prompt test")
assert rendered == ("""input test\n\nprompt test""")
tests/test_dln_templates.py
microsoft-deep-language-networks-e7accd0
[ { "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 template\ndef load_t...
python
render(input="input test", prompt="prompt test")
# -*- 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...
collection_repo.get_by_name = Mock(return_value=expected_rows)
# 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...
tests/service/test_collection_service.py
EmbedInAI-EmbedInDB-b2d7852
[ { "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 self.session = M...
python
collection_repo.get_by_name = Mock(return_value=expected_rows)
# -*- 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...
model.encode([text], convert_to_numpy=True)
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...
tests/embedding/test_sentence_transformer_embedding.py
EmbedInAI-EmbedInDB-b2d7852
[ { "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 the License for the...
python
model.encode([text], convert_to_numpy=True)
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) ...
entry.config(textvariable=var)
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...
thoughttree/StatusBar.py
vsiegel-thoughttree-84b1498
[ { "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=\"light blue\")\n ...
python
entry.config(textvariable=var)
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...
nametowidget(self.notebook.select())
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") ...
thoughttree/ForkableText.py
vsiegel-thoughttree-84b1498
[ { "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, text=new_sibling(note...
python
nametowidget(self.notebook.select())
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() ...
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": key = "<Control-Alt-Key-4>" elif model_name == "gpt-3.5-turbo": key = "<Control-Alt-Key-3>" if key: command...
thoughttree/ModelsMenu.py
vsiegel-thoughttree-84b1498
[ { "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 self.fixed...
python
delete(0, present_items - self.fixed_model_menu_items - 1)
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() ...
index(tk.END) + 1
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": ...
thoughttree/ModelsMenu.py
vsiegel-thoughttree-84b1498
[ { "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 self.fixed...
python
index(tk.END) + 1
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) ...
pack(side=LEFT, padx=(5, 0))
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...
thoughttree/StatusBar.py
vsiegel-thoughttree-84b1498
[ { "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, borderwidth=4, anchor...
python
pack(side=LEFT, padx=(5, 0))
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...
add(sheet, text=new_child(parent))
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...
thoughttree/Sheet.py
vsiegel-thoughttree-84b1498
[ { "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(self)\n self...
python
add(sheet, text=new_child(parent))
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...
bind("<<NotebookTabChanged>>", update_notebook_height)
return "break"
thoughttree/ForkableText.py
vsiegel-thoughttree-84b1498
[ { "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, text=new_sibling(note...
python
bind("<<NotebookTabChanged>>", update_notebook_height)
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...
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") self.notebook.bind("<<NotebookTabChanged>>", update_notebook_height) return "break"
thoughttree/ForkableText.py
vsiegel-thoughttree-84b1498
[ { "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, text=new_sibling(note...
python
configure(height=current_tab.winfo_reqheight())
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...
RADIO, is_required=True)
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_...
backend/tests/apis/v1/forms/conftest.py
taptorestart-forms-40b1a91
[ { "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.min)\n end_date =...
python
RADIO, is_required=True)
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...
id}]}
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}]...
backend/tests/apis/v1/forms/test_serializers.py
taptorestart-forms-40b1a91
[ { "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_radio):\n c...
python
id}]}
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...
id, component=component_text, answer="answer")
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...
backend/tests/apps/forms/test_tasks.py
taptorestart-forms-40b1a91
[ { "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\": choice2.id},\n ...
python
id, component=component_text, answer="answer")
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...
add(text_tab1, text="Tab 1")
self.notebook.add(text_tab2, text="Tab 2") self.notebook.bind("<<NotebookTabChanged>>", update_notebook_height) return "break"
thoughttree/ForkableText.py
vsiegel-thoughttree-84b1498
[ { "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, text=new_sibling(note...
python
add(text_tab1, text="Tab 1")
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...
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"
backend/tests/apps/forms/test_tasks.py
taptorestart-forms-40b1a91
[ { "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 for answer...
python
iloc[0][0] == "2023-05-01 00:00:00"
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...
objects.filter(form_id=obj.form_id).values_list("order", flat=True)
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...
backend/apps/forms/admin.py
taptorestart-forms-40b1a91
[ { "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=form.id, type__in=C...
python
objects.filter(form_id=obj.form_id).values_list("order", flat=True)
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 =...
root.title("Forkable Text")
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__":...
thoughttree/Scrollable.py
vsiegel-thoughttree-84b1498
[ { "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.canvas.configure(scroll...
python
root.title("Forkable Text")
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...
columns[2] == "select"
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"
backend/tests/apps/forms/test_tasks.py
taptorestart-forms-40b1a91
[ { "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 for answer...
python
columns[2] == "select"
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...
focus_get()=}")
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=}') ...
thoughttree/MainMenu.py
vsiegel-thoughttree-84b1498
[ { "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', font=(name, int(size...
python
focus_get()=}")
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 =...
pack(fill="both", expand=False)
self.mainloop() if __name__ == "__main__": ScrollableTest()
thoughttree/Scrollable.py
vsiegel-thoughttree-84b1498
[ { "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": 93.02540542272445 }...
python
pack(fill="both", expand=False)
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): ...
item(title, None, command)
thoughttree/WindowsMenu.py
vsiegel-thoughttree-84b1498
[ { "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 self.ui = thoughttr...
python
item(title, None, command)