uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d2f05b115acbb91aab5ab4eb | train | class | class CircuitBuilder:
def __init__(
self,
qregs: List[QuantumRegister],
cregs: Optional[List[ClassicalRegister]] = None,
name: Optional[str] = None,
phase: Optional[sympy.Expr] = 0 * sympy.pi,
):
self.qregs = qregs
self.cregs = [] if cregs is None else cre... | class CircuitBuilder:
| def __init__(
self,
qregs: List[QuantumRegister],
cregs: Optional[List[ClassicalRegister]] = None,
name: Optional[str] = None,
phase: Optional[sympy.Expr] = 0 * sympy.pi,
):
self.qregs = qregs
self.cregs = [] if cregs is None else cregs
self.qbmap ... | ype
# assumption that unitary will refer to unitary2qbox, even though it means any unitary
_gate_str_2_optype["unitary"] = OpType.Unitary2qBox
_gate_str_2_optype_rev = {v: k for k, v in _gate_str_2_optype.items()}
# the aliasing of the name is ok in the reverse map
_gate_str_2_optype_rev[OpType.Unitary1qBox] = "unitar... | 256 | 256 | 944 | 4 | 252 | irfankhan10/pytket-extensions | modules/pytket-qiskit/pytket/extensions/qiskit/qiskit_convert.py | Python | CircuitBuilder | CircuitBuilder | 214 | 308 | 214 | 214 | 44d8fa9e6aba66e7f8c9cff9437b4ae0f8e10ad1 | bigcode/the-stack | train |
0f87090b3c2414f1baffd30e | train | function | def append_tk_command_to_qiskit(
op: "Op",
args: List["UnitID"],
qcirc: QuantumCircuit,
qregmap: Dict[str, QuantumRegister],
cregmap: Dict[str, ClassicalRegister],
symb_map: Dict[Parameter, sympy.Symbol],
range_preds: Dict[Bit, Tuple[List["UnitID"], int]],
) -> Instruction:
optype = op.t... | def append_tk_command_to_qiskit(
op: "Op",
args: List["UnitID"],
qcirc: QuantumCircuit,
qregmap: Dict[str, QuantumRegister],
cregmap: Dict[str, ClassicalRegister],
symb_map: Dict[Parameter, sympy.Symbol],
range_preds: Dict[Bit, Tuple[List["UnitID"], int]],
) -> Instruction:
| optype = op.type
if optype == OpType.Measure:
qubit = args[0]
bit = args[1]
qb = qregmap[qubit.reg_name][qubit.index[0]]
b = cregmap[bit.reg_name][bit.index[0]]
return qcirc.measure(qb, b)
if optype == OpType.Reset:
qb = qregmap[args[0].reg_name][args[0].inde... | return symexpr._sympy_() / sympy.pi
except AttributeError:
return symexpr / sympy.pi
else:
return p / sympy.pi
def param_to_qiskit(
p: sympy.Expr, symb_map: Dict[Parameter, sympy.Symbol]
) -> Union[float, ParameterExpression]:
ppi = p * sympy.pi
if len(ppi.free_symbols) ==... | 256 | 256 | 1,274 | 86 | 170 | irfankhan10/pytket-extensions | modules/pytket-qiskit/pytket/extensions/qiskit/qiskit_convert.py | Python | append_tk_command_to_qiskit | append_tk_command_to_qiskit | 369 | 495 | 369 | 377 | 17a187134d9e2c00bcae383851fec747d50e58a3 | bigcode/the-stack | train |
de3ae7f51f76bc2dbaf84306 | train | class | class FullyConnected2(Architecture):
"""A replacement FullyConnected architecture that doesn't build the full
matrix.
For use with large numbers of qubits, to avoid calculations/routing."""
def __init__(self, n_nodes: int) -> None:
super().__init__([])
self.n_nodes = n_nodes
@prope... | class FullyConnected2(Architecture):
| """A replacement FullyConnected architecture that doesn't build the full
matrix.
For use with large numbers of qubits, to avoid calculations/routing."""
def __init__(self, n_nodes: int) -> None:
super().__init__([])
self.n_nodes = n_nodes
@property
def nodes(self) -> List[Node]... | _name, uuid = name_spl
new_p = Parameter.__new__(Parameter, p_name, UUID(uuid))
new_p.__init__(p_name)
updates[p] = new_p
qcirc.assign_parameters(updates, inplace=True)
return qcirc
class FullyConnected2(Architecture):
| 64 | 64 | 119 | 7 | 56 | irfankhan10/pytket-extensions | modules/pytket-qiskit/pytket/extensions/qiskit/qiskit_convert.py | Python | FullyConnected2 | FullyConnected2 | 555 | 570 | 555 | 555 | 65c870b71db2f769d5e750a6b175649fcf50fd9b | bigcode/the-stack | train |
566dba5bacb6ed2eaefb48e7 | train | function | def _get_params(
op: Op, symb_map: Dict[Parameter, sympy.Symbol]
) -> List[Union[float, ParameterExpression]]:
return [param_to_qiskit(p, symb_map) for p in op.params]
| def _get_params(
op: Op, symb_map: Dict[Parameter, sympy.Symbol]
) -> List[Union[float, ParameterExpression]]:
| return [param_to_qiskit(p, symb_map) for p in op.params]
| (ppi.free_symbols) == 0:
return float(ppi.evalf())
else:
return ParameterExpression(symb_map, ppi)
def _get_params(
op: Op, symb_map: Dict[Parameter, sympy.Symbol]
) -> List[Union[float, ParameterExpression]]:
| 64 | 64 | 53 | 33 | 31 | irfankhan10/pytket-extensions | modules/pytket-qiskit/pytket/extensions/qiskit/qiskit_convert.py | Python | _get_params | _get_params | 363 | 366 | 363 | 365 | b96c639e71288acade672a9c716c49f8858bb48b | bigcode/the-stack | train |
78822c52cee27467ede4fac1 | train | function | def qiskit_to_tk(qcirc: QuantumCircuit, preserve_param_uuid: bool = False) -> Circuit:
"""Convert a :py:class:`qiskit.QuantumCircuit` to a :py:class:`Circuit`.
:param qcirc: A circuit to be converted
:type qcirc: QuantumCircuit
:param preserve_param_uuid: Whether to preserve symbolic Parameter uuids
... | def qiskit_to_tk(qcirc: QuantumCircuit, preserve_param_uuid: bool = False) -> Circuit:
| """Convert a :py:class:`qiskit.QuantumCircuit` to a :py:class:`Circuit`.
:param qcirc: A circuit to be converted
:type qcirc: QuantumCircuit
:param preserve_param_uuid: Whether to preserve symbolic Parameter uuids
by appending them to the tket Circuit symbol names as "_UUID:<uuid>".
Thi... | qubits,
**condition_kwargs,
)
else:
raise NotImplementedError("CUGate with nonzero phase")
else:
params = [param_to_tk(p) for p in i.params]
self.tkc.add_gate(optype, param... | 91 | 91 | 306 | 24 | 67 | irfankhan10/pytket-extensions | modules/pytket-qiskit/pytket/extensions/qiskit/qiskit_convert.py | Python | qiskit_to_tk | qiskit_to_tk | 311 | 339 | 311 | 311 | fe092354776a7daf422740b68c8c36a3dddfb32d | bigcode/the-stack | train |
ce793c0fe08fe80f91e990fb | train | function | def param_to_tk(p: Union[float, ParameterExpression]) -> sympy.Expr:
if isinstance(p, ParameterExpression):
symexpr = p._symbol_expr
try:
return symexpr._sympy_() / sympy.pi
except AttributeError:
return symexpr / sympy.pi
else:
return p / sympy.pi
| def param_to_tk(p: Union[float, ParameterExpression]) -> sympy.Expr:
| if isinstance(p, ParameterExpression):
symexpr = p._symbol_expr
try:
return symexpr._sympy_() / sympy.pi
except AttributeError:
return symexpr / sympy.pi
else:
return p / sympy.pi
| cregs=qcirc.cregs,
name=circ_name,
phase=param_to_tk(qcirc.global_phase),
)
builder.add_qiskit_data(qcirc.data)
return builder.circuit()
def param_to_tk(p: Union[float, ParameterExpression]) -> sympy.Expr:
| 64 | 64 | 78 | 19 | 45 | irfankhan10/pytket-extensions | modules/pytket-qiskit/pytket/extensions/qiskit/qiskit_convert.py | Python | param_to_tk | param_to_tk | 342 | 350 | 342 | 342 | 493b8781d9f67dcc23d3f9df559b790961fc1799 | bigcode/the-stack | train |
8d82349cccc48d0bc288cc77 | train | function | def param_to_qiskit(
p: sympy.Expr, symb_map: Dict[Parameter, sympy.Symbol]
) -> Union[float, ParameterExpression]:
ppi = p * sympy.pi
if len(ppi.free_symbols) == 0:
return float(ppi.evalf())
else:
return ParameterExpression(symb_map, ppi)
| def param_to_qiskit(
p: sympy.Expr, symb_map: Dict[Parameter, sympy.Symbol]
) -> Union[float, ParameterExpression]:
| ppi = p * sympy.pi
if len(ppi.free_symbols) == 0:
return float(ppi.evalf())
else:
return ParameterExpression(symb_map, ppi)
| sympy.pi
except AttributeError:
return symexpr / sympy.pi
else:
return p / sympy.pi
def param_to_qiskit(
p: sympy.Expr, symb_map: Dict[Parameter, sympy.Symbol]
) -> Union[float, ParameterExpression]:
| 64 | 64 | 79 | 35 | 28 | irfankhan10/pytket-extensions | modules/pytket-qiskit/pytket/extensions/qiskit/qiskit_convert.py | Python | param_to_qiskit | param_to_qiskit | 353 | 360 | 353 | 355 | 541f5ed39c618d5fd4816d13f413c56cb3e9be77 | bigcode/the-stack | train |
e5ebd8fc80fce0b16feea187 | train | function | def process_characterisation(backend: "QiskitBackend") -> Dict[str, Any]:
"""Convert a :py:class:`qiskit.providers.backend.Backendv1` to a dictionary
containing device Characteristics
:param backend: A backend to be converted
:type backend: Backendv1
:return: A dictionary containing device charact... | def process_characterisation(backend: "QiskitBackend") -> Dict[str, Any]:
| """Convert a :py:class:`qiskit.providers.backend.Backendv1` to a dictionary
containing device Characteristics
:param backend: A backend to be converted
:type backend: Backendv1
:return: A dictionary containing device characteristics
:rtype: dict
"""
gate_set = _tk_gate_set(backend)
... | # if UUID stored in name, set parameter uuids accordingly (see qiskit_to_tk)
updates = dict()
for p in qcirc.parameters:
name_spl = p.name.split("_UUID:", 2)
if len(name_spl) == 2:
p_name, uuid = name_spl
new_p = Parameter.__new__(Parameter, p_name, UUID(uuid))
... | 256 | 256 | 989 | 19 | 236 | irfankhan10/pytket-extensions | modules/pytket-qiskit/pytket/extensions/qiskit/qiskit_convert.py | Python | process_characterisation | process_characterisation | 573 | 668 | 573 | 573 | 8f974d9bbe438cafd94048ba1a35b7c1f8e28baa | bigcode/the-stack | train |
971acc5e3e0c2aa16842244c | train | function | def tk_to_qiskit(tkcirc: Circuit) -> QuantumCircuit:
"""Convert back
:param tkcirc: A circuit to be converted
:type tkcirc: Circuit
:return: The converted circuit
:rtype: QuantumCircuit
"""
tkc = tkcirc
qcirc = QuantumCircuit(name=tkc.name)
qreg_sizes: Dict[str, int] = {}
for qb... | def tk_to_qiskit(tkcirc: Circuit) -> QuantumCircuit:
| """Convert back
:param tkcirc: A circuit to be converted
:type tkcirc: Circuit
:return: The converted circuit
:rtype: QuantumCircuit
"""
tkc = tkcirc
qcirc = QuantumCircuit(name=tkc.name)
qreg_sizes: Dict[str, int] = {}
for qb in tkc.qubits:
if len(qb.index) != 1:
... | .append(
qiskit_gates.UGate(params[1], params[0] - half, params[2] + half),
qargs=qargs,
)
qcirc.global_phase += -params[0] / 2 - params[2] / 2
return qcirc
# others are direct translations
try:
gatetype, phase = _known_gate_rev_phase[optype]
except Ke... | 187 | 187 | 625 | 16 | 171 | irfankhan10/pytket-extensions | modules/pytket-qiskit/pytket/extensions/qiskit/qiskit_convert.py | Python | tk_to_qiskit | tk_to_qiskit | 498 | 552 | 498 | 498 | 42f88e5b807e91d3b0100936ab435414d0d9a51a | bigcode/the-stack | train |
a0ed3a48ca4084978c6cfe91 | train | class | class XRSTimeSeries(GenericTimeSeries):
"""
GOES XRS Time Series.
Each GOES satellite there are two X-ray Sensors (XRS) which provide solar X ray fluxes
for the wavelength bands of 0.5 to 4 Å (short channel) sand 1 to 8 Å (long channel).
Most recent data is usually available one or two days late.... | class XRSTimeSeries(GenericTimeSeries):
| """
GOES XRS Time Series.
Each GOES satellite there are two X-ray Sensors (XRS) which provide solar X ray fluxes
for the wavelength bands of 0.5 to 4 Å (short channel) sand 1 to 8 Å (long channel).
Most recent data is usually available one or two days late.
Data is available starting on 1981... | """
This module provies GOES XRS `~sunpy.timeseries.TimeSeries` source.
"""
import datetime
from pathlib import Path
from collections import OrderedDict
from distutils.version import LooseVersion
import h5netcdf
import matplotlib.dates
import matplotlib.ticker as mticker
import numpy as np
from matplotlib import pyplo... | 185 | 256 | 2,338 | 9 | 176 | RhnSharma/sunpy | sunpy/timeseries/sources/goes.py | Python | XRSTimeSeries | XRSTimeSeries | 30 | 265 | 30 | 30 | 60003cb0f5ddbd521528813517825a0419dd2ab5 | bigcode/the-stack | train |
0899171a65e664562a1b5356 | train | class | class V1ResourceAttributes(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute t... | class V1ResourceAttributes(object):
| """NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The... | # coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1.18.20
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
f... | 100 | 256 | 2,123 | 7 | 92 | opsani/kubernetes_asyncio | kubernetes_asyncio/client/models/v1_resource_attributes.py | Python | V1ResourceAttributes | V1ResourceAttributes | 21 | 290 | 21 | 21 | 9df1e7aab17cd67e530a3da7c1cb0a73ea2c3b0b | bigcode/the-stack | train |
76195cd52095bfebca845819 | train | function | def _run_cmd(*args):
"""Runs a command using subprocess, returning a two-tuple consisting of
the return code and a binary string containing the data written to
stdout."""
proc = Popen(
args, stdin=PIPE, stdout=PIPE, stderr=PIPE,
cwd=os.path.dirname(__file__))
output, _ = proc.communi... | def _run_cmd(*args):
| """Runs a command using subprocess, returning a two-tuple consisting of
the return code and a binary string containing the data written to
stdout."""
proc = Popen(
args, stdin=PIPE, stdout=PIPE, stderr=PIPE,
cwd=os.path.dirname(__file__))
output, _ = proc.communicate()
code = pro... | """Version metadata file. This file is overridden by setuptools with the
actual version when the module is "built"."""
import os
from subprocess import Popen, PIPE
def _run_cmd(*args):
| 42 | 64 | 91 | 7 | 34 | jvanstraten/vhdmmio | vhdmmio/version.py | Python | _run_cmd | _run_cmd | 8 | 17 | 8 | 8 | 624e0ca1c5f75bce174f9e1e63a5281888266943 | bigcode/the-stack | train |
fc10d0e8bff008d1fc5d1e99 | train | function | def _get_version():
"""Attempts to get vhdmmio's version at runtime using `git`."""
try:
code, output = _run_cmd('git', 'describe', '--tags')
if code:
return 'unknown'
output = output.decode('utf8').strip().split('-')
if len(output) != 3:
return 'unknown'
... | def _get_version():
| """Attempts to get vhdmmio's version at runtime using `git`."""
try:
code, output = _run_cmd('git', 'describe', '--tags')
if code:
return 'unknown'
output = output.decode('utf8').strip().split('-')
if len(output) != 3:
return 'unknown'
version = '%... | the data written to
stdout."""
proc = Popen(
args, stdin=PIPE, stdout=PIPE, stderr=PIPE,
cwd=os.path.dirname(__file__))
output, _ = proc.communicate()
code = proc.returncode
return code, output
def _get_version():
| 64 | 64 | 140 | 5 | 58 | jvanstraten/vhdmmio | vhdmmio/version.py | Python | _get_version | _get_version | 20 | 37 | 20 | 20 | 2642dc82ca703dbe46bbec567d30e3ed6d8e93f7 | bigcode/the-stack | train |
acabd0ed5c9ca7827d49fbb6 | train | class | class Form1(tkinter.Tk):
def __init__(self):
super().__init__()
self.frame = tkinter.ttk.Frame(self)
self.frame.pack(fill = tkinter.BOTH, expand=1)
self.frameTrackBar = tkinter.ttk.Frame(self.frame, width=200, height=25)
self.frameTrackBar.pack_propagate(0)
self.frameTrackBar.place(x = 2... | class Form1(tkinter.Tk):
| def __init__(self):
super().__init__()
self.frame = tkinter.ttk.Frame(self)
self.frame.pack(fill = tkinter.BOTH, expand=1)
self.frameTrackBar = tkinter.ttk.Frame(self.frame, width=200, height=25)
self.frameTrackBar.pack_propagate(0)
self.frameTrackBar.place(x = 20, y = 50)
self.valu... | #!/usr/bin/env python3
# -*-coding:utf-8 -*
import tkinter
import tkinter.ttk
class Form1(tkinter.Tk):
| 32 | 108 | 361 | 9 | 22 | Python-clique/Examples_Python | tkinter/TrackBar/TrackBar.py | Python | Form1 | Form1 | 7 | 44 | 7 | 7 | 286800bd961d299d61059ad169ee70a83e328a0b | bigcode/the-stack | train |
dbafe72bdca815d9ebfdaba2 | train | class | class ResnetTest(absltest.TestCase):
def test_resnet(self):
input_shape = (3, 256, 256, 3)
model = resnet.Resnet50(d_hidden=8, n_output_classes=10)
final_shape = tl.check_shape_agreement(model, input_shape)
self.assertEqual((3, 10), final_shape)
def test_wide_resnet(self):
input_shape = (3, 32... | class ResnetTest(absltest.TestCase):
| def test_resnet(self):
input_shape = (3, 256, 256, 3)
model = resnet.Resnet50(d_hidden=8, n_output_classes=10)
final_shape = tl.check_shape_agreement(model, input_shape)
self.assertEqual((3, 10), final_shape)
def test_wide_resnet(self):
input_shape = (3, 32, 32, 3)
model = resnet.WideResnet... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import absltest
from tensor2tensor.trax import layers as tl
from tensor2tensor.trax.models import resnet
class ResnetTest(absltest.TestCase):
| 64 | 64 | 151 | 10 | 53 | phamthuonghai/tensor2tensor | tensor2tensor/trax/models/resnet_test.py | Python | ResnetTest | ResnetTest | 27 | 39 | 27 | 28 | 23794a67fbd0e764bb9f86fff5bdf72f1d00a02f | bigcode/the-stack | train |
9631e2ce1f94736a3c26f328 | train | function | def test_unexpected_result():
with databricks_test.session() as dbrickstest:
actual_query = """
SELECT col1,col2
FROM
(VALUES
(100,'foo'),
(101,'bar')
) AS v (col1, col2)
"""
expected_query = """
SELECT col1,col2
FROM
... | def test_unexpected_result():
| with databricks_test.session() as dbrickstest:
actual_query = """
SELECT col1,col2
FROM
(VALUES
(100,'foo'),
(101,'bar')
) AS v (col1, col2)
"""
expected_query = """
SELECT col1,col2
FROM
(VALUES
(100,'f... | x')
) AS v (col1, col2)
"""
with pytest.raises(Exception) as exception_message:
dbrickstest.assert_queries_are_equal(actual_query, expected_query)
assert str(exception_message.value).startswith("the result sets did not match:")
def test_unexpected_result():
| 63 | 64 | 196 | 6 | 58 | edharper01/databricks_test | tests/assert_queries_are_equal_test.py | Python | test_unexpected_result | test_unexpected_result | 46 | 77 | 46 | 46 | 3689607a2e44b58928824ebcac658d05373559b4 | bigcode/the-stack | train |
1c7f630424cf8203934d33d7 | train | function | def test_results_match():
with databricks_test.session() as dbrickstest:
query = """
SELECT col1,col2
FROM
(VALUES
(100,'foo'),
(101,'bar'),
(102,'baz')
) AS v (col1, col2)
"""
dbrickstest.assert_queries_are_equal(query, query)
| def test_results_match():
| with databricks_test.session() as dbrickstest:
query = """
SELECT col1,col2
FROM
(VALUES
(100,'foo'),
(101,'bar'),
(102,'baz')
) AS v (col1, col2)
"""
dbrickstest.assert_queries_are_equal(query, query)
| import databricks_test
import pytest
def test_results_match():
| 14 | 64 | 79 | 5 | 8 | edharper01/databricks_test | tests/assert_queries_are_equal_test.py | Python | test_results_match | test_results_match | 5 | 17 | 5 | 5 | de9a09214abbab3ca49c5d3449d47fecc8ffc2e2 | bigcode/the-stack | train |
241560d87b39c4cb15a3bf7d | train | function | def test_results_do_not_match():
with databricks_test.session() as dbrickstest:
actual_query = """
SELECT col1,col2
FROM
(VALUES
(100,'foo'),
(101,'bar'),
(102,'baz')
) AS v (col1, col2)
"""
expected_query = """
SELECT c... | def test_results_do_not_match():
| with databricks_test.session() as dbrickstest:
actual_query = """
SELECT col1,col2
FROM
(VALUES
(100,'foo'),
(101,'bar'),
(102,'baz')
) AS v (col1, col2)
"""
expected_query = """
SELECT col1,col2
FROM
(VA... | SELECT col1,col2
FROM
(VALUES
(100,'foo'),
(101,'bar'),
(102,'baz')
) AS v (col1, col2)
"""
dbrickstest.assert_queries_are_equal(query, query)
def test_results_do_not_match():
| 64 | 64 | 163 | 7 | 57 | edharper01/databricks_test | tests/assert_queries_are_equal_test.py | Python | test_results_do_not_match | test_results_do_not_match | 19 | 44 | 19 | 19 | 47132e89ec885ea5e151753c4c78bea2c001185d | bigcode/the-stack | train |
946c3417ec79a8339406305d | train | function | def test_missing_result():
with databricks_test.session() as dbrickstest:
actual_query = """
SELECT col1,col2
FROM
(VALUES
(100,'foo')
) AS v (col1, col2)
"""
expected_query = """
SELECT col1,col2
FROM
(VALUES
(10... | def test_missing_result():
| with databricks_test.session() as dbrickstest:
actual_query = """
SELECT col1,col2
FROM
(VALUES
(100,'foo')
) AS v (col1, col2)
"""
expected_query = """
SELECT col1,col2
FROM
(VALUES
(100,'foo'),
(101,'b... | |= |100 |foo |
|> |101 |bar |
+---+----+----+
"""
with pytest.raises(Exception) as exception_message:
dbrickstest.assert_queries_are_equal(actual_query, expected_query)
assert str(exception_message.value)==expected_message
def test_missing_result():
| 64 | 64 | 195 | 5 | 58 | edharper01/databricks_test | tests/assert_queries_are_equal_test.py | Python | test_missing_result | test_missing_result | 79 | 110 | 79 | 79 | 1124a9fafe91909b0edcd45eb1d829c528ca9af6 | bigcode/the-stack | train |
74657b0e4e12327a87e664f6 | train | function | @web.middleware
async def check_auth(request, handler):
"""Check if client has correct token in case of accessing protected paths."""
if request.path.startswith(USER_PATH):
secret_key = request.app["constants"]["SECRET_KEY"]
auth_token = request.headers.get("Authorization")
decoded_token... | @web.middleware
async def check_auth(request, handler):
| """Check if client has correct token in case of accessing protected paths."""
if request.path.startswith(USER_PATH):
secret_key = request.app["constants"]["SECRET_KEY"]
auth_token = request.headers.get("Authorization")
decoded_token = decode_jwt(auth_token, secret_key)
if not dec... | """This module provides middlewares for server app."""
from aiohttp import web
from core.jwt import decode_jwt
USER_PATH = "/user"
@web.middleware
async def check_auth(request, handler):
| 42 | 64 | 124 | 12 | 30 | SheetWithoutShit/sws | server/app/middlewares.py | Python | check_auth | check_auth | 11 | 25 | 11 | 12 | c7f327ade224cac5da218f003ce911b2aa0e7ae9 | bigcode/the-stack | train |
1a3f52f220de5e071a28f717 | train | function | @web.middleware
async def check_permission(request, handler):
"""Check if client has appropriate permissions."""
if request.path.startswith(USER_PATH):
telegram_id = int(request.match_info["telegram_id"])
if telegram_id != request.user_id:
return web.json_response(
da... | @web.middleware
async def check_permission(request, handler):
| """Check if client has appropriate permissions."""
if request.path.startswith(USER_PATH):
telegram_id = int(request.match_info["telegram_id"])
if telegram_id != request.user_id:
return web.json_response(
data={"message": "Forbidden. You don't have appropriate permissi... | not decoded_token:
return web.json_response(
data={"message": "You aren't authorized. Please provide correct authorization token."},
status=401
)
request.user_id = decoded_token.get("user_id")
return await handler(request)
@web.middleware
async def c... | 64 | 64 | 84 | 12 | 52 | SheetWithoutShit/sws | server/app/middlewares.py | Python | check_permission | check_permission | 28 | 39 | 28 | 29 | 68a41f2c0b6d09fb796480a3976c2c515f0eff71 | bigcode/the-stack | train |
76eaea986c354156586b166e | train | function | def meta_data():
listDS = ['test-data-set', 'test-control-set', '250-test', 'control1',
'control2', 'control3' ,'control4', 'control5', 'control6',
'control7', 'control8']
attrib = defaultdict(list)
for dfname in listDS:
for direction in ['up', 'dw']:
logger.i... | def meta_data():
| listDS = ['test-data-set', 'test-control-set', '250-test', 'control1',
'control2', 'control3' ,'control4', 'control5', 'control6',
'control7', 'control8']
attrib = defaultdict(list)
for dfname in listDS:
for direction in ['up', 'dw']:
logger.info('load datafra... | :
method = 'sum'
self.up = up_g.sum()
self.dw = dw_g.sum()
return
#############################################################################
# Helper func
#############################################################################
def getSortedCDF(data):
"""
r... | 117 | 117 | 393 | 4 | 113 | briancabbott/xtrax | Software-Projects/experimental/experimental--tv-data-analysis/comcast-analysis/dev/old/dataplot.py | Python | meta_data | meta_data | 277 | 311 | 277 | 277 | 02ec596dabead0c6df33379109836ca35ac3338a | bigcode/the-stack | train |
f2a40b110e2b0f371b25bf69 | train | class | class ComcastDataSet:
def __init__(self, **kwargs):
self.DATAPATH = kwargs['DATAPATH']
self.PROCESSEDPATH = kwargs['PROCESSEDPATH']
self.OUTPUTPATH = kwargs['OUTPUTPATH']
self.FILTEREDPATH = kwargs['FILTEREDPATH']
self.NDEV = 1000
self.name = None
if 'FILENAME... | class ComcastDataSet:
| def __init__(self, **kwargs):
self.DATAPATH = kwargs['DATAPATH']
self.PROCESSEDPATH = kwargs['PROCESSEDPATH']
self.OUTPUTPATH = kwargs['OUTPUTPATH']
self.FILTEREDPATH = kwargs['FILTEREDPATH']
self.NDEV = 1000
self.name = None
if 'FILENAME' in kwargs.keys():
... | S = ['control5']
#LIST_OF_CONTROLLABELS = ['control'+str(l) for l in range(1,9)]
#LIST_OF_CONTROLLABELS.remove('control3') #causes errors unslicable
foldername = CONTROLLABEL
DATAPATH = '../data/'
FILTEREDPATH = '../filtered/'
PROCESSEDPATH = '../processed/' + foldername + '/'
OUTPUTPATH = '../output/' + folde... | 256 | 256 | 1,878 | 5 | 251 | briancabbott/xtrax | Software-Projects/experimental/experimental--tv-data-analysis/comcast-analysis/dev/old/dataplot.py | Python | ComcastDataSet | ComcastDataSet | 62 | 257 | 62 | 62 | e6c99176eeabc0dec935f9d3931634eecb2d7204 | bigcode/the-stack | train |
9786fcad1ebb7b3ca88e8f2d | train | function | def getSortedCDF(data):
"""
return x,y for a cdf given one dimensional unsorted data x
"""
sorted_data = np.sort( data )
YSCALE = len(sorted_data)
yvals = [y/YSCALE for y in range( len(sorted_data) )]
return sorted_data, yvals
| def getSortedCDF(data):
| """
return x,y for a cdf given one dimensional unsorted data x
"""
sorted_data = np.sort( data )
YSCALE = len(sorted_data)
yvals = [y/YSCALE for y in range( len(sorted_data) )]
return sorted_data, yvals
| if method=='max':
self.up = up_g.max()
self.dw = dw_g.max()
else:
method = 'sum'
self.up = up_g.sum()
self.dw = dw_g.sum()
return
#############################################################################
# Helper func
############... | 64 | 64 | 72 | 6 | 58 | briancabbott/xtrax | Software-Projects/experimental/experimental--tv-data-analysis/comcast-analysis/dev/old/dataplot.py | Python | getSortedCDF | getSortedCDF | 264 | 271 | 264 | 264 | 6bb7222f5c51d70ff48ff0874fc01d2cd8bab49b | bigcode/the-stack | train |
d3f5ffe7d8e96240f02056f0 | train | function | def main2(ndev=NDEVICES, DataSet=DATALABEL, ControlSets=LIST_OF_CONTROLLABELS, method='sum'):
logger.info("NDEVICES "+str(ndev)+" DateSet "+DataSet+" ControlSets "+str(ControlSets))
# Plotter Class Object
p = Plotter()
# load test set up and down
DATA_up, DATA_dw = load_dataframe(DataSet)
# for ... | def main2(ndev=NDEVICES, DataSet=DATALABEL, ControlSets=LIST_OF_CONTROLLABELS, method='sum'):
| logger.info("NDEVICES "+str(ndev)+" DateSet "+DataSet+" ControlSets "+str(ControlSets))
# Plotter Class Object
p = Plotter()
# load test set up and down
DATA_up, DATA_dw = load_dataframe(DataSet)
# for control set in [control1 - control8]
for ControlSet in ControlSets:
# load test an... | ##############################################################################
#DATASET = 'test-data-set.dat'
#CONTROLSET = 'test-control-set.dat'
#DATALABEL = 'test-data-set'
LIST_OF_CONTROLLABELS = ['test-control-set']
NDEVICES = 1000
def main2(ndev=NDEVICES, DataSet=DATALABEL, ControlSets=LIST_OF_CONTROLLABELS, met... | 81 | 81 | 270 | 29 | 51 | briancabbott/xtrax | Software-Projects/experimental/experimental--tv-data-analysis/comcast-analysis/dev/old/dataplot.py | Python | main2 | main2 | 619 | 645 | 619 | 619 | b3710e075f7ff2b4c2f80f27651739273217885a | bigcode/the-stack | train |
18d22dd1e35a0a4a79711bb9 | train | function | def process_df(df, method='sum'):
g = df.groupby(['Device_number', 'end_time', 'date', 'time'], as_index=False)
if method=='sum':
return g.sum()
elif method=='max':
return g.max()
elif method=='wifi':
return df[df['service_class_name'] == 'xwifi_dn' | df['service_class_name'] == ... | def process_df(df, method='sum'):
| g = df.groupby(['Device_number', 'end_time', 'date', 'time'], as_index=False)
if method=='sum':
return g.sum()
elif method=='max':
return g.max()
elif method=='wifi':
return df[df['service_class_name'] == 'xwifi_dn' | df['service_class_name'] == 'xwifi_up']
else:
retu... | )
p.import_df(test_up, test_dw, control_up, control_dw)
p.DLABEL = DataSet
p.CLABEL = ControlSet
x = p.plotAll()
logger.info("Done "+ControlSet)
return p, x
def process_df(df, method='sum'):
| 64 | 64 | 105 | 9 | 54 | briancabbott/xtrax | Software-Projects/experimental/experimental--tv-data-analysis/comcast-analysis/dev/old/dataplot.py | Python | process_df | process_df | 647 | 656 | 647 | 647 | 21f515eb44d134f81095562e8b30ccc98ed02df7 | bigcode/the-stack | train |
d464c6ac16d05760e1eaa42f | train | class | class Plotter:
def __init__(self, dlabel=DATALABEL, clabel=CONTROLLABEL, XSCALE='log'):
self.test_up = 0
self.test_dw = 0
self.control_up = 0
self.control_dw = 0
self.DLABEL = dlabel
self.CLABEL = clabel
self.DISPLAY_MEAN = 1
self.OUTPUTPATH = OUTPUTP... | class Plotter:
| def __init__(self, dlabel=DATALABEL, clabel=CONTROLLABEL, XSCALE='log'):
self.test_up = 0
self.test_dw = 0
self.control_up = 0
self.control_dw = 0
self.DLABEL = dlabel
self.CLABEL = clabel
self.DISPLAY_MEAN = 1
self.OUTPUTPATH = OUTPUTPATH
sel... | )) )
CUP_sliced = slice_df(CONTROL_up, ndev, date_start, date_stop)
DUP_sliced = slice_df(DATA_up, ndev, date_start, date_stop)
#logger.debug("sliced UP sets ")
# get date_start, date_end
date_start, date_stop = get_dates(CONTROL_dw)
# slice
logger.debug(ControlSet + " ndev=" + str(ndev) ... | 256 | 256 | 2,515 | 4 | 252 | briancabbott/xtrax | Software-Projects/experimental/experimental--tv-data-analysis/comcast-analysis/dev/old/dataplot.py | Python | Plotter | Plotter | 344 | 607 | 344 | 344 | a2f852bcf36fc530744e4d7830fd6deb8b36309f | bigcode/the-stack | train |
2c5a799387a4ff8386b01df4 | train | function | def slicer(ControlSet, DATA_up, DATA_dw, ndev):
CONTROL_up, CONTROL_dw = load_dataframe(ControlSet)
# get date_start, date_end
date_start, date_stop = get_dates(CONTROL_up)
# slice
logger.debug(ControlSet + " ndev=" + str(ndev) + " control set unique: "\
+ str(len( CONTROL_up['Device_number'... | def slicer(ControlSet, DATA_up, DATA_dw, ndev):
| CONTROL_up, CONTROL_dw = load_dataframe(ControlSet)
# get date_start, date_end
date_start, date_stop = get_dates(CONTROL_up)
# slice
logger.debug(ControlSet + " ndev=" + str(ndev) + " control set unique: "\
+ str(len( CONTROL_up['Device_number'].unique() )) + " data set unique: "\
+ ... | 90) )
logger.debug(pd.DataFrame(attrib))
df_attributes = pd.DataFrame(attrib)[['name', 'direction', 'len',
'date_start', 'date_end',
'num_devices', 'device_start',
'device_end',... | 108 | 108 | 362 | 15 | 92 | briancabbott/xtrax | Software-Projects/experimental/experimental--tv-data-analysis/comcast-analysis/dev/old/dataplot.py | Python | slicer | slicer | 313 | 339 | 313 | 313 | c357b60abe97be591e410b5714bbf4c84b9ea043 | bigcode/the-stack | train |
e7618b5b3108d2b7aca54215 | train | function | def bob(preference, depth):
"""
Bob decides where to go by reasoning about Alice's choice
"""
bob_prior = location(preference)
if depth > 0:
with poutine.block():
alice_marginal = HashingMarginal(Search(alice).run(preference, depth))
return pyro.sample("alice_choice", ali... | def bob(preference, depth):
| """
Bob decides where to go by reasoning about Alice's choice
"""
bob_prior = location(preference)
if depth > 0:
with poutine.block():
alice_marginal = HashingMarginal(Search(alice).run(preference, depth))
return pyro.sample("alice_choice", alice_marginal, obs=bob_prior)
... | """
alice_prior = location(preference)
with poutine.block():
bob_marginal = HashingMarginal(Search(bob).run(preference, depth - 1))
return pyro.sample("bob_choice", bob_marginal, obs=alice_prior)
def bob(preference, depth):
| 64 | 64 | 91 | 7 | 57 | Jayanth-kumar5566/pyro | examples/rsa/schelling.py | Python | bob | bob | 42 | 52 | 42 | 42 | 6e79dab9e075c6b5f09fa03ecddfbf1cce96454b | bigcode/the-stack | train |
b331a2b33a3872e51126a826 | train | function | def alice(preference, depth):
"""
Alice decides where to go by reasoning about Bob's choice
"""
alice_prior = location(preference)
with poutine.block():
bob_marginal = HashingMarginal(Search(bob).run(preference, depth - 1))
return pyro.sample("bob_choice", bob_marginal, obs=alice_prior)
| def alice(preference, depth):
| """
Alice decides where to go by reasoning about Bob's choice
"""
alice_prior = location(preference)
with poutine.block():
bob_marginal = HashingMarginal(Search(bob).run(preference, depth - 1))
return pyro.sample("bob_choice", bob_marginal, obs=alice_prior)
| a weighted coin to decide between two locations to meet
In this example, we assume that Alice and Bob share a prior preference
for one location over another, reflected in the value of preference below.
"""
return pyro.sample("loc", Bernoulli(preference))
def alice(preference, depth):
| 64 | 64 | 79 | 7 | 57 | Jayanth-kumar5566/pyro | examples/rsa/schelling.py | Python | alice | alice | 32 | 39 | 32 | 32 | b537b3b625e75a23cb1f490d6439c946cd2dfc0d | bigcode/the-stack | train |
9699fd49e5619489382e3b2f | train | function | def main(args):
# Here Alice and Bob slightly prefer one location over the other a priori
shared_preference = torch.tensor([args.preference])
bob_depth = args.depth
num_samples = args.num_samples
# We sample Bob's choice of location by marginalizing
# over his decision process.
bob_decisio... | def main(args):
# Here Alice and Bob slightly prefer one location over the other a priori
| shared_preference = torch.tensor([args.preference])
bob_depth = args.depth
num_samples = args.num_samples
# We sample Bob's choice of location by marginalizing
# over his decision process.
bob_decision = HashingMarginal(Search(bob).run(shared_preference, bob_depth))
bob_prob = bob_decision... | _marginal = HashingMarginal(Search(alice).run(preference, depth))
return pyro.sample("alice_choice", alice_marginal, obs=bob_prior)
else:
return bob_prior
def main(args):
# Here Alice and Bob slightly prefer one location over the other a priori
| 64 | 64 | 211 | 20 | 43 | Jayanth-kumar5566/pyro | examples/rsa/schelling.py | Python | main | main | 55 | 78 | 55 | 56 | ba0e31092c434b21ee0bacc35b94fa4a94ab44c8 | bigcode/the-stack | train |
fc39023cc2af822e6906fb9d | train | function | def location(preference):
"""
Flips a weighted coin to decide between two locations to meet
In this example, we assume that Alice and Bob share a prior preference
for one location over another, reflected in the value of preference below.
"""
return pyro.sample("loc", Bernoulli(preference))
| def location(preference):
| """
Flips a weighted coin to decide between two locations to meet
In this example, we assume that Alice and Bob share a prior preference
for one location over another, reflected in the value of preference below.
"""
return pyro.sample("loc", Bernoulli(preference))
| recursively reasoning about one another.
Taken from: http://forestdb.org/models/schelling.html
"""
import argparse
import torch
from search_inference import HashingMarginal, Search
import pyro
import pyro.poutine as poutine
from pyro.distributions import Bernoulli
def location(preference):
| 64 | 64 | 67 | 5 | 58 | Jayanth-kumar5566/pyro | examples/rsa/schelling.py | Python | location | location | 23 | 29 | 23 | 23 | cc7a613e45d6a1f89b2a5c2fd4c3162d646f48fc | bigcode/the-stack | train |
4a66a336d10b933f3cefc9f1 | train | class | class DFCLayer(LayerInterface):
"""Implementation of a Deep Feedback Control layer.
It contains the following important functions:
* forward: which computes the linear activation based on the previous layer
as well as the post non-linearity activation. It stores these in the
attributes "_linea... | class DFCLayer(LayerInterface):
| """Implementation of a Deep Feedback Control layer.
It contains the following important functions:
* forward: which computes the linear activation based on the previous layer
as well as the post non-linearity activation. It stores these in the
attributes "_linear_activations" and "_activa.tion... | Meulemans, Matilde Tristany, Maria Cervera
#
# 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.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | 256 | 256 | 2,952 | 8 | 247 | mariacer/strong_dfc | dfc/networks/dfc_layer.py | Python | DFCLayer | DFCLayer | 34 | 364 | 34 | 34 | 1d7dd6c357930c1c370de0fcbba058fe96507bd5 | bigcode/the-stack | train |
31304ce44f6b6ecd1730703e | train | class | class CloudflareScraper(Session):
def __init__(self, *args, **kwargs):
self.delay = kwargs.pop("delay", None)
# Use headers with a random User-Agent if no custom headers have been set
headers = OrderedDict(kwargs.pop("headers", DEFAULT_HEADERS))
# Set the User-Agent header if it was... | class CloudflareScraper(Session):
| def __init__(self, *args, **kwargs):
self.delay = kwargs.pop("delay", None)
# Use headers with a random User-Agent if no custom headers have been set
headers = OrderedDict(kwargs.pop("headers", DEFAULT_HEADERS))
# Set the User-Agent header if it was not provided
headers.setd... | +xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
),
("Accept-Language", "en-US,en;q=0.9"),
("Accept-Encoding", "gzip, deflate"),
)
)
BUG_REPORT = """\
Cloudflare may have changed their technique, or there may be a bug in the script.
Please read https://github.com/Anorov/cloudfl... | 256 | 256 | 2,255 | 7 | 248 | lukastribus/cloudflare-scrape | cfscrape/__init__.py | Python | CloudflareScraper | CloudflareScraper | 68 | 343 | 68 | 68 | 2a3070badb48a3a0551dacbd813f096a80893b97 | bigcode/the-stack | train |
bbe8fe06320f961781dee268 | train | class | class CloudflareError(RequestException):
pass
| class CloudflareError(RequestException):
| pass
| challenge answer delay (default: 8 seconds). \
For example: cfscrape.create_scraper(delay=15)
If increasing the delay does not help, please open a GitHub issue at \
https://github.com/Anorov/cloudflare-scrape/issues\
"""
class CloudflareError(RequestException):
| 64 | 64 | 10 | 7 | 57 | lukastribus/cloudflare-scrape | cfscrape/__init__.py | Python | CloudflareError | CloudflareError | 60 | 61 | 60 | 60 | 9662b589b4a139da77f9d0007f71b9c0ceb3570b | bigcode/the-stack | train |
ab7665e46ab793cb2beeb966 | train | class | class CloudflareCaptchaError(CloudflareError):
pass
| class CloudflareCaptchaError(CloudflareError):
| pass
| : cfscrape.create_scraper(delay=15)
If increasing the delay does not help, please open a GitHub issue at \
https://github.com/Anorov/cloudflare-scrape/issues\
"""
class CloudflareError(RequestException):
pass
class CloudflareCaptchaError(CloudflareError):
| 64 | 64 | 13 | 10 | 53 | lukastribus/cloudflare-scrape | cfscrape/__init__.py | Python | CloudflareCaptchaError | CloudflareCaptchaError | 64 | 65 | 64 | 64 | c21bfd4c077c7ce218903293abed7de994097c45 | bigcode/the-stack | train |
9d92e0a0901931bcf9c5fbf8 | train | class | class Reader(Cache):
def __init__(self, filepath):
self.filepath = filepath
self.serializer = Serializer(magic_number=unhexlify('e3486a45'))
self.streams = defaultdict(PriorityQueue)
self.stream = Stream()
| class Reader(Cache):
| def __init__(self, filepath):
self.filepath = filepath
self.serializer = Serializer(magic_number=unhexlify('e3486a45'))
self.streams = defaultdict(PriorityQueue)
self.stream = Stream()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from binascii import hexlify, unhexlify
from collections import defaultdict
from Queue import PriorityQueue
from pcap import Stream, Cache
from protocol import Serializer
class Reader(Cache):
| 56 | 64 | 55 | 4 | 51 | BTHPOS/bitnodes | tests/test_bip144.py | Python | Reader | Reader | 12 | 17 | 12 | 12 | 122862d7c54cf6a0b65d9b3e229fbed9448a8914 | bigcode/the-stack | train |
cd567d847934968a6cb57aaf | train | function | def test_bip144():
filepath = os.path.join(
os.path.dirname(os.path.realpath(__file__)), 'data', 'bip144.pcap')
reader = Reader(filepath=filepath)
reader.extract_streams()
msgs = []
for stream_id, reader.stream.segments in reader.streams.iteritems():
assert stream_id == ('1.1.1.1',... | def test_bip144():
| filepath = os.path.join(
os.path.dirname(os.path.realpath(__file__)), 'data', 'bip144.pcap')
reader = Reader(filepath=filepath)
reader.extract_streams()
msgs = []
for stream_id, reader.stream.segments in reader.streams.iteritems():
assert stream_id == ('1.1.1.1', 56691, '2.2.2.2', ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from binascii import hexlify, unhexlify
from collections import defaultdict
from Queue import PriorityQueue
from pcap import Stream, Cache
from protocol import Serializer
class Reader(Cache):
def __init__(self, filepath):
self.filepath = filepath
... | 113 | 115 | 385 | 6 | 107 | BTHPOS/bitnodes | tests/test_bip144.py | Python | test_bip144 | test_bip144 | 20 | 61 | 20 | 20 | 38329385155952d23ace2ba34a3c9a67a442661a | bigcode/the-stack | train |
8d87e89778655c978cd00bbe | train | class | class RoomTypingTestCase(unittest.HomeserverTestCase):
"""Tests /rooms/$room_id/typing/$user_id REST API."""
user_id = "@sid:red"
user = UserID.from_string(user_id)
servlets = [room.register_servlets]
def make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver(
... | class RoomTypingTestCase(unittest.HomeserverTestCase):
| """Tests /rooms/$room_id/typing/$user_id REST API."""
user_id = "@sid:red"
user = UserID.from_string(user_id)
servlets = [room.register_servlets]
def make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver(
"red",
federation_http_client=None,
... | # Copyright 2014-2016 OpenMarket Ltd
# Copyright 2018 New Vector
#
# 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.org/licenses/LICENSE-2.0
#
# Unless required by appl... | 199 | 207 | 690 | 12 | 187 | manju-rn/synapse | tests/rest/client/test_typing.py | Python | RoomTypingTestCase | RoomTypingTestCase | 28 | 127 | 28 | 28 | 1f20a27977f800396cc0223882300a35cc3bf574 | bigcode/the-stack | train |
5c5f9a3f08d7a92b01c5b8f5 | train | class | class Reseller:
def add_client(self, add_client_values):
default_values = {
'authkey' : Base.authkey
}
values = {}
values.update(default_values)
values.update(add_client_values)
response = Base.call('add_client.php', values)
return response
d... | class Reseller:
| def add_client(self, add_client_values):
default_values = {
'authkey' : Base.authkey
}
values = {}
values.update(default_values)
values.update(add_client_values)
response = Base.call('add_client.php', values)
return response
def client_list(se... | import json
from base import Base
class Reseller:
| 12 | 151 | 504 | 4 | 7 | MSG91/msg91-python | msg91/reseller.py | Python | Reseller | Reseller | 4 | 86 | 4 | 5 | 437c608fd35040191a15e40ba46703f07613393e | bigcode/the-stack | train |
ee3edf68e01fe481f7c8bbbf | train | function | def setup(bot):
bot.add_cog(Moderation(bot))
| def setup(bot):
| bot.add_cog(Moderation(bot))
| ged = await ctx.channel.purge(limit=number)
purgeEmbed = discord.Embed(title='Done', description=f"**{ctx.author}** cleared **{len(amount_purged)}** messages",colour=discord.Color.green())
await ctx.send(embed=purgeEmbed)
def setup(bot):
| 63 | 64 | 14 | 4 | 59 | Ay-355/the-buds-bot | cogs/moderation.py | Python | setup | setup | 57 | 58 | 57 | 57 | a5316c9385e81ec77f866165cf6eb2a69dc76bd4 | bigcode/the-stack | train |
6ea0bfc4f118a3fc53b239d0 | train | class | class Moderation(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name="kick")
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
kickEmbed = discord.Embed(ti... | class Moderation(commands.Cog):
| def __init__(self, bot):
self.bot = bot
@commands.command(name="kick")
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
kickEmbed = discord.Embed(title="Member kicked!", descriptio... | import traceback
import asyncio
import discord
from discord.ext import commands
from discord.ext.commands.core import has_permissions
from cogs.utils.checks import admin
class Moderation(commands.Cog):
| 40 | 108 | 362 | 7 | 32 | Ay-355/the-buds-bot | cogs/moderation.py | Python | Moderation | Moderation | 10 | 51 | 10 | 10 | 4de01cb721dbad81cfd730f4a2d96268c5968336 | bigcode/the-stack | train |
336acfacb4db16fb80d002fb | train | class | class SlurmErrorParser(AbstractErrorParser):
"""
Implementation of the error definitions for the Slurm scheduler
"""
@property
def error_definitions(self):
return {
SubmitError: {
'batch_err': {
'string': "Batch job submission failed",
... | class SlurmErrorParser(AbstractErrorParser):
| """
Implementation of the error definitions for the Slurm scheduler
"""
@property
def error_definitions(self):
return {
SubmitError: {
'batch_err': {
'string': "Batch job submission failed",
'meta_filter': {}
... | Parse for the occurens of all errors defined in ERRORS
"""
for error in self.error_definitions:
result = self.parse_single(self.error_definitions[error])
if result[0]:
self.errors.append(error(result[1], result[2]))
if len(self.errors) > 0:
pr... | 93 | 93 | 312 | 9 | 84 | yanikou19/pymatgen | pymatgen/io/gwwrapper/scheduler_error_parsers.py | Python | SlurmErrorParser | SlurmErrorParser | 308 | 356 | 308 | 308 | 8f8a9a9509e548db55d85278152cad453f508502 | bigcode/the-stack | train |
a714d40d1d57d256db5e9687 | train | class | class TimeCancelError(AbstractError):
"""
Error due to exceeding the time limit for the job.
.limit will return a list of limits that were broken, None if it could not be determined.
"""
@property
def limit(self):
return self.meta_data.get('broken_limit')
@property
def schedu... | class TimeCancelError(AbstractError):
| """
Error due to exceeding the time limit for the job.
.limit will return a list of limits that were broken, None if it could not be determined.
"""
@property
def limit(self):
return self.meta_data.get('broken_limit')
@property
def scheduler_adapter_solutions(self):
r... | may have changed.
"""
class FullQueueError(AbstractError):
"""
Errors occurring at submission. To many jobs in the queue / total cpus / .. .
"""
class DiskError(AbstractError):
"""
Errors involving problems writing to disk.
"""
class TimeCancelError(AbstractError):
| 63 | 64 | 110 | 7 | 56 | yanikou19/pymatgen | pymatgen/io/gwwrapper/scheduler_error_parsers.py | Python | TimeCancelError | TimeCancelError | 174 | 190 | 174 | 174 | bc73b7f7516a03e7901cb558c4cc82d05c8b6542 | bigcode/the-stack | train |
15dce2a477ddebf01383f082 | train | class | @six.add_metaclass(ABCMeta)
class CorrectorProtocolScheduler(object):
"""
Abstract class to define the protocol / interface for correction operators. The client code quadapters / submission
script generator method / ... should implement these methods.
"""
@abstractproperty
def name(self):
... | @six.add_metaclass(ABCMeta)
class CorrectorProtocolScheduler(object):
| """
Abstract class to define the protocol / interface for correction operators. The client code quadapters / submission
script generator method / ... should implement these methods.
"""
@abstractproperty
def name(self):
return str()
@abstractmethod
def exclude_nodes(self, nodes... | = "Michiel van Setten"
__email__ = "mjvansetten@gmail.com"
__date__ = "May 2014"
__all_errors__ = ['SubmitError', 'FullQueueError', 'DiskError', 'TimeCancelError', 'MemoryCancelError',
'NodeFailureError']
import re
import abc
import six
from abc import ABCMeta, abstractproperty, abstractmethod
@si... | 101 | 101 | 339 | 16 | 84 | yanikou19/pymatgen | pymatgen/io/gwwrapper/scheduler_error_parsers.py | Python | CorrectorProtocolScheduler | CorrectorProtocolScheduler | 25 | 76 | 25 | 26 | ba9910de295f6538364b62ff661d1c2b78dadf4d | bigcode/the-stack | train |
f40f66443b87a60f37119e3d | train | class | class NodeFailureError(AbstractError):
"""
Error due the hardware failure of a specific node.
.node will return a list of problematic nodes, None if it could not be determined.
"""
@property
def nodes(self):
return self.meta_data.get('nodes')
@property
def scheduler_adapter_so... | class NodeFailureError(AbstractError):
| """
Error due the hardware failure of a specific node.
.node will return a list of problematic nodes, None if it could not be determined.
"""
@property
def nodes(self):
return self.meta_data.get('nodes')
@property
def scheduler_adapter_solutions(self):
return [(Correct... | self.meta_data.get('broken_limit')
@property
def scheduler_adapter_solutions(self):
return [(CorrectorProtocolScheduler.increase_mem,)]
@property
def application_adapter_solutions(self):
return [(CorrectorProtocolApplication.decrease_mem,)]
class NodeFailureError(AbstractError):
| 63 | 64 | 85 | 7 | 56 | yanikou19/pymatgen | pymatgen/io/gwwrapper/scheduler_error_parsers.py | Python | NodeFailureError | NodeFailureError | 212 | 224 | 212 | 212 | 1d5a882e4708a5dbf294e152d85244093a95c8be | bigcode/the-stack | train |
225650f56716ba7cb8c60b47 | train | class | @six.add_metaclass(ABCMeta)
class AbstractErrorParser(object):
"""
Abstract class for parsing errors originating from the scheduler system and error that are not reported by the
program itself, i.e. segmentation faults.
A concrete implementation of this class for a specific scheduler needs a class attr... | @six.add_metaclass(ABCMeta)
class AbstractErrorParser(object):
| """
Abstract class for parsing errors originating from the scheduler system and error that are not reported by the
program itself, i.e. segmentation faults.
A concrete implementation of this class for a specific scheduler needs a class attribute ERRORS for containing a
dictionary specifying error:
... | , None if it could not be determined.
"""
@property
def limit(self):
return self.meta_data.get('broken_limit')
@property
def scheduler_adapter_solutions(self):
return [(CorrectorProtocolScheduler.increase_mem,)]
@property
def application_adapter_solutions(self):
re... | 179 | 180 | 602 | 15 | 164 | yanikou19/pymatgen | pymatgen/io/gwwrapper/scheduler_error_parsers.py | Python | AbstractErrorParser | AbstractErrorParser | 227 | 305 | 227 | 228 | 6729489d10f664fa0c451a1d1ca2a5e2607e6a56 | bigcode/the-stack | train |
1780113a2121045191307e2c | train | class | @six.add_metaclass(ABCMeta)
class AbstractError(object):
"""
Error base class
"""
def __init__(self, errmsg, meta_data):
self.errmsg = errmsg
self.meta_data = meta_data if meta_data is not None else {}
def __str__(self):
_message = '%s %s\n' \
' error m... | @six.add_metaclass(ABCMeta)
class AbstractError(object):
| """
Error base class
"""
def __init__(self, errmsg, meta_data):
self.errmsg = errmsg
self.meta_data = meta_data if meta_data is not None else {}
def __str__(self):
_message = '%s %s\n' \
' error message : %s \n' \
' meta data : %... | been crashed
due to a insufficient memory.
returns True is the memory could be increased False otherwise
"""
return bool
@abstractmethod
def speed_up(self):
"""
Method to speed_up the calculation. It is called when a calculation seemed to time limits being brok... | 94 | 94 | 315 | 14 | 79 | yanikou19/pymatgen | pymatgen/io/gwwrapper/scheduler_error_parsers.py | Python | AbstractError | AbstractError | 110 | 153 | 110 | 111 | 2cca3a27f1c38b781b90ca650ffef7ab14ff8883 | bigcode/the-stack | train |
00210cd7ab2889011f1c2bc5 | train | class | class SubmitError(AbstractError):
"""
Errors occurring at submission. The limits on the cluster may have changed.
"""
| class SubmitError(AbstractError):
| """
Errors occurring at submission. The limits on the cluster may have changed.
"""
| the second element should
contain the arguments.
"""
return []
def last_resort_solution(self):
"""
what to do if every thing else fails...
"""
print('non of the defined solutions for %s returned success...' % self.name)
return
class SubmitError(Abs... | 64 | 64 | 25 | 6 | 57 | yanikou19/pymatgen | pymatgen/io/gwwrapper/scheduler_error_parsers.py | Python | SubmitError | SubmitError | 156 | 159 | 156 | 156 | 0270c87a06bb2bada5e46a8a9445fcffe90ba7d4 | bigcode/the-stack | train |
801c07936f21a6fe721da9eb | train | class | @six.add_metaclass(ABCMeta)
class CorrectorProtocolApplication(object):
"""
Abstract class to define the protocol / interface for correction operators. The client code quadapters / submission
script generator method / ... should implement these methods.
"""
@abstractproperty
def name(self):
... | @six.add_metaclass(ABCMeta)
class CorrectorProtocolApplication(object):
| """
Abstract class to define the protocol / interface for correction operators. The client code quadapters / submission
script generator method / ... should implement these methods.
"""
@abstractproperty
def name(self):
return str()
@abstractmethod
def decrease_mem(self):
... | cpus being used in the calculation. It is called when a calculation seemed to
have been crashed due to time or memory limits being broken.
returns True is the memory could be increased False otherwise
"""
return bool
@six.add_metaclass(ABCMeta)
class CorrectorProtocolApplication(object... | 64 | 64 | 178 | 16 | 47 | yanikou19/pymatgen | pymatgen/io/gwwrapper/scheduler_error_parsers.py | Python | CorrectorProtocolApplication | CorrectorProtocolApplication | 79 | 107 | 79 | 80 | 227be7e376367962353a74802d603a260b4deed0 | bigcode/the-stack | train |
a55112486d3f7004b3b9aca8 | train | class | class MemoryCancelError(AbstractError):
"""
Error due to exceeding the memory limit for the job.
.limit will return a list of limits that were broken, None if it could not be determined.
"""
@property
def limit(self):
return self.meta_data.get('broken_limit')
@property
def sc... | class MemoryCancelError(AbstractError):
| """
Error due to exceeding the memory limit for the job.
.limit will return a list of limits that were broken, None if it could not be determined.
"""
@property
def limit(self):
return self.meta_data.get('broken_limit')
@property
def scheduler_adapter_solutions(self):
... | return self.meta_data.get('broken_limit')
@property
def scheduler_adapter_solutions(self):
return [(CorrectorProtocolScheduler.increase_time,)]
@property
def application_adapter_solutions(self):
return [(CorrectorProtocolApplication.speed_up,)]
class MemoryCancelError(AbstractError):
| 63 | 64 | 111 | 7 | 56 | yanikou19/pymatgen | pymatgen/io/gwwrapper/scheduler_error_parsers.py | Python | MemoryCancelError | MemoryCancelError | 193 | 209 | 193 | 193 | cb840a9e5c50424beca414b1338ff3aaecf08574 | bigcode/the-stack | train |
aac082f57f193e1f623af01b | train | class | class PBSErrorParser(AbstractErrorParser):
"""
Implementation for the PBS scheduler
"""
@property
def error_definitions(self):
return {
TimeCancelError: {
'out': {
'string': "job killed: walltime",
'meta_filter': {
... | class PBSErrorParser(AbstractErrorParser):
| """
Implementation for the PBS scheduler
"""
@property
def error_definitions(self):
return {
TimeCancelError: {
'out': {
'string': "job killed: walltime",
'meta_filter': {
'broken_limit': [r"job kill... | can't open (\S*), network down \(err=26\)", 1]
}
}
},
AbstractError: {
'out': {
'string': "a string to be found",
'meta_filter': {}
}
}
}
class PBSErrorParser(AbstractE... | 64 | 64 | 127 | 8 | 56 | yanikou19/pymatgen | pymatgen/io/gwwrapper/scheduler_error_parsers.py | Python | PBSErrorParser | PBSErrorParser | 359 | 381 | 359 | 359 | 2a045a6c891279e54b3ba887be03a15a464fe2e9 | bigcode/the-stack | train |
910644e292419ba40db55c0c | train | class | class DiskError(AbstractError):
"""
Errors involving problems writing to disk.
"""
| class DiskError(AbstractError):
| """
Errors involving problems writing to disk.
"""
|
class SubmitError(AbstractError):
"""
Errors occurring at submission. The limits on the cluster may have changed.
"""
class FullQueueError(AbstractError):
"""
Errors occurring at submission. To many jobs in the queue / total cpus / .. .
"""
class DiskError(AbstractError):
| 63 | 64 | 18 | 6 | 57 | yanikou19/pymatgen | pymatgen/io/gwwrapper/scheduler_error_parsers.py | Python | DiskError | DiskError | 168 | 171 | 168 | 168 | cf06ea97df5626872089e74cfc0ccc841d04b368 | bigcode/the-stack | train |
901e37cdaab7b8bda6a58353 | train | class | class FullQueueError(AbstractError):
"""
Errors occurring at submission. To many jobs in the queue / total cpus / .. .
"""
| class FullQueueError(AbstractError):
| """
Errors occurring at submission. To many jobs in the queue / total cpus / .. .
"""
| to do if every thing else fails...
"""
print('non of the defined solutions for %s returned success...' % self.name)
return
class SubmitError(AbstractError):
"""
Errors occurring at submission. The limits on the cluster may have changed.
"""
class FullQueueError(AbstractError):
| 63 | 64 | 30 | 7 | 56 | yanikou19/pymatgen | pymatgen/io/gwwrapper/scheduler_error_parsers.py | Python | FullQueueError | FullQueueError | 162 | 165 | 162 | 162 | ca30a69d1aec89a8309179dc62a5b257c8af6589 | bigcode/the-stack | train |
bc8f467bfaa84f3dd803cd7c | train | function | def get_parser(scheduler, err_file, out_file=None, run_err_file=None, batch_err_file=None):
"""
Factory function to provide the parser for the specified scheduler. If the scheduler is not implemented None is
returned. The files, string, correspond to file names of the out and err files:
err_file ... | def get_parser(scheduler, err_file, out_file=None, run_err_file=None, batch_err_file=None):
| """
Factory function to provide the parser for the specified scheduler. If the scheduler is not implemented None is
returned. The files, string, correspond to file names of the out and err files:
err_file stderr of the scheduler
out_file stdout of the scheduler
run_err_file stde... | 'meta_filter': {}
}
}
}
ALL_PARSERS = {'slurm': SlurmErrorParser, 'pbs': PBSErrorParser, 'torque': PBSErrorParser}
def get_parser(scheduler, err_file, out_file=None, run_err_file=None, batch_err_file=None):
| 64 | 64 | 133 | 23 | 41 | yanikou19/pymatgen | pymatgen/io/gwwrapper/scheduler_error_parsers.py | Python | get_parser | get_parser | 387 | 397 | 387 | 387 | 70415d7f33e2856056bf23c1e76c61dd548d6331 | bigcode/the-stack | train |
77e107c9df2dfeed4a945314 | train | class | class EmbeddingTestsMixin:
def setUp(self):
here = os.path.abspath(__file__)
basepath = os.path.dirname(os.path.dirname(os.path.dirname(here)))
exename = "_testembed"
if MS_WINDOWS:
ext = ("_d" if "_d" in sys.executable else "") + ".exe"
exename += ext
... | class EmbeddingTestsMixin:
| def setUp(self):
here = os.path.abspath(__file__)
basepath = os.path.dirname(os.path.dirname(os.path.dirname(here)))
exename = "_testembed"
if MS_WINDOWS:
ext = ("_d" if "_d" in sys.executable else "") + ".exe"
exename += ext
exepath = os.path.dirn... | # Run the tests in Programs/_testembed.c (tests for the CPython embedding APIs)
from test import support
import unittest
from collections import namedtuple
import json
import os
import re
import subprocess
import sys
import textwrap
MS_WINDOWS = (os.name == 'nt')
class EmbeddingTestsMixin:
| 68 | 256 | 986 | 6 | 62 | mak213k/Servidor_automatizado_python | ServidorPython/python32_web/Lib/test/test_embed.py | Python | EmbeddingTestsMixin | EmbeddingTestsMixin | 17 | 116 | 17 | 17 | edf08848167ea0274f66c3fdbc5c9b2a2c77e2c6 | bigcode/the-stack | train |
06a880464352f9fe4c0b4ed3 | train | class | class InitConfigTests(EmbeddingTestsMixin, unittest.TestCase):
maxDiff = 4096
UTF8_MODE_ERRORS = ('surrogatepass' if MS_WINDOWS else 'surrogateescape')
# core config
UNTESTED_CORE_CONFIG = (
# FIXME: untested core configuration variables
'dll_path',
'executable',
'module... | class InitConfigTests(EmbeddingTestsMixin, unittest.TestCase):
| maxDiff = 4096
UTF8_MODE_ERRORS = ('surrogatepass' if MS_WINDOWS else 'surrogateescape')
# core config
UNTESTED_CORE_CONFIG = (
# FIXME: untested core configuration variables
'dll_path',
'executable',
'module_search_paths',
)
# Mark config which should be get by ... | ):
"""
bpo-20891: Calling PyGILState_Ensure in a non-Python thread before
calling PyEval_InitThreads() must not crash. PyGILState_Ensure() must
call PyEval_InitThreads() for us in this case.
"""
out, err = self.run_embedded_interpreter("bpo20891")
self.assertEqual... | 255 | 256 | 2,528 | 13 | 242 | mak213k/Servidor_automatizado_python | ServidorPython/python32_web/Lib/test/test_embed.py | Python | InitConfigTests | InitConfigTests | 257 | 569 | 257 | 257 | 794f3404fbf5bbe201f8aba679882baa7e4e7690 | bigcode/the-stack | train |
72c13910342b36ba3df0fab4 | train | class | class EmbeddingTests(EmbeddingTestsMixin, unittest.TestCase):
def test_subinterps_main(self):
for run in self.run_repeated_init_and_subinterpreters():
main = run[0]
self.assertEqual(main.id, '0')
def test_subinterps_different_ids(self):
for run in self.run_repeated_init... | class EmbeddingTests(EmbeddingTestsMixin, unittest.TestCase):
| def test_subinterps_main(self):
for run in self.run_repeated_init_and_subinterpreters():
main = run[0]
self.assertEqual(main.id, '0')
def test_subinterps_different_ids(self):
for run in self.run_repeated_init_and_subinterpreters():
main, *subs, _ = run
... | ")
numloops = 0
current_run = []
for line in out.splitlines():
if line == "--- Pass {} ---".format(numloops):
self.assertEqual(len(current_run), 0)
if support.verbose > 1:
print(line)
numloops += 1
c... | 255 | 256 | 1,283 | 13 | 242 | mak213k/Servidor_automatizado_python | ServidorPython/python32_web/Lib/test/test_embed.py | Python | EmbeddingTests | EmbeddingTests | 119 | 254 | 119 | 119 | d373a073afd82eee71ef9417c5791f440924f14a | bigcode/the-stack | train |
de124b5b7941edd7066b8777 | train | class | class BotConfig:
def __init__(self, config={}):
self.enableStop = config.get('enableStop', False)
self.stopDoRound = config.get('stopDoRound', 20)
self.action_wait_time = config.get('action_wait_time', 1)
self.enableBreak = config.get('enableBreak', True)
self.breakTime = co... | class BotConfig:
| def __init__(self, config={}):
self.enableStop = config.get('enableStop', False)
self.stopDoRound = config.get('stopDoRound', 20)
self.action_wait_time = config.get('action_wait_time', 1)
self.enableBreak = config.get('enableBreak', True)
self.breakTime = config.get('breakTi... | from enum import Enum
class TrainingAndUpgradeLevel(Enum):
T1 = 0
T2 = 1
T3 = 2
T4 = 3
T5 = 4
UPGRADE_ALL = 5
DISABLED = -1
class BotConfig:
| 67 | 255 | 852 | 4 | 62 | seashell-freya/Rise-of-Kingdoms-Bot | bot_related/bot_config.py | Python | BotConfig | BotConfig | 14 | 92 | 14 | 14 | 4537c7652f1d60f0d98a1533fc16b09fe909bb11 | bigcode/the-stack | train |
4fa548c61de8331c28385653 | train | class | class TrainingAndUpgradeLevel(Enum):
T1 = 0
T2 = 1
T3 = 2
T4 = 3
T5 = 4
UPGRADE_ALL = 5
DISABLED = -1
| class TrainingAndUpgradeLevel(Enum):
| T1 = 0
T2 = 1
T3 = 2
T4 = 3
T5 = 4
UPGRADE_ALL = 5
DISABLED = -1
| from enum import Enum
class TrainingAndUpgradeLevel(Enum):
| 12 | 64 | 58 | 7 | 4 | seashell-freya/Rise-of-Kingdoms-Bot | bot_related/bot_config.py | Python | TrainingAndUpgradeLevel | TrainingAndUpgradeLevel | 4 | 11 | 4 | 4 | ddfe7a3c67f8e06eea617676332e1b094f8e49fa | bigcode/the-stack | train |
4d5b1afa836468c263a34471 | train | function | def wrapper_fn(x):
return torch.foo(x)
| def wrapper_fn(x):
| return torch.foo(x)
| return a + 1
real_wrapped_via_decorator = wrapped_via_decorator
real_a_lifed_leaf = a_lifted_leaf
real_a_lifed_leaf2 = a_lifted_leaf2
_sqrt = sqrt
wrap('wrapper_fn')
def wrapper_fn(x):
| 64 | 64 | 11 | 5 | 59 | SpaceIm/pytorch | test/test_fx.py | Python | wrapper_fn | wrapper_fn | 85 | 86 | 85 | 85 | b489bc9a0239ce0b5f9dabf3bafd708e93a82e96 | bigcode/the-stack | train |
61d83240d6449119c42de521 | train | function | def run_getitem_target():
from torch.fx.symbolic_trace import _wrapped_methods_to_patch
_wrapped_methods_to_patch.append((torch.Tensor, "__getitem__"))
try:
TestFX().getitem_inner()
finally:
_wrapped_methods_to_patch.pop()
| def run_getitem_target():
| from torch.fx.symbolic_trace import _wrapped_methods_to_patch
_wrapped_methods_to_patch.append((torch.Tensor, "__getitem__"))
try:
TestFX().getitem_inner()
finally:
_wrapped_methods_to_patch.pop()
| _f = symbolic_trace(f, enable_cpatching=False)
assert(all(i.target != torch.randn for i in fx_f.graph.nodes))
fx_f = symbolic_trace(f, enable_cpatching=True)
assert(any(i.target == torch.randn for i in fx_f.graph.nodes))
def run_getitem_target():
| 64 | 64 | 56 | 6 | 58 | SpaceIm/pytorch | test/test_fx.py | Python | run_getitem_target | run_getitem_target | 2,221 | 2,227 | 2,221 | 2,221 | 55bc0833698b81a05dca629953532d12df91de78 | bigcode/the-stack | train |
55f8bee1443044a2e0e880d5 | train | function | def a_lifted_leaf2(a, b):
return a[0] + a[1] + b
| def a_lifted_leaf2(a, b):
| return a[0] + a[1] + b
| function
# directly
def a_lifted_leaf(a, b):
return a[0] + a[1] + b
wrap('a_lifted_leaf')
# Test wrapping twice doesn't break anything
wrap('a_lifted_leaf')
def a_lifted_leaf2(a, b):
| 64 | 64 | 25 | 11 | 53 | SpaceIm/pytorch | test/test_fx.py | Python | a_lifted_leaf2 | a_lifted_leaf2 | 66 | 67 | 66 | 66 | 7c85a8423064e8fea5087735902604ea90fcc596 | bigcode/the-stack | train |
65bcba7c711f0029d8192579 | train | class | class TestOperatorSignatures(JitTestCase):
@onlyCPU
@ops(op_db, allowed_dtypes=(torch.float,))
def test_get_torch_func_signature_exhaustive(self, device, dtype, op):
known_no_schema = {'stack', 'hstack', 'vstack', 'dstack', 'repeat', '__getitem__', 'linalg.multi_dot'}
try:
sampl... | class TestOperatorSignatures(JitTestCase):
@onlyCPU
@ops(op_db, allowed_dtypes=(torch.float,))
| def test_get_torch_func_signature_exhaustive(self, device, dtype, op):
known_no_schema = {'stack', 'hstack', 'vstack', 'dstack', 'repeat', '__getitem__', 'linalg.multi_dot'}
try:
sample_inputs_itr = op.sample_inputs(device, dtype, requires_grad=False)
schemas = get_signature... | from torch.fx.symbolic_trace import _wrapped_methods_to_patch
_wrapped_methods_to_patch.append((torch.Tensor, "__getitem__"))
try:
TestFX().getitem_inner()
finally:
_wrapped_methods_to_patch.pop()
class TestOperatorSignatures(JitTestCase):
@onlyCPU
@ops(op_db, allowed_dtypes=(tor... | 78 | 78 | 263 | 28 | 50 | SpaceIm/pytorch | test/test_fx.py | Python | TestOperatorSignatures | TestOperatorSignatures | 2,230 | 2,256 | 2,230 | 2,232 | d71ff1a10857bcb4802ea5da8cbaed9a5699a7dc | bigcode/the-stack | train |
49ea6df74faf6844ad2fb315 | train | class | class Pair(NamedTuple):
x : torch.Tensor
y : torch.Tensor
| class Pair(NamedTuple):
| x : torch.Tensor
y : torch.Tensor
| _decorator = wrapped_via_decorator
real_a_lifed_leaf = a_lifted_leaf
real_a_lifed_leaf2 = a_lifted_leaf2
_sqrt = sqrt
wrap('wrapper_fn')
def wrapper_fn(x):
return torch.foo(x)
class Pair(NamedTuple):
| 64 | 64 | 18 | 6 | 58 | SpaceIm/pytorch | test/test_fx.py | Python | Pair | Pair | 88 | 90 | 88 | 88 | deac3841cd0db0473fccd9a2ea834b39b30f2ddc | bigcode/the-stack | train |
9200866cc5574a4d3c8850cb | train | function | @wrap
def wrapped_via_decorator(a):
return a + 1
| @wrap
def wrapped_via_decorator(a):
| return a + 1
| # Test wrapping twice doesn't break anything
wrap('a_lifted_leaf')
def a_lifted_leaf2(a, b):
return a[0] + a[1] + b
wrap(a_lifted_leaf2)
wrap('len')
@wrap
def wrapped_via_decorator(a):
| 64 | 64 | 18 | 11 | 53 | SpaceIm/pytorch | test/test_fx.py | Python | wrapped_via_decorator | wrapped_via_decorator | 73 | 75 | 73 | 74 | a3501346f5fa8e65b54c7027b1f7ce78575ab4ce | bigcode/the-stack | train |
3683f2662aa39a6e0bf6a87e | train | class | class SimpleTest(torch.nn.Module):
def forward(self, x):
return torch.relu(x + 3.0)
| class SimpleTest(torch.nn.Module):
| def forward(self, x):
return torch.relu(x + 3.0)
| NamedTup
try:
from torchvision.models import resnet18
HAS_TORCHVISION = True
except ImportError:
HAS_TORCHVISION = False
skipIfNoTorchVision = unittest.skipIf(not HAS_TORCHVISION, "no torchvision")
class SimpleTest(torch.nn.Module):
| 64 | 64 | 25 | 7 | 57 | SpaceIm/pytorch | test/test_fx.py | Python | SimpleTest | SimpleTest | 50 | 52 | 50 | 50 | 72ea5633be13211b166158ed1c4bb9d6522f5d76 | bigcode/the-stack | train |
5a6e0ba047dc5ecdaf732752 | train | function | def a_non_torch_leaf(a, b):
return a + b
| def a_non_torch_leaf(a, b):
| return a + b
| HAS_TORCHVISION = False
skipIfNoTorchVision = unittest.skipIf(not HAS_TORCHVISION, "no torchvision")
class SimpleTest(torch.nn.Module):
def forward(self, x):
return torch.relu(x + 3.0)
def a_non_torch_leaf(a, b):
| 64 | 64 | 16 | 10 | 54 | SpaceIm/pytorch | test/test_fx.py | Python | a_non_torch_leaf | a_non_torch_leaf | 54 | 55 | 54 | 54 | 3c1100a1195cfc3110ce1bbf32d265bed8434696 | bigcode/the-stack | train |
3bd271ac1813c6490c11f71b | train | function | def a_lifted_leaf(a, b):
return a[0] + a[1] + b
| def a_lifted_leaf(a, b):
| return a[0] + a[1] + b
| .Module):
def forward(self, x):
return torch.relu(x + 3.0)
def a_non_torch_leaf(a, b):
return a + b
# Test wrap() passing both a function name as well as a function
# directly
def a_lifted_leaf(a, b):
| 64 | 64 | 24 | 10 | 53 | SpaceIm/pytorch | test/test_fx.py | Python | a_lifted_leaf | a_lifted_leaf | 59 | 60 | 59 | 59 | 422bca01cbe07c30776b1b185d7a7bc44e582583 | bigcode/the-stack | train |
339900ca159f1f95d1eadc10 | train | class | class TestFX(JitTestCase):
def setUp(self):
if TEST_WITH_ROCM or IS_SANDCASTLE or IS_WINDOWS or IS_MACOS:
return
torch_root = Path(__file__).resolve().parent.parent
p = torch_root / 'build' / 'lib' / 'libtorchbind_test.so'
torch.ops.load_library(str(p))
def checkGrap... | class TestFX(JitTestCase):
| def setUp(self):
if TEST_WITH_ROCM or IS_SANDCASTLE or IS_WINDOWS or IS_MACOS:
return
torch_root = Path(__file__).resolve().parent.parent
p = torch_root / 'build' / 'lib' / 'libtorchbind_test.so'
torch.ops.load_library(str(p))
def checkGraphModule(self, m: torch.nn.M... | , "no torchvision")
class SimpleTest(torch.nn.Module):
def forward(self, x):
return torch.relu(x + 3.0)
def a_non_torch_leaf(a, b):
return a + b
# Test wrap() passing both a function name as well as a function
# directly
def a_lifted_leaf(a, b):
return a[0] + a[1] + b
wrap('a_lifted_leaf')
# Tes... | 256 | 256 | 17,397 | 8 | 247 | SpaceIm/pytorch | test/test_fx.py | Python | TestFX | TestFX | 92 | 2,219 | 92 | 92 | 6ad000c8b557657c63fcc23315b9c0d22c68042d | bigcode/the-stack | train |
6a2da95e293dd977df975dc6 | train | class | @declare(guid=guid("9640427c-7d03-4331-b8ee-fb77625bf381"), event_id=8, version=0)
class Microsoft_Windows_MSFTEDIT_8_0(Etw):
pattern = Struct(
"param" / Int32ul
)
| @declare(guid=guid("9640427c-7d03-4331-b8ee-fb77625bf381"), event_id=8, version=0)
class Microsoft_Windows_MSFTEDIT_8_0(Etw):
| pattern = Struct(
"param" / Int32ul
)
| (
"param" / Int32ul
)
@declare(guid=guid("9640427c-7d03-4331-b8ee-fb77625bf381"), event_id=8, version=0)
class Microsoft_Windows_MSFTEDIT_8_0(Etw):
| 64 | 64 | 68 | 52 | 12 | IMULMUL/etl-parser | etl/parsers/etw/Microsoft_Windows_MSFTEDIT.py | Python | Microsoft_Windows_MSFTEDIT_8_0 | Microsoft_Windows_MSFTEDIT_8_0 | 44 | 48 | 44 | 45 | 62f5ee9c7fdd0ba1c1a6163b5164910858644304 | bigcode/the-stack | train |
1e743680d2f5592f22ec455d | train | class | @declare(guid=guid("9640427c-7d03-4331-b8ee-fb77625bf381"), event_id=9, version=0)
class Microsoft_Windows_MSFTEDIT_9_0(Etw):
pattern = Struct(
"param" / Int32ul
)
| @declare(guid=guid("9640427c-7d03-4331-b8ee-fb77625bf381"), event_id=9, version=0)
class Microsoft_Windows_MSFTEDIT_9_0(Etw):
| pattern = Struct(
"param" / Int32ul
)
| (
"param" / Int32ul
)
@declare(guid=guid("9640427c-7d03-4331-b8ee-fb77625bf381"), event_id=9, version=0)
class Microsoft_Windows_MSFTEDIT_9_0(Etw):
| 64 | 64 | 68 | 52 | 12 | IMULMUL/etl-parser | etl/parsers/etw/Microsoft_Windows_MSFTEDIT.py | Python | Microsoft_Windows_MSFTEDIT_9_0 | Microsoft_Windows_MSFTEDIT_9_0 | 51 | 55 | 51 | 52 | 1d20d173bfc4006ab7bae7f1d589627f62918430 | bigcode/the-stack | train |
89645b6349f3e36972f635e6 | train | class | @declare(guid=guid("9640427c-7d03-4331-b8ee-fb77625bf381"), event_id=1, version=0)
class Microsoft_Windows_MSFTEDIT_1_0(Etw):
pattern = Struct(
"param1" / Int32ul,
"param2" / Int32ul
)
| @declare(guid=guid("9640427c-7d03-4331-b8ee-fb77625bf381"), event_id=1, version=0)
class Microsoft_Windows_MSFTEDIT_1_0(Etw):
| pattern = Struct(
"param1" / Int32ul,
"param2" / Int32ul
)
| .parsers.etw.core import Etw, declare, guid
@declare(guid=guid("9640427c-7d03-4331-b8ee-fb77625bf381"), event_id=1, version=0)
class Microsoft_Windows_MSFTEDIT_1_0(Etw):
| 64 | 64 | 79 | 52 | 11 | IMULMUL/etl-parser | etl/parsers/etw/Microsoft_Windows_MSFTEDIT.py | Python | Microsoft_Windows_MSFTEDIT_1_0 | Microsoft_Windows_MSFTEDIT_1_0 | 12 | 17 | 12 | 13 | fcefe34d9defddf3da6c857f8b6e3552866ba731 | bigcode/the-stack | train |
f627d80e31a239fb08d9912f | train | class | @declare(guid=guid("9640427c-7d03-4331-b8ee-fb77625bf381"), event_id=13, version=0)
class Microsoft_Windows_MSFTEDIT_13_0(Etw):
pattern = Struct(
"param1" / Int32ul,
"param2" / Int32ul
)
| @declare(guid=guid("9640427c-7d03-4331-b8ee-fb77625bf381"), event_id=13, version=0)
class Microsoft_Windows_MSFTEDIT_13_0(Etw):
| pattern = Struct(
"param1" / Int32ul,
"param2" / Int32ul
)
| "param2" / Int32ul
)
@declare(guid=guid("9640427c-7d03-4331-b8ee-fb77625bf381"), event_id=13, version=0)
class Microsoft_Windows_MSFTEDIT_13_0(Etw):
| 64 | 64 | 79 | 52 | 12 | IMULMUL/etl-parser | etl/parsers/etw/Microsoft_Windows_MSFTEDIT.py | Python | Microsoft_Windows_MSFTEDIT_13_0 | Microsoft_Windows_MSFTEDIT_13_0 | 66 | 71 | 66 | 67 | adebba0b6b60b4e6251bebbecc8aa8bf64c03170 | bigcode/the-stack | train |
5bfeba257e82892fa77f7a72 | train | class | @declare(guid=guid("9640427c-7d03-4331-b8ee-fb77625bf381"), event_id=2, version=0)
class Microsoft_Windows_MSFTEDIT_2_0(Etw):
pattern = Struct(
"param1" / Int32ul,
"param2" / Int32ul
)
| @declare(guid=guid("9640427c-7d03-4331-b8ee-fb77625bf381"), event_id=2, version=0)
class Microsoft_Windows_MSFTEDIT_2_0(Etw):
| pattern = Struct(
"param1" / Int32ul,
"param2" / Int32ul
)
| "param2" / Int32ul
)
@declare(guid=guid("9640427c-7d03-4331-b8ee-fb77625bf381"), event_id=2, version=0)
class Microsoft_Windows_MSFTEDIT_2_0(Etw):
| 64 | 64 | 79 | 52 | 12 | IMULMUL/etl-parser | etl/parsers/etw/Microsoft_Windows_MSFTEDIT.py | Python | Microsoft_Windows_MSFTEDIT_2_0 | Microsoft_Windows_MSFTEDIT_2_0 | 20 | 25 | 20 | 21 | 8819bae166e1de07fe79b755e850672422d6b502 | bigcode/the-stack | train |
7a13619d8020a211517f058f | train | class | @declare(guid=guid("9640427c-7d03-4331-b8ee-fb77625bf381"), event_id=6, version=0)
class Microsoft_Windows_MSFTEDIT_6_0(Etw):
pattern = Struct(
"param1" / Int32ul,
"param2" / Int32ul,
"param3" / Int32ul
)
| @declare(guid=guid("9640427c-7d03-4331-b8ee-fb77625bf381"), event_id=6, version=0)
class Microsoft_Windows_MSFTEDIT_6_0(Etw):
| pattern = Struct(
"param1" / Int32ul,
"param2" / Int32ul,
"param3" / Int32ul
)
| "param2" / Int32ul
)
@declare(guid=guid("9640427c-7d03-4331-b8ee-fb77625bf381"), event_id=6, version=0)
class Microsoft_Windows_MSFTEDIT_6_0(Etw):
| 64 | 64 | 89 | 52 | 12 | IMULMUL/etl-parser | etl/parsers/etw/Microsoft_Windows_MSFTEDIT.py | Python | Microsoft_Windows_MSFTEDIT_6_0 | Microsoft_Windows_MSFTEDIT_6_0 | 28 | 34 | 28 | 29 | 2344db3471357198841b056c216ebce3b63d96b1 | bigcode/the-stack | train |
94f61da0500074d8a4b36907 | train | class | @declare(guid=guid("9640427c-7d03-4331-b8ee-fb77625bf381"), event_id=7, version=0)
class Microsoft_Windows_MSFTEDIT_7_0(Etw):
pattern = Struct(
"param" / Int32ul
)
| @declare(guid=guid("9640427c-7d03-4331-b8ee-fb77625bf381"), event_id=7, version=0)
class Microsoft_Windows_MSFTEDIT_7_0(Etw):
| pattern = Struct(
"param" / Int32ul
)
| "param3" / Int32ul
)
@declare(guid=guid("9640427c-7d03-4331-b8ee-fb77625bf381"), event_id=7, version=0)
class Microsoft_Windows_MSFTEDIT_7_0(Etw):
| 64 | 64 | 68 | 52 | 12 | IMULMUL/etl-parser | etl/parsers/etw/Microsoft_Windows_MSFTEDIT.py | Python | Microsoft_Windows_MSFTEDIT_7_0 | Microsoft_Windows_MSFTEDIT_7_0 | 37 | 41 | 37 | 38 | bc32f53b3d5a6b15a3ba816f3e8cd00aa9cc603e | bigcode/the-stack | train |
d266eeebd77fe8380d86e728 | train | class | @declare(guid=guid("9640427c-7d03-4331-b8ee-fb77625bf381"), event_id=12, version=0)
class Microsoft_Windows_MSFTEDIT_12_0(Etw):
pattern = Struct(
"param1" / Int32ul,
"param2" / Int32ul
)
| @declare(guid=guid("9640427c-7d03-4331-b8ee-fb77625bf381"), event_id=12, version=0)
class Microsoft_Windows_MSFTEDIT_12_0(Etw):
| pattern = Struct(
"param1" / Int32ul,
"param2" / Int32ul
)
| (
"param" / Int32ul
)
@declare(guid=guid("9640427c-7d03-4331-b8ee-fb77625bf381"), event_id=12, version=0)
class Microsoft_Windows_MSFTEDIT_12_0(Etw):
| 64 | 64 | 79 | 52 | 12 | IMULMUL/etl-parser | etl/parsers/etw/Microsoft_Windows_MSFTEDIT.py | Python | Microsoft_Windows_MSFTEDIT_12_0 | Microsoft_Windows_MSFTEDIT_12_0 | 58 | 63 | 58 | 59 | f71fb05e8c8f6ad1e4b4c703a695c3335c5f2404 | bigcode/the-stack | train |
297dfafca5e36a3a15466662 | train | class | class Dummy(Field):
""" A black hole which consumes all values without error. Use to mark
sections of the configuration which have yet to be implemented and should
be ignored.
"""
def validate_and_normalize(self, instance, root=None):
return []
def process_source(self, source):
... | class Dummy(Field):
| """ A black hole which consumes all values without error. Use to mark
sections of the configuration which have yet to be implemented and should
be ignored.
"""
def validate_and_normalize(self, instance, root=None):
return []
def process_source(self, source):
pass
def __get... | ):
return self._forms[key]
def is_unset(self, instance=None):
return all([c.is_unset(self) for c in self._forms])
def _to_dict_value(self, instance=None):
return [c.to_dict() for c in self._forms]
class Dummy(Field):
| 64 | 64 | 111 | 4 | 60 | ihmeuw/cascade-at | src/cascade_at/core/form/fields.py | Python | Dummy | Dummy | 95 | 114 | 95 | 95 | 630838b6273129d3830e7a8793c5f4c9391f261e | bigcode/the-stack | train |
48de4d435794b29fb2a74000 | train | class | class NativeListField(SimpleTypeField):
"""Because we already have a ListField for space separated
strings which become lists, this field type should be used
when the .json config returns a native python list."""
def __init__(self, *args, **kwargs):
super().__init__(list, *args, **kwargs)
| class NativeListField(SimpleTypeField):
| """Because we already have a ListField for space separated
strings which become lists, this field type should be used
when the .json config returns a native python list."""
def __init__(self, *args, **kwargs):
super().__init__(list, *args, **kwargs)
| init__(self, *args, **kwargs):
super().__init__(float, *args, **kwargs)
class StrField(SimpleTypeField):
def __init__(self, *args, **kwargs):
super().__init__(str, *args, **kwargs)
class NativeListField(SimpleTypeField):
| 64 | 64 | 72 | 8 | 56 | ihmeuw/cascade-at | src/cascade_at/core/form/fields.py | Python | NativeListField | NativeListField | 33 | 38 | 33 | 33 | d524c585a38edaeda04a5f72d9672e6a1d63e607 | bigcode/the-stack | train |
e65eb10f484a9bc2fe050c5e | train | class | class IntField(SimpleTypeField):
def __init__(self, *args, **kwargs):
super().__init__(int, *args, **kwargs)
| class IntField(SimpleTypeField):
| def __init__(self, *args, **kwargs):
super().__init__(int, *args, **kwargs)
| TypeField, NO_VALUE)
from cascade_at.core.log import get_loggers
LOG = get_loggers(__name__)
class BoolField(SimpleTypeField):
def __init__(self, *args, **kwargs):
super().__init__(bool, *args, **kwargs)
class IntField(SimpleTypeField):
| 64 | 64 | 33 | 7 | 57 | ihmeuw/cascade-at | src/cascade_at/core/form/fields.py | Python | IntField | IntField | 18 | 20 | 18 | 18 | 6d06bb420104c8e0e825bd236ff5fab5c14c77ae | bigcode/the-stack | train |
c46219af993108aa30f2399c | train | class | class FloatField(SimpleTypeField):
def __init__(self, *args, **kwargs):
super().__init__(float, *args, **kwargs)
| class FloatField(SimpleTypeField):
| def __init__(self, *args, **kwargs):
super().__init__(float, *args, **kwargs)
| __init__(self, *args, **kwargs):
super().__init__(bool, *args, **kwargs)
class IntField(SimpleTypeField):
def __init__(self, *args, **kwargs):
super().__init__(int, *args, **kwargs)
class FloatField(SimpleTypeField):
| 64 | 64 | 33 | 7 | 57 | ihmeuw/cascade-at | src/cascade_at/core/form/fields.py | Python | FloatField | FloatField | 23 | 25 | 23 | 23 | b76b1d30afe0fe6ebb70518033be1f7ad557dceb | bigcode/the-stack | train |
927cf0cec1da50f28dc66fa4 | train | class | class StringListField(ListField):
def _validate_and_normalize(self, instance, value):
if isinstance(value, str):
values = [val.strip() for val in split(
rf'{self.separator}+', value.strip())]
else:
# This case hits when there's only a single numerical value in... | class StringListField(ListField):
| def _validate_and_normalize(self, instance, value):
if isinstance(value, str):
values = [val.strip() for val in split(
rf'{self.separator}+', value.strip())]
else:
# This case hits when there's only a single numerical value in the
# list because Ep... | validate_and_normalize(instance, item)
if error:
errors.append(error)
else:
new_values.append(new_value)
if errors:
return None, "Errors in items: [" + ", ".join(errors) + "]"
return new_values, None
class StringListField(ListField):
| 64 | 64 | 138 | 7 | 56 | ihmeuw/cascade-at | src/cascade_at/core/form/fields.py | Python | StringListField | StringListField | 171 | 185 | 171 | 171 | b6601ca6bbdbc551de9437f501ec430f21409cb6 | bigcode/the-stack | train |
8857a7d330a22d40ef81e058 | train | class | class FormList(Form):
""" This represents a homogeneous list of forms. For example, it might be
used to contain a list of priors within a smoothing grid.
Args:
inner_form_constructor: A factory which produces an instance of a Form
subclass. Most often it will just be the Form subclass itself.
... | class FormList(Form):
| """ This represents a homogeneous list of forms. For example, it might be
used to contain a list of priors within a smoothing grid.
Args:
inner_form_constructor: A factory which produces an instance of a Form
subclass. Most often it will just be the Form subclass itself.
"""
def __init... | float, *args, **kwargs)
class StrField(SimpleTypeField):
def __init__(self, *args, **kwargs):
super().__init__(str, *args, **kwargs)
class NativeListField(SimpleTypeField):
"""Because we already have a ListField for space separated
strings which become lists, this field type should be used
w... | 118 | 118 | 396 | 5 | 113 | ihmeuw/cascade-at | src/cascade_at/core/form/fields.py | Python | FormList | FormList | 41 | 92 | 41 | 41 | 1cc854baedce115ba47464a0310e334a6e011f59 | bigcode/the-stack | train |
72dbe304f3167b8db4b76d55 | train | class | class StrField(SimpleTypeField):
def __init__(self, *args, **kwargs):
super().__init__(str, *args, **kwargs)
| class StrField(SimpleTypeField):
| def __init__(self, *args, **kwargs):
super().__init__(str, *args, **kwargs)
| __init__(self, *args, **kwargs):
super().__init__(int, *args, **kwargs)
class FloatField(SimpleTypeField):
def __init__(self, *args, **kwargs):
super().__init__(float, *args, **kwargs)
class StrField(SimpleTypeField):
| 64 | 64 | 33 | 7 | 57 | ihmeuw/cascade-at | src/cascade_at/core/form/fields.py | Python | StrField | StrField | 28 | 30 | 28 | 28 | be6530f1ce0fb8509e0e2c12879d7dcea3e3dba9 | bigcode/the-stack | train |
5e513d86170d369df55661f8 | train | class | class BoolField(SimpleTypeField):
def __init__(self, *args, **kwargs):
super().__init__(bool, *args, **kwargs)
| class BoolField(SimpleTypeField):
| def __init__(self, *args, **kwargs):
super().__init__(bool, *args, **kwargs)
| the general tools in abstract_form,
mostly useful field types.
"""
from re import split
from cascade_at.core.form.abstract_form import (
Form, Field, SimpleTypeField, NO_VALUE)
from cascade_at.core.log import get_loggers
LOG = get_loggers(__name__)
class BoolField(SimpleTypeField):
| 64 | 64 | 33 | 7 | 57 | ihmeuw/cascade-at | src/cascade_at/core/form/fields.py | Python | BoolField | BoolField | 13 | 15 | 13 | 13 | 5894ce16d2829322412950e5b22535ec0b367799 | bigcode/the-stack | train |
51c9dc965191ee6a1a60b765 | train | class | class OptionField(SimpleTypeField):
""" A field which will only accept values from a predefined set.
Args:
options (list): The list of options to choose from
constructor: A function which takes a string and returns the expected
type. Behaves as the constructor for SimpleTypeField. Def... | class OptionField(SimpleTypeField):
| """ A field which will only accept values from a predefined set.
Args:
options (list): The list of options to choose from
constructor: A function which takes a string and returns the expected
type. Behaves as the constructor for SimpleTypeField. Defaults to str
"""
def __init... | return []
def process_source(self, source):
pass
def __get__(self, instance, owner):
return NO_VALUE
def __set__(self, instance, value):
pass
def is_unset(self, instance=None):
return True
class OptionField(SimpleTypeField):
| 64 | 64 | 176 | 7 | 56 | ihmeuw/cascade-at | src/cascade_at/core/form/fields.py | Python | OptionField | OptionField | 117 | 138 | 117 | 117 | 2c3203b7f55a4d9d32d5c6b3ca1ee72ebb6e2331 | bigcode/the-stack | train |
f8938624974677eaa0046b2a | train | class | class ListField(SimpleTypeField):
""" A field which takes a string containing values demarcated by some
separator and transforms them into a homogeneous list of items of an
expected type.
Args:
constructor: A function which takes a string and returns the expected
type. Behaves as the ... | class ListField(SimpleTypeField):
| """ A field which takes a string containing values demarcated by some
separator and transforms them into a homogeneous list of items of an
expected type.
Args:
constructor: A function which takes a string and returns the expected
type. Behaves as the constructor for SimpleTypeField. D... | instance, value):
new_value, error = super()._validate_and_normalize(instance, value)
if error:
return None, error
if new_value not in self.options:
return None, f"Invalid option '{new_value}'"
return new_value, None
class ListField(SimpleTypeField):
| 67 | 67 | 226 | 7 | 59 | ihmeuw/cascade-at | src/cascade_at/core/form/fields.py | Python | ListField | ListField | 141 | 168 | 141 | 141 | 08659ec358cf82292d1090247b1fd4412e1e96b6 | bigcode/the-stack | train |
77889c6e7d411dbc26fb0e7c | train | function | def gather_org_admin_recipients(organization, exclude_username_list):
"""
Gather email recipients from an organnization's admin users who
have email notifications enabled and are not in the exclusion list.
"""
org_admin_recipients = []
members = toolkit.get_action('member_list')({'ignore_auth': ... | def gather_org_admin_recipients(organization, exclude_username_list):
| """
Gather email recipients from an organnization's admin users who
have email notifications enabled and are not in the exclusion list.
"""
org_admin_recipients = []
members = toolkit.get_action('member_list')({'ignore_auth': True}, {
'id': organization.get('id'),
'object_type': ... | _streams_email_notifications
and sysadmin.name not in exclude_username_list):
sysadmin_recipients.append({
'name': sysadmin.name,
'email': sysadmin.email
})
return sysadmin_recipients
def gather_org_admin_recipients(organization, exclude_username_l... | 64 | 64 | 212 | 14 | 49 | OpenGov-OpenData/ckanext-harvestnotification | ckanext/harvestnotification/utils.py | Python | gather_org_admin_recipients | gather_org_admin_recipients | 23 | 46 | 23 | 23 | 8d5fd6ac9f4f689d1f0c49c54c7ae18d5f14fe94 | bigcode/the-stack | train |
328a98bb9c7b35853a608deb | train | function | def gather_sysadmin_recipients(model, exclude_username_list):
"""
Gather email recipients from an sysadmin users who
have email notifications enabled and are not in the exclusion list.
"""
sysadmin_recipients = []
sysadmins = model.Session.query(model.User).filter(
model.User.sysadmin ==... | def gather_sysadmin_recipients(model, exclude_username_list):
| """
Gather email recipients from an sysadmin users who
have email notifications enabled and are not in the exclusion list.
"""
sysadmin_recipients = []
sysadmins = model.Session.query(model.User).filter(
model.User.sysadmin == True
).all()
for sysadmin in sysadmins:
if (s... | import ckan.plugins.toolkit as toolkit
def gather_sysadmin_recipients(model, exclude_username_list):
| 22 | 64 | 143 | 13 | 8 | OpenGov-OpenData/ckanext-harvestnotification | ckanext/harvestnotification/utils.py | Python | gather_sysadmin_recipients | gather_sysadmin_recipients | 4 | 21 | 4 | 4 | 78c28cd9cd45f3030b36399dc03dc67ab820f575 | bigcode/the-stack | train |
32125f5d1640bbc47a15b656 | train | function | def get_available_languages():
handle = tesseract_raw.init()
try:
return tesseract_raw.get_available_languages(handle)
finally:
tesseract_raw.cleanup(handle)
| def get_available_languages():
| handle = tesseract_raw.init()
try:
return tesseract_raw.get_available_languages(handle)
finally:
tesseract_raw.cleanup(handle)
| 03
if version[0] < 3 or (version[0] == 3 and version[1] < 4):
logger.warning("Unsupported version [%s]" % ".".join([str(r) for r in version]))
return False
return True
def get_available_languages():
| 64 | 64 | 39 | 5 | 58 | xingkong0113/bookworm | bookworm/ocr_engines/tesseract_ocr_engine/pyocr/libtesseract/__init__.py | Python | get_available_languages | get_available_languages | 279 | 284 | 279 | 279 | 32c429c3284e9166294bbf84c0f67b2cc8353e88 | bigcode/the-stack | train |
d4971beb06543abbd20043bc | train | function | def get_name():
return "Tesseract (C-API)"
| def get_name():
| return "Tesseract (C-API)"
| ,
tesseract_raw.Orientation.PAGE_DOWN: 180,
tesseract_raw.Orientation.PAGE_LEFT: 270,
}[os["orientation"]]
return {"angle": orientation, "confidence": os["confidence"]}
finally:
tesseract_raw.cleanup(handle)
def get_name():
| 64 | 64 | 15 | 4 | 60 | xingkong0113/bookworm | bookworm/ocr_engines/tesseract_ocr_engine/pyocr/libtesseract/__init__.py | Python | get_name | get_name | 68 | 69 | 68 | 68 | 9d28dc5299e3385f6a6766c60ec977073b90a785 | bigcode/the-stack | train |
b38a852afac0a80445ccacbe | train | function | def get_version():
version = tesseract_raw.get_version()
version = version.split(" ", 1)[0]
# cut off "dev" string if exists for proper int conversion
index = version.find("dev")
if index != -1:
version = version[:index]
version = version.split(".")
major = digits_only(version[0])
... | def get_version():
| version = tesseract_raw.get_version()
version = version.split(" ", 1)[0]
# cut off "dev" string if exists for proper int conversion
index = version.find("dev")
if index != -1:
version = version[:index]
version = version.split(".")
major = digits_only(version[0])
minor = digits_... | % ".".join([str(r) for r in version]))
return False
return True
def get_available_languages():
handle = tesseract_raw.init()
try:
return tesseract_raw.get_available_languages(handle)
finally:
tesseract_raw.cleanup(handle)
def get_version():
| 64 | 64 | 121 | 4 | 60 | xingkong0113/bookworm | bookworm/ocr_engines/tesseract_ocr_engine/pyocr/libtesseract/__init__.py | Python | get_version | get_version | 287 | 302 | 287 | 287 | 60f7035e430160b41a66588e8035a4bae3a60b71 | bigcode/the-stack | train |
88b06b5c41f66acc83b2e699 | train | function | def can_detect_orientation():
langs = get_available_languages()
return "osd" in langs
| def can_detect_orientation():
| langs = get_available_languages()
return "osd" in langs
| __)
__all__ = [
"can_detect_orientation",
"detect_orientation",
"get_available_builders",
"get_available_languages",
"get_name",
"get_version",
"image_to_string",
"is_available",
"TesseractError",
]
def can_detect_orientation():
| 64 | 64 | 21 | 5 | 59 | xingkong0113/bookworm | bookworm/ocr_engines/tesseract_ocr_engine/pyocr/libtesseract/__init__.py | Python | can_detect_orientation | can_detect_orientation | 40 | 42 | 40 | 40 | 00495b330840a8ecea42a471d02d8bc5f9484831 | bigcode/the-stack | train |
0a8b39776aecda900dce0848 | train | function | def get_available_builders():
return [
builders.TextBuilder,
builders.WordBoxBuilder,
builders.DigitBuilder,
builders.LineBoxBuilder,
builders.DigitLineBoxBuilder,
]
| def get_available_builders():
| return [
builders.TextBuilder,
builders.WordBoxBuilder,
builders.DigitBuilder,
builders.LineBoxBuilder,
builders.DigitLineBoxBuilder,
]
| _raw.Orientation.PAGE_LEFT: 270,
}[os["orientation"]]
return {"angle": orientation, "confidence": os["confidence"]}
finally:
tesseract_raw.cleanup(handle)
def get_name():
return "Tesseract (C-API)"
def get_available_builders():
| 63 | 64 | 42 | 6 | 57 | xingkong0113/bookworm | bookworm/ocr_engines/tesseract_ocr_engine/pyocr/libtesseract/__init__.py | Python | get_available_builders | get_available_builders | 72 | 79 | 72 | 72 | 73b8c46391267cb6d12571ebc9bee5e7350b4b90 | bigcode/the-stack | train |
d728a9b22b0826c005a0c446 | train | function | def detect_orientation(image, lang=None):
# C-API with Tesseract 4 segfaults if running OSD_ONLY
# psm mode with other than osd language
# lang argument left purely for compatibility reasons
# tested on 4.0.0-rc2
handle = tesseract_raw.init(lang="osd")
try:
tesseract_raw.set_page_seg_mod... | def detect_orientation(image, lang=None):
# C-API with Tesseract 4 segfaults if running OSD_ONLY
# psm mode with other than osd language
# lang argument left purely for compatibility reasons
# tested on 4.0.0-rc2
| handle = tesseract_raw.init(lang="osd")
try:
tesseract_raw.set_page_seg_mode(handle, tesseract_raw.PageSegMode.OSD_ONLY)
tesseract_raw.set_image(handle, image)
os = tesseract_raw.detect_os(handle)
if os["confidence"] <= 0:
raise TesseractError("no script", "no script ... | "osd" in langs
def detect_orientation(image, lang=None):
# C-API with Tesseract 4 segfaults if running OSD_ONLY
# psm mode with other than osd language
# lang argument left purely for compatibility reasons
# tested on 4.0.0-rc2
| 71 | 71 | 238 | 64 | 6 | xingkong0113/bookworm | bookworm/ocr_engines/tesseract_ocr_engine/pyocr/libtesseract/__init__.py | Python | detect_orientation | detect_orientation | 45 | 65 | 45 | 49 | b0aaa5782eb11e1edc694af76cd5d073d329f9c5 | bigcode/the-stack | train |
a4e7d268f46fb041413cdbc8 | train | function | def _tess_box_to_pyocr_box(box):
return (
(box[0], box[1]),
(box[2], box[3]),
)
| def _tess_box_to_pyocr_box(box):
| return (
(box[0], box[1]),
(box[2], box[3]),
)
| "Tesseract (C-API)"
def get_available_builders():
return [
builders.TextBuilder,
builders.WordBoxBuilder,
builders.DigitBuilder,
builders.LineBoxBuilder,
builders.DigitLineBoxBuilder,
]
def _tess_box_to_pyocr_box(box):
| 63 | 64 | 36 | 11 | 52 | xingkong0113/bookworm | bookworm/ocr_engines/tesseract_ocr_engine/pyocr/libtesseract/__init__.py | Python | _tess_box_to_pyocr_box | _tess_box_to_pyocr_box | 82 | 86 | 82 | 82 | 7e53bd7e6dbbdbaa97e6ca55653bc371d0aac891 | bigcode/the-stack | train |
7782676c1809177a55a0e3c3 | train | function | def is_available():
available = tesseract_raw.is_available()
if not available:
return False
version = get_version()
# C-API with Tesseract <= 3.02 segfaults sometimes
# (seen with Debian stable + Paperwork)
# not tested with 3.03
if version[0] < 3 or (version[0] == 3 and version[1] ... | def is_available():
| available = tesseract_raw.is_available()
if not available:
return False
version = get_version()
# C-API with Tesseract <= 3.02 segfaults sometimes
# (seen with Debian stable + Paperwork)
# not tested with 3.03
if version[0] < 3 or (version[0] == 3 and version[1] < 4):
logger... | _name(handle, input_file)
tesseract_raw.recognize(handle)
tesseract_raw.add_renderer_image(handle, renderer)
tesseract_raw.end_document(renderer)
finally:
tesseract_raw.cleanup(handle)
if renderer:
tesseract_raw.cleanup(rendere... | 64 | 64 | 126 | 4 | 60 | xingkong0113/bookworm | bookworm/ocr_engines/tesseract_ocr_engine/pyocr/libtesseract/__init__.py | Python | is_available | is_available | 264 | 276 | 264 | 264 | 01264c029164c171b3374c51fb935780aafc69e5 | bigcode/the-stack | train |
c56998be1c84f091c8d34130 | train | function | def image_to_pdf(image, output_file, lang=None, input_file="stdin", textonly=False):
"""
Creates pdf file with embeded text based on OCR from an image
Args:
image: image to be converted
output_file: path to the file that will be created, `.pdf` extension
should not be specified
... | def image_to_pdf(image, output_file, lang=None, input_file="stdin", textonly=False):
| """
Creates pdf file with embeded text based on OCR from an image
Args:
image: image to be converted
output_file: path to the file that will be created, `.pdf` extension
should not be specified
lang: three letter language code. For available languages see
htt... | if last_word_in_line:
builder.end_line()
if not tesseract_raw.page_iterator_next(page_iterator, lvl_word):
break
finally:
tesseract_raw.cleanup(handle)
return builder.get_output()
def image_to_pdf(image, output_file, lang=None, input_file="stdin", text... | 68 | 68 | 229 | 21 | 47 | xingkong0113/bookworm | bookworm/ocr_engines/tesseract_ocr_engine/pyocr/libtesseract/__init__.py | Python | image_to_pdf | image_to_pdf | 161 | 181 | 161 | 161 | 290f98387b8c9f102cb6fea75fb0ebd69b906685 | bigcode/the-stack | train |
d7be037ae2040d8baec028f2 | train | class | class LibtesseractPdfBuilder(object):
"""
Creates a pdf file with embeded text based on OCR from one or more images.
"""
def __init__(self):
self.images = []
self.output_file = None
self.lang = None
self.text_only = False
def set_lang(self, lang):
"""
... | class LibtesseractPdfBuilder(object):
| """
Creates a pdf file with embeded text based on OCR from one or more images.
"""
def __init__(self):
self.images = []
self.output_file = None
self.lang = None
self.text_only = False
def set_lang(self, lang):
"""
Language to be used for ocr.
... | ://github.com/tesseract-ocr/tesseract/blob/master/doc/tesseract.1.asc#languages.
Defaults to None.
input_file: path to the image file that should be beneath the text in
output pdf. If not specified (stdin, incorrect file) output pdf is
correct but tesseract writes some errors... | 150 | 150 | 501 | 9 | 141 | xingkong0113/bookworm | bookworm/ocr_engines/tesseract_ocr_engine/pyocr/libtesseract/__init__.py | Python | LibtesseractPdfBuilder | LibtesseractPdfBuilder | 184 | 261 | 184 | 184 | 9489e758503cb7c8b33ec9064697de44b4acab7a | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.