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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a76d18df379244be4f02911a | train | class | class ISignalExecutor(Protocol):
def execute(self, signal: Signal) -> None:
pass
| class ISignalExecutor(Protocol):
| def execute(self, signal: Signal) -> None:
pass
| from typing import Protocol
from tinkoff.invest.strategies.base.signal import Signal
class ISignalExecutor(Protocol):
| 25 | 64 | 22 | 7 | 17 | Tinkoff/invest-python | tinkoff/invest/strategies/base/signal_executor_interface.py | Python | ISignalExecutor | ISignalExecutor | 6 | 8 | 6 | 6 | b588431bc6ab6b2b7ba318f8d7d13a59ac84043b | bigcode/the-stack | train |
25cbb1030e43b40749edb5e2 | train | class | class FergusonFrontend(pykka.ThreadingActor, CoreListener):
def __init__(self, core):
super(FergusonFrontend, self).__init__()
self.core = core
| class FergusonFrontend(pykka.ThreadingActor, CoreListener):
| def __init__(self, core):
super(FergusonFrontend, self).__init__()
self.core = core
| import pykka
from mopidy.core import CoreListener
logger = logging.getLogger('mopidy_ferguson')
class FergusonFrontend(pykka.ThreadingActor, CoreListener):
| 39 | 64 | 38 | 12 | 27 | mattbrailsford/mopidy-ferguson | mopidy_ferguson/frontend.py | Python | FergusonFrontend | FergusonFrontend | 7 | 10 | 7 | 7 | bfd5f44348cf3ecc9d6e901b39a82510eece2e8a | bigcode/the-stack | train |
c6de29b9053551f5c8a9e9de | train | class | class ScopedMetaGraphTest(test.TestCase):
def _testScopedExport(self, test_dir, exported_filenames):
graph = ops.Graph()
with graph.as_default():
# Creates an inference graph.
# Hidden 1
colocate_constraint = constant_op.constant(1.2, name="constraint")
images = constant_op.constant(
... | class ScopedMetaGraphTest(test.TestCase):
| def _testScopedExport(self, test_dir, exported_filenames):
graph = ops.Graph()
with graph.as_default():
# Creates an inference graph.
# Hidden 1
colocate_constraint = constant_op.constant(1.2, name="constraint")
images = constant_op.constant(
1.2, dtypes.float32, shape=[100, ... | If we call the function on a constant, there should be two ops
_ = f1(constant_op.constant(7))
op_list = meta_graph.stripped_op_list_for_graph(ops.get_default_graph()
.as_graph_def())
self.assertEqual(["Const", "Square"], [op.name for op in op_lis... | 256 | 256 | 3,894 | 9 | 247 | AlexChrisF/udacity | tensorflow/python/framework/meta_graph_test.py | Python | ScopedMetaGraphTest | ScopedMetaGraphTest | 154 | 523 | 154 | 155 | b9437854bbef3007167adefccb0b8bf53ed7b13e | bigcode/the-stack | train |
a9cdd7088ed4595cb4debebc | train | class | class SimpleMetaGraphTest(test.TestCase):
def testNoVariables(self):
test_dir = _TestDir("no_variables")
filename = os.path.join(test_dir, "metafile")
input_feed_value = -10 # Arbitrary input value for feed_dict.
orig_graph = ops.Graph()
with self.test_session(graph=orig_graph) as sess:
... | class SimpleMetaGraphTest(test.TestCase):
| def testNoVariables(self):
test_dir = _TestDir("no_variables")
filename = os.path.join(test_dir, "metafile")
input_feed_value = -10 # Arbitrary input value for feed_dict.
orig_graph = ops.Graph()
with self.test_session(graph=orig_graph) as sess:
# Create a minimal graph with zero variable... | for tensorflow.python.framework.meta_graph.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import os.path
import random
import shutil
from tensorflow.core.framework import graph_pb2
from tensorflow.python.framework import constant_op
fr... | 256 | 256 | 894 | 9 | 246 | AlexChrisF/udacity | tensorflow/python/framework/meta_graph_test.py | Python | SimpleMetaGraphTest | SimpleMetaGraphTest | 57 | 151 | 57 | 58 | 25e38ba76639abd3e74aae80adf8c5b54aeafc62 | bigcode/the-stack | train |
fdd13b7fee5ca93c2fa59b38 | train | function | def _TestDir(test_name):
test_dir = os.path.join(test.get_temp_dir(), test_name)
if os.path.exists(test_dir):
shutil.rmtree(test_dir)
gfile.MakeDirs(test_dir)
return test_dir
| def _TestDir(test_name):
| test_dir = os.path.join(test.get_temp_dir(), test_name)
if os.path.exists(test_dir):
shutil.rmtree(test_dir)
gfile.MakeDirs(test_dir)
return test_dir
|
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import gfile
from tensorflow.python.platform import test
from tensorflow.python.training import queue_runner_impl
# pylint: disable=invalid-... | 64 | 64 | 50 | 7 | 56 | AlexChrisF/udacity | tensorflow/python/framework/meta_graph_test.py | Python | _TestDir | _TestDir | 46 | 51 | 46 | 46 | 0b7d158a970473a17faded72bfaf4010c3aebf25 | bigcode/the-stack | train |
9ac1ab1c2b7e4d906ebb2288 | train | function | def canTransform2(start, end):
n = len(start)
i, j = 0, 0
while i < n or j < n:
while i < n and start[i] == "X": i += 1
while j < n and end[j] == "X": j += 1
if (i < n) != (j < n): return False
if i < n and j < n:
if (start[i] != end[j]) or (start[i] == "L" and... | def canTransform2(start, end):
| n = len(start)
i, j = 0, 0
while i < n or j < n:
while i < n and start[i] == "X": i += 1
while j < n and end[j] == "X": j += 1
if (i < n) != (j < n): return False
if i < n and j < n:
if (start[i] != end[j]) or (start[i] == "L" and i < j) or (end[j] == "R" and i... | if end[i] == "L"]
for s, e in zip(startR, endR):
if s > e: return False
for s, e in zip(startL, endL):
if s < e: return False
return True
def canTransform2(start, end):
| 64 | 64 | 155 | 8 | 55 | KanegaeGabriel/ye-olde-interview-prep-grind | LeetCode/0777_swap_adjacent_in_lr_string.py | Python | canTransform2 | canTransform2 | 20 | 37 | 20 | 20 | a485d3fa2289fb1ab186e0c7d832f15f01e66a50 | bigcode/the-stack | train |
80a6eed6a026cd1fd0426285 | train | function | def canTransform1(start, end):
startX = "".join([c for c in start if c != "X"])
endX = "".join([c for c in end if c != "X"])
if startX != endX: return False
startR = [i for i in range(len(start)) if start[i] == "R"]
startL = [i for i in range(len(start)) if start[i] == "L"]
endR = [i for i... | def canTransform1(start, end):
| startX = "".join([c for c in start if c != "X"])
endX = "".join([c for c in end if c != "X"])
if startX != endX: return False
startR = [i for i in range(len(start)) if start[i] == "R"]
startL = [i for i in range(len(start)) if start[i] == "L"]
endR = [i for i in range(len(end)) if end[i] =... | def canTransform1(start, end):
| 8 | 64 | 188 | 8 | 0 | KanegaeGabriel/ye-olde-interview-prep-grind | LeetCode/0777_swap_adjacent_in_lr_string.py | Python | canTransform1 | canTransform1 | 1 | 18 | 1 | 1 | b9d9bf8856fc8c3679ed199a9b0d26e82a9ea011 | bigcode/the-stack | train |
1475e3e1c2aa0f5589d3f8cb | train | function | def t_string_tickx(t):
r"'(?:[^\\'\n]|\\.)*'"
t.type = 'string'
t.value = fml(t.lexer.module, t.value)
return t
| def t_string_tickx(t):
| r"'(?:[^\\'\n]|\\.)*'"
t.type = 'string'
t.value = fml(t.lexer.module, t.value)
return t
| (t.lexer.module, t.value, 1)
return t
def t_multiline_string_quotex(t):
r'''""".*?"""'''
t.type = 'string'
t.value = fml(t.lexer.module, t.value, 1)
return t
def t_string_tickx(t):
| 64 | 64 | 41 | 7 | 56 | nicolasessisbreton/fython | fython/lex/translate_fml.py | Python | t_string_tickx | t_string_tickx | 27 | 31 | 27 | 27 | ae9ddb49f83dc8515f1cc80c01161cd06228acf6 | bigcode/the-stack | train |
702440bd15935732edd243aa | train | function | def t_interpolationx(t):
r'\|.*?\|'
t.type = 'code'
return t
| def t_interpolationx(t):
| r'\|.*?\|'
t.type = 'code'
return t
| from .config import *
from ply.lex import lex as plex
from fython.fml import *
tokens = (
'string',
'code',
)
def t_interpolationx(t):
| 38 | 64 | 23 | 7 | 31 | nicolasessisbreton/fython | fython/lex/translate_fml.py | Python | t_interpolationx | t_interpolationx | 10 | 13 | 10 | 10 | bb94aeb311894d0bad8509dad0fb86df1950c419 | bigcode/the-stack | train |
096c9678cb8a92700c304167 | train | function | def t_multiline_string_quotex(t):
r'''""".*?"""'''
t.type = 'string'
t.value = fml(t.lexer.module, t.value, 1)
return t
| def t_multiline_string_quotex(t):
| r'''""".*?"""'''
t.type = 'string'
t.value = fml(t.lexer.module, t.value, 1)
return t
| ?\|'
t.type = 'code'
return t
def t_multiline_string_tickx(t):
r"""'''.*?'''"""
t.type = 'string'
t.value = fml(t.lexer.module, t.value, 1)
return t
def t_multiline_string_quotex(t):
| 64 | 64 | 43 | 10 | 53 | nicolasessisbreton/fython | fython/lex/translate_fml.py | Python | t_multiline_string_quotex | t_multiline_string_quotex | 21 | 25 | 21 | 21 | 6ac2d3988c56aa0d726c2f793eacd43c55b70672 | bigcode/the-stack | train |
af1b1c60cbbbdba0e1344d7c | train | function | def t_string_quotex(t):
r'"(?:[^\\"\n]|\\.)*"'
t.type = 'string'
t.value = fml(t.lexer.module, t.value)
return t
| def t_string_quotex(t):
| r'"(?:[^\\"\n]|\\.)*"'
t.type = 'string'
t.value = fml(t.lexer.module, t.value)
return t
| ml(t.lexer.module, t.value, 1)
return t
def t_string_tickx(t):
r"'(?:[^\\'\n]|\\.)*'"
t.type = 'string'
t.value = fml(t.lexer.module, t.value)
return t
def t_string_quotex(t):
| 64 | 64 | 42 | 8 | 55 | nicolasessisbreton/fython | fython/lex/translate_fml.py | Python | t_string_quotex | t_string_quotex | 33 | 37 | 33 | 33 | f04b52c17d37f5aa8e7babedcbe91211b0d8998b | bigcode/the-stack | train |
848ebe758e34aaf918ef243e | train | function | def translate_fml(module):
lexer = main_lexer.clone()
lexer.module = module
lexer.input(module.source_with_invisible)
r = ''
t = lexer.token()
while t:
r += t.value
t = lexer.token()
module.source_with_invisible_and_fml = r | def translate_fml(module):
| lexer = main_lexer.clone()
lexer.module = module
lexer.input(module.source_with_invisible)
r = ''
t = lexer.token()
while t:
r += t.value
t = lexer.token()
module.source_with_invisible_and_fml = r | _error(t):
t.lexer.module.throw(
error = err.fml_error,
line = t.lexer.lineno,
position = t.lexer.lexpos,
lexem = repr(t.value),
)
main_lexer = plex(reflags = re.DOTALL )
def translate_fml(module):
| 64 | 64 | 62 | 6 | 58 | nicolasessisbreton/fython | fython/lex/translate_fml.py | Python | translate_fml | translate_fml | 53 | 64 | 53 | 53 | 069251ac5d2e8d47e5d83e09f2e4a82fd6f9c62a | bigcode/the-stack | train |
69d86c39d465f9d1018ed0da | train | function | def t_multiline_string_tickx(t):
r"""'''.*?'''"""
t.type = 'string'
t.value = fml(t.lexer.module, t.value, 1)
return t
| def t_multiline_string_tickx(t):
| r"""'''.*?'''"""
t.type = 'string'
t.value = fml(t.lexer.module, t.value, 1)
return t
| from .config import *
from ply.lex import lex as plex
from fython.fml import *
tokens = (
'string',
'code',
)
def t_interpolationx(t):
r'\|.*?\|'
t.type = 'code'
return t
def t_multiline_string_tickx(t):
| 63 | 64 | 42 | 9 | 53 | nicolasessisbreton/fython | fython/lex/translate_fml.py | Python | t_multiline_string_tickx | t_multiline_string_tickx | 15 | 19 | 15 | 15 | f8ce30d6ce2ae566d1b3d9e0242c7512de378c8f | bigcode/the-stack | train |
6bbed7459b96ba6cdb25f57b | train | function | def t_code(t):
r"""[^'"\|]+"""
return t
| def t_code(t):
| r"""[^'"\|]+"""
return t
| '
t.value = fml(t.lexer.module, t.value)
return t
def t_string_quotex(t):
r'"(?:[^\\"\n]|\\.)*"'
t.type = 'string'
t.value = fml(t.lexer.module, t.value)
return t
def t_code(t):
| 64 | 64 | 16 | 5 | 58 | nicolasessisbreton/fython | fython/lex/translate_fml.py | Python | t_code | t_code | 39 | 41 | 39 | 39 | f7bd889287afba0c1f529f333146ff99c8a4b7b2 | bigcode/the-stack | train |
fcca816cc4ea98e047ed3f5a | train | function | def t_error(t):
t.lexer.module.throw(
error = err.fml_error,
line = t.lexer.lineno,
position = t.lexer.lexpos,
lexem = repr(t.value),
)
| def t_error(t):
| t.lexer.module.throw(
error = err.fml_error,
line = t.lexer.lineno,
position = t.lexer.lexpos,
lexem = repr(t.value),
)
|
def t_string_quotex(t):
r'"(?:[^\\"\n]|\\.)*"'
t.type = 'string'
t.value = fml(t.lexer.module, t.value)
return t
def t_code(t):
r"""[^'"\|]+"""
return t
def t_error(t):
| 64 | 64 | 47 | 5 | 58 | nicolasessisbreton/fython | fython/lex/translate_fml.py | Python | t_error | t_error | 43 | 49 | 43 | 43 | d454302afc6355840d5da9275b9e600ff9211d83 | bigcode/the-stack | train |
8226408fbe0cd8616f9baa90 | train | class | class ipCamera(object):
def __init__(self, url, user = None, password = None, debug=False):
self.url = url
self.auth_encoded = base64.encodestring(('%s:%s' % (user, password)).encode())[:-1]
self.debug = debug
self.curr_frame = None
self.thread = threading.Thread(target=self... | class ipCamera(object):
| def __init__(self, url, user = None, password = None, debug=False):
self.url = url
self.auth_encoded = base64.encodestring(('%s:%s' % (user, password)).encode())[:-1]
self.debug = debug
self.curr_frame = None
self.thread = threading.Thread(target=self.stream_frame)
se... | import cv2, time
import urllib.request as urllib
import base64
import numpy as np
import threading
class ipCamera(object):
| 29 | 78 | 263 | 5 | 23 | noob-ja/SeekerRovio | lib/rovio_video.py | Python | ipCamera | ipCamera | 7 | 36 | 7 | 8 | 9c9b68d036d9e9f35a2480f63f84cccc492036d5 | bigcode/the-stack | train |
98b2f4f6f59937210796bc49 | train | function | def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(",")[0]
else:
ip = request.META.get("REMOTE_ADDR", None)
return ip | def get_client_ip(request):
| x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(",")[0]
else:
ip = request.META.get("REMOTE_ADDR", None)
return ip | def get_client_ip(request):
| 6 | 64 | 62 | 6 | 0 | mathemartins/talisaHMO | analytics/utils.py | Python | get_client_ip | get_client_ip | 1 | 7 | 1 | 1 | c22ca92a1213ac1ce6c8564354fbba3112767ab5 | bigcode/the-stack | train |
e18a413b2ab27640c8aaeb20 | train | function | @app.route('/profile/<int:user_id>')
def profile(user_id):
user = User.query.get(user_id)
return render_template("profile.html", user=user)
| @app.route('/profile/<int:user_id>')
def profile(user_id):
| user = User.query.get(user_id)
return render_template("profile.html", user=user)
| *
# resume-app page
@app.route('/')
def index():
users = User.query.all()
return render_template("index.html", users=users)
@app.route('/newuser')
def newuser():
return render_template("new_user.html")
@app.route('/profile/<int:user_id>')
def profile(user_id):
| 64 | 64 | 34 | 14 | 50 | mattRicotta/resume-builder | routes.py | Python | profile | profile | 20 | 23 | 20 | 21 | 2797a529e9965e0d0de7d68be4631adab180c738 | bigcode/the-stack | train |
84502e16008757738e82d06d | train | function | @app.route('/newuser')
def newuser():
return render_template("new_user.html")
| @app.route('/newuser')
def newuser():
| return render_template("new_user.html")
| Field, SubmitField
from wtforms.validators import DataRequired
from app import app, db
from models import *
# resume-app page
@app.route('/')
def index():
users = User.query.all()
return render_template("index.html", users=users)
@app.route('/newuser')
def newuser():
| 64 | 64 | 19 | 10 | 54 | mattRicotta/resume-builder | routes.py | Python | newuser | newuser | 16 | 18 | 16 | 17 | 1b3d56d1985a33b68146afe204dacb9c9640ab09 | bigcode/the-stack | train |
1c942cc6e15c07e4d7124afb | train | function | @app.route('/')
def index():
users = User.query.all()
return render_template("index.html", users=users)
| @app.route('/')
def index():
| users = User.query.all()
return render_template("index.html", users=users)
| from flask import render_template, request, url_for
from flask import Flask
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
from app import app, db
from models import *
# resume-app page
@app.route('/')
def index():
| 64 | 64 | 25 | 6 | 57 | mattRicotta/resume-builder | routes.py | Python | index | index | 11 | 14 | 11 | 12 | 075e787463a54ae11e70a197cd04ae92837211d4 | bigcode/the-stack | train |
6226e205db5d6a956581f778 | train | class | class ElementT(Enum):
H = auto()
He = auto()
Li = auto()
Be = auto()
B = auto()
C = auto()
N = auto()
O = auto()
F = auto()
Ne = auto()
Na = auto()
Mg = auto()
Al = auto()
Si = auto()
P = auto()
S = auto()
Cl = auto()
Ar = auto()
K = auto()
... | class ElementT(Enum):
| H = auto()
He = auto()
Li = auto()
Be = auto()
B = auto()
C = auto()
N = auto()
O = auto()
F = auto()
Ne = auto()
Na = auto()
Mg = auto()
Al = auto()
Si = auto()
P = auto()
S = auto()
Cl = auto()
Ar = auto()
K = auto()
Ca = auto()
Sc = ... | ## @file ChemTypes.py
# @author Aditya Sharma
# @brief This file creates a module related to the elements on the periodic table
from enum import Enum, auto
## @brief This class implements a ____. It is a _____.
class ElementT(Enum):
| 59 | 183 | 612 | 5 | 54 | AdityaSharma6/The-Chemist | src/ChemTypes.py | Python | ElementT | ElementT | 9 | 127 | 9 | 9 | 175b4852861bd22b82f09f7b51ac28602fa9515d | bigcode/the-stack | train |
8f4d6139636139d7f77ee4f8 | train | function | def ImageProcess(image):
global processedImg
(H, W) = (None, None)
frame = image.copy()
if W is None or H is None:
(H, W) = frame.shape[:2]
blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
starttime = time.time()
layerOutputs ... | def ImageProcess(image):
| global processedImg
(H, W) = (None, None)
frame = image.copy()
if W is None or H is None:
(H, W) = frame.shape[:2]
blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
starttime = time.time()
layerOutputs = net.forward(ln)
sto... | def Setup(yolo):
global net, ln, LABELS
weights = os.path.sep.join([yolo, "/users/anshsahny/darknet/yolov3.weights"])
config = os.path.sep.join([yolo, "/users/anshsahny/darknet/cfg/yolov3.cfg"])
labelsPath = os.path.sep.join([yolo, "/users/anshsahny/darknet/data/coco.names"])
LABELS = open(labelsPat... | 194 | 194 | 647 | 5 | 188 | anshsahny/DistancingDetector | DistancingDetector.py | Python | ImageProcess | ImageProcess | 35 | 97 | 35 | 35 | 9241d433a0e62dc881d5a7cc55d2fffbfcdcb8e2 | bigcode/the-stack | train |
fcb96c0a5380a50330cb22a4 | train | function | def Check(a, b):
dist = (((a[0] - b[0]) ** 2) + (a[1] - b[1]) ** 2) ** 0.5
calibration = (a[1] + b[1]) / 2
if 0 < dist < 0.25 * calibration:
return True
else:
return False
| def Check(a, b):
| dist = (((a[0] - b[0]) ** 2) + (a[1] - b[1]) ** 2) ** 0.5
calibration = (a[1] + b[1]) / 2
if 0 < dist < 0.25 * calibration:
return True
else:
return False
| import numpy as np
import cv2
import imutils
import os
import time
# This function calculates the distance between the center of two individuals in a
# single frame of the video
def Check(a, b):
| 47 | 64 | 86 | 6 | 40 | anshsahny/DistancingDetector | DistancingDetector.py | Python | Check | Check | 10 | 16 | 10 | 10 | 62ad9c806899084b1886016fbdfc8c3c5bdbfb8a | bigcode/the-stack | train |
f51429fa403077ed1d17a888 | train | function | def Setup(yolo):
global net, ln, LABELS
weights = os.path.sep.join([yolo, "/users/anshsahny/darknet/yolov3.weights"])
config = os.path.sep.join([yolo, "/users/anshsahny/darknet/cfg/yolov3.cfg"])
labelsPath = os.path.sep.join([yolo, "/users/anshsahny/darknet/data/coco.names"])
LABELS = open(labelsPat... | def Setup(yolo):
| global net, ln, LABELS
weights = os.path.sep.join([yolo, "/users/anshsahny/darknet/yolov3.weights"])
config = os.path.sep.join([yolo, "/users/anshsahny/darknet/cfg/yolov3.cfg"])
labelsPath = os.path.sep.join([yolo, "/users/anshsahny/darknet/data/coco.names"])
LABELS = open(labelsPath).read().strip()... | 0.25 * calibration:
return True
else:
return False
# This function joins the path components, reads the network model stored in Darknet,
# and gets all the layers of the network model to only store the indexes of layers with
# unconnected outputs
def Setup(yolo):
| 64 | 64 | 160 | 5 | 58 | anshsahny/DistancingDetector | DistancingDetector.py | Python | Setup | Setup | 22 | 30 | 22 | 22 | f489849acb9e6e54de98ecd9782790b12c528189 | bigcode/the-stack | train |
10b5811c0e053e32b9bba529 | train | class | class CustomObjectFloatPromoteToString(CustomObjectRepr):
def _psp_dtype_(self):
return float
| class CustomObjectFloatPromoteToString(CustomObjectRepr):
| def _psp_dtype_(self):
return float
| self, value):
self._value = value
def __repr__(self):
return str(self._value)
class CustomObjectIntPromoteToString(CustomObjectRepr):
def _psp_dtype_(self):
return int
class CustomObjectFloatPromoteToString(CustomObjectRepr):
| 64 | 64 | 26 | 13 | 50 | vishalbelsare/perspective | python/perspective/perspective/tests/table/test_table_object.py | Python | CustomObjectFloatPromoteToString | CustomObjectFloatPromoteToString | 42 | 44 | 42 | 42 | f5a8cf1e4f2e50d6c89e5e19bbf44b31a695b733 | bigcode/the-stack | train |
b03cdf5128cd2f126534c3ab | train | class | class TestTableObjectsExtract(object):
def test_table_custom_object(self):
data = {"a": [CustomObjectBlank()]}
tbl = Table(data)
assert tbl.schema() == {"a": str}
assert tbl.size() == 1
assert '<perspective.tests.table.test_table_object.CustomObjectBlank object at 0x' in tbl... | class TestTableObjectsExtract(object):
| def test_table_custom_object(self):
data = {"a": [CustomObjectBlank()]}
tbl = Table(data)
assert tbl.schema() == {"a": str}
assert tbl.size() == 1
assert '<perspective.tests.table.test_table_object.CustomObjectBlank object at 0x' in tbl.view().to_dict()["a"][0]
def test... | + 1
class CustomObjectFloatBoth(CustomObjectRepr):
def _psp_dtype_(self):
return float
def _psp_repr_(self):
return float(self._value) + 1.0
class CustomObjectIntConvert(CustomObjectRepr):
def _psp_dtype_(self):
return int
def __int__(self):
return int(self._value)
... | 256 | 256 | 972 | 7 | 249 | vishalbelsare/perspective | python/perspective/perspective/tests/table/test_table_object.py | Python | TestTableObjectsExtract | TestTableObjectsExtract | 101 | 192 | 101 | 101 | 5cd43c40177021b745d7d908e15d4da5d32812c8 | bigcode/the-stack | train |
df1a9d094f4da57f636dfcd5 | train | class | class CustomObjectIntBoth(CustomObjectRepr):
def _psp_dtype_(self):
return int
def _psp_repr_(self):
return int(self._value) + 1
| class CustomObjectIntBoth(CustomObjectRepr):
| def _psp_dtype_(self):
return int
def _psp_repr_(self):
return int(self._value) + 1
| value)
class CustomObjectIntPromoteToString(CustomObjectRepr):
def _psp_dtype_(self):
return int
class CustomObjectFloatPromoteToString(CustomObjectRepr):
def _psp_dtype_(self):
return float
class CustomObjectIntBoth(CustomObjectRepr):
| 64 | 64 | 43 | 10 | 53 | vishalbelsare/perspective | python/perspective/perspective/tests/table/test_table_object.py | Python | CustomObjectIntBoth | CustomObjectIntBoth | 46 | 51 | 46 | 46 | 9172eda8a24afa00083cb0c86089f4830bed2f6c | bigcode/the-stack | train |
a6ad75fed1cb12f09ce9eb06 | train | class | class CustomObjectFloatConvert(CustomObjectRepr):
def _psp_dtype_(self):
return float
def __float__(self):
return float(self._value)
def __repr__(self):
return 'test'
| class CustomObjectFloatConvert(CustomObjectRepr):
| def _psp_dtype_(self):
return float
def __float__(self):
return float(self._value)
def __repr__(self):
return 'test'
| 1.0
class CustomObjectIntConvert(CustomObjectRepr):
def _psp_dtype_(self):
return int
def __int__(self):
return int(self._value)
def __repr__(self):
return 'test'
class CustomObjectFloatConvert(CustomObjectRepr):
| 64 | 64 | 49 | 10 | 54 | vishalbelsare/perspective | python/perspective/perspective/tests/table/test_table_object.py | Python | CustomObjectFloatConvert | CustomObjectFloatConvert | 70 | 78 | 70 | 70 | 62d1df110973ed1e541efa71c0e5cc5d79d28ab6 | bigcode/the-stack | train |
09ce1a17e54a93508a2f44b1 | train | class | class CustomObjectRepr(object):
def __init__(self, value):
self._value = value
def __repr__(self):
return str(self._value)
| class CustomObjectRepr(object):
| def __init__(self, value):
self._value = value
def __repr__(self):
return str(self._value)
| ):
def __init__(self, value):
self._value = value
def _psp_dtype_(self):
return "object"
def __int__(self):
return int(self._value)
def __repr__(self):
return 'test'
class CustomObjectRepr(object):
| 64 | 64 | 37 | 7 | 57 | vishalbelsare/perspective | python/perspective/perspective/tests/table/test_table_object.py | Python | CustomObjectRepr | CustomObjectRepr | 31 | 36 | 31 | 31 | 0914d8606f4dccc31806698b8e9a16eefe5e09ea | bigcode/the-stack | train |
02043e693cd84e355e45100f | train | class | class CustomObjectIntConvert(CustomObjectRepr):
def _psp_dtype_(self):
return int
def __int__(self):
return int(self._value)
def __repr__(self):
return 'test'
| class CustomObjectIntConvert(CustomObjectRepr):
| def _psp_dtype_(self):
return int
def __int__(self):
return int(self._value)
def __repr__(self):
return 'test'
| int(self._value) + 1
class CustomObjectFloatBoth(CustomObjectRepr):
def _psp_dtype_(self):
return float
def _psp_repr_(self):
return float(self._value) + 1.0
class CustomObjectIntConvert(CustomObjectRepr):
| 64 | 64 | 49 | 10 | 53 | vishalbelsare/perspective | python/perspective/perspective/tests/table/test_table_object.py | Python | CustomObjectIntConvert | CustomObjectIntConvert | 60 | 68 | 60 | 60 | a4e9c8ffb2ded5377299a3542c6de80641c8a36d | bigcode/the-stack | train |
c0829a093ed26e751faf4dc6 | train | class | class CustomObjectIntPromoteToString(CustomObjectRepr):
def _psp_dtype_(self):
return int
| class CustomObjectIntPromoteToString(CustomObjectRepr):
| def _psp_dtype_(self):
return int
| value)
def __repr__(self):
return 'test'
class CustomObjectRepr(object):
def __init__(self, value):
self._value = value
def __repr__(self):
return str(self._value)
class CustomObjectIntPromoteToString(CustomObjectRepr):
| 64 | 64 | 26 | 13 | 51 | vishalbelsare/perspective | python/perspective/perspective/tests/table/test_table_object.py | Python | CustomObjectIntPromoteToString | CustomObjectIntPromoteToString | 38 | 40 | 38 | 38 | 3404163236c2caedf32b8592bce7bed4fc97418e | bigcode/the-stack | train |
3b48ace56fb837f3b603efba | train | class | class TestTableObjectsStore(object):
def test_object_passthrough(self):
t = CustomObjectStore(1)
t2 = CustomObjectStore(2)
t3 = CustomObjectStore(3)
data = {"a": [t, t2, t3]}
tbl = Table(data)
assert tbl.schema() == {"a": object}
assert tbl.size() == 3
... | class TestTableObjectsStore(object):
| def test_object_passthrough(self):
t = CustomObjectStore(1)
t2 = CustomObjectStore(2)
t3 = CustomObjectStore(3)
data = {"a": [t, t2, t3]}
tbl = Table(data)
assert tbl.schema() == {"a": object}
assert tbl.size() == 3
assert tbl.view().to_dict() == {"a"... | }
def test_custom_object_float_convert(self):
data = {"a": [CustomObjectFloatConvert(1), CustomObjectFloatConvert(2)]}
tbl = Table(data)
assert tbl.schema() == {"a": float}
assert tbl.size() == 2
assert tbl.view().to_dict() == {"a": [1.0, 2.0]}
def test_custom_object_i... | 255 | 256 | 1,392 | 7 | 248 | vishalbelsare/perspective | python/perspective/perspective/tests/table/test_table_object.py | Python | TestTableObjectsStore | TestTableObjectsStore | 194 | 346 | 194 | 194 | d5af7f367abbd9c592bb0ae92fca2c4f477947b5 | bigcode/the-stack | train |
1a89a3de29999d8ccfa827e6 | train | class | class CustomObjectFloatConvertFromInt(CustomObjectRepr):
def _psp_dtype_(self):
return float
def __int__(self):
return int(self._value)
def __repr__(self):
return 'test'
| class CustomObjectFloatConvertFromInt(CustomObjectRepr):
| def _psp_dtype_(self):
return float
def __int__(self):
return int(self._value)
def __repr__(self):
return 'test'
| '
class CustomObjectIntConvertFromFloat(CustomObjectRepr):
def _psp_dtype_(self):
return int
def __float__(self):
return float(self._value)
def __repr__(self):
return 'test'
class CustomObjectFloatConvertFromInt(CustomObjectRepr):
| 64 | 64 | 51 | 12 | 52 | vishalbelsare/perspective | python/perspective/perspective/tests/table/test_table_object.py | Python | CustomObjectFloatConvertFromInt | CustomObjectFloatConvertFromInt | 91 | 99 | 91 | 91 | d925c41f4fb48e314ec7e839350959897bbfb5f9 | bigcode/the-stack | train |
2e1a3bad40d7b75c8d15d930 | train | class | class CustomObjectStore(object):
def __init__(self, value):
self._value = value
def _psp_dtype_(self):
return "object"
def __int__(self):
return int(self._value)
def __repr__(self):
return 'test'
| class CustomObjectStore(object):
| def __init__(self, value):
self._value = value
def _psp_dtype_(self):
return "object"
def __int__(self):
return int(self._value)
def __repr__(self):
return 'test'
| distributed under the terms of
# the Apache License 2.0. The full license can be found in the LICENSE file.
#
import sys
from datetime import date, datetime
from random import randint
from perspective.table import Table
class CustomObjectBlank(object):
pass
class CustomObjectStore(object):
| 64 | 64 | 62 | 6 | 57 | vishalbelsare/perspective | python/perspective/perspective/tests/table/test_table_object.py | Python | CustomObjectStore | CustomObjectStore | 18 | 29 | 18 | 18 | f4e481c84f1775391bec9e05cb7de233be8e7cd9 | bigcode/the-stack | train |
cb11c8d3d6b02d881ca67ff5 | train | class | class CustomObjectBlank(object):
pass
| class CustomObjectBlank(object):
| pass
| This file is part of the Perspective library, distributed under the terms of
# the Apache License 2.0. The full license can be found in the LICENSE file.
#
import sys
from datetime import date, datetime
from random import randint
from perspective.table import Table
class CustomObjectBlank(object):
| 64 | 64 | 9 | 6 | 57 | vishalbelsare/perspective | python/perspective/perspective/tests/table/test_table_object.py | Python | CustomObjectBlank | CustomObjectBlank | 15 | 16 | 15 | 15 | 4190c489526144488a0af380126fea986adc1b3c | bigcode/the-stack | train |
1b1cd21049a74cd613413fc2 | train | class | class CustomObjectIntConvertFromFloat(CustomObjectRepr):
def _psp_dtype_(self):
return int
def __float__(self):
return float(self._value)
def __repr__(self):
return 'test'
| class CustomObjectIntConvertFromFloat(CustomObjectRepr):
| def _psp_dtype_(self):
return int
def __float__(self):
return float(self._value)
def __repr__(self):
return 'test'
| 'test'
class CustomObjectFloatConvert(CustomObjectRepr):
def _psp_dtype_(self):
return float
def __float__(self):
return float(self._value)
def __repr__(self):
return 'test'
class CustomObjectIntConvertFromFloat(CustomObjectRepr):
| 64 | 64 | 51 | 12 | 52 | vishalbelsare/perspective | python/perspective/perspective/tests/table/test_table_object.py | Python | CustomObjectIntConvertFromFloat | CustomObjectIntConvertFromFloat | 81 | 89 | 81 | 81 | 42e113ae4bfef1ebdbf1fdb3e33e183d9e60d7ea | bigcode/the-stack | train |
8208f9c330648b976c89f455 | train | class | class CustomObjectFloatBoth(CustomObjectRepr):
def _psp_dtype_(self):
return float
def _psp_repr_(self):
return float(self._value) + 1.0
| class CustomObjectFloatBoth(CustomObjectRepr):
| def _psp_dtype_(self):
return float
def _psp_repr_(self):
return float(self._value) + 1.0
| _psp_dtype_(self):
return float
class CustomObjectIntBoth(CustomObjectRepr):
def _psp_dtype_(self):
return int
def _psp_repr_(self):
return int(self._value) + 1
class CustomObjectFloatBoth(CustomObjectRepr):
| 64 | 64 | 45 | 10 | 53 | vishalbelsare/perspective | python/perspective/perspective/tests/table/test_table_object.py | Python | CustomObjectFloatBoth | CustomObjectFloatBoth | 53 | 58 | 53 | 53 | 138e54beb1cdb014ca91c92e0f8b52e6f5fba54b | bigcode/the-stack | train |
44b00b1106499b6251a7e341 | train | class | class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1027, 499)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.s... | class Ui_MainWindow(object):
| def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1027, 499)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(1)
... | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/Users/blogin/Projects/hatch-masternode-tool/src/ui/ui_main_dlg.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object... | 88 | 256 | 6,670 | 6 | 81 | hatchpay/hatch-masternode-tool | src/ui/ui_main_dlg.py | Python | Ui_MainWindow | Ui_MainWindow | 11 | 427 | 11 | 11 | 622a9f4b85da7c46b43822bbf5ae6ee7c0c8238f | bigcode/the-stack | train |
8b43676f9dcf539c7e8caa2c | train | class | class JapaneseFontTests(unittest.TestCase):
def hDraw(self, c, msg, fnt, x, y):
"Helper - draws it with a box around"
c.setFont(fnt, 16, 16)
font = pdfmetrics.getFont(fnt)
c.drawString(x, y, msg)
width = font.stringWidth(msg, 16)
c.rect(x,y,width,16,stroke=1,fill=0)
... | class JapaneseFontTests(unittest.TestCase):
| def hDraw(self, c, msg, fnt, x, y):
"Helper - draws it with a box around"
c.setFont(fnt, 16, 16)
font = pdfmetrics.getFont(fnt)
c.drawString(x, y, msg)
width = font.stringWidth(msg, 16)
c.rect(x,y,width,16,stroke=1,fill=0)
def test0(self):
"A basic docume... | #Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
#history www.reportlab.co.uk/rl-cgi/viewcvs.cgi/rlextra/rlj/jpsupport.py
# Temporary japanese support for ReportLab.
"""
The code in this module will disappear any day now and be replaced
by classes in reportlab.pdfbase.cidfonts
"""
from re... | 194 | 256 | 9,581 | 8 | 185 | MrBitBucket/reportlab-ci | tests/test_multibyte_jpn.py | Python | JapaneseFontTests | JapaneseFontTests | 22 | 419 | 22 | 23 | 51c99a8324f0707f16c636aade429088529df17f | bigcode/the-stack | train |
1b0465b9e9bcf7ffa44114fa | train | function | def makeSuite():
return makeSuiteForClasses(JapaneseFontTests)
| def makeSuite():
| return makeSuiteForClasses(JapaneseFontTests)
| (row) + chr(cell)
x = x0 + cell*dx
y = y0 - row*dy
c.drawString(x,y,s)
c.save()
if VERBOSE:
print('saved '+outputfile('test_multibyte_jpn.pdf'))
def makeSuite():
| 63 | 64 | 15 | 4 | 59 | MrBitBucket/reportlab-ci | tests/test_multibyte_jpn.py | Python | makeSuite | makeSuite | 422 | 423 | 422 | 422 | ec2dee5a1282c5f00a7c83a6e5a4d0de73af5639 | bigcode/the-stack | train |
9be17ce55238b2d2e6e74f3a | train | class | class ActivationStatus(BaseResource, ActivationStatusData):
"""Local number portability order activation status"""
_xpath = XPATH_ACTIVATION_STATUS
def __init__(self, parent=None, client=None):
super().__init__(parent, client)
ActivationStatusData.__init__(self)
self._id = 1
... | class ActivationStatus(BaseResource, ActivationStatusData):
| """Local number portability order activation status"""
_xpath = XPATH_ACTIVATION_STATUS
def __init__(self, parent=None, client=None):
super().__init__(parent, client)
ActivationStatusData.__init__(self)
self._id = 1
def get(self):
return self._get_data()
def save(... | from __future__ import division, absolute_import, print_function
from future.builtins import super
from iris_sdk.models.base_resource import BaseResource
from iris_sdk.models.data.activation_status import ActivationStatusData
XPATH_ACTIVATION_STATUS = "/activationStatus"
class ActivationStatus(BaseResource, Activatio... | 64 | 64 | 98 | 10 | 54 | NumberAI/python-bandwidth-iris | iris_sdk/models/activation_status.py | Python | ActivationStatus | ActivationStatus | 11 | 27 | 11 | 12 | 56754004e27953ada43578529df6c3f04d282518 | bigcode/the-stack | train |
c6367a5c04b173dd2d536d2a | train | class | class BananaEnv(BaseEnvironment):
"""
Banana environment
"""
def __init__(self, file_name) -> None:
"""
Creates banana environment
:param file_name: path to unity binary
"""
self.env = UnityEnvironment(file_name=file_name)
self.brain_name = self.env.brain... | class BananaEnv(BaseEnvironment):
| """
Banana environment
"""
def __init__(self, file_name) -> None:
"""
Creates banana environment
:param file_name: path to unity binary
"""
self.env = UnityEnvironment(file_name=file_name)
self.brain_name = self.env.brain_names[0]
brain = self.env... | from abc import ABC, abstractmethod
from unityagents import UnityEnvironment
class BaseEnvironment(ABC):
@abstractmethod
def initialize(self, train_mode):
pass
@abstractmethod
def reset(self):
pass
@abstractmethod
def step(self, action):
pass
@abstractmethod
... | 84 | 94 | 314 | 6 | 77 | piotrbazan/deep-reinforcement-learning | p1_navigation/environment.py | Python | BananaEnv | BananaEnv | 25 | 65 | 25 | 25 | 3426d6408f54af41d4f3dbd930d2169f77658002 | bigcode/the-stack | train |
2bf74b460f7dfd983748e0fb | train | class | class BaseEnvironment(ABC):
@abstractmethod
def initialize(self, train_mode):
pass
@abstractmethod
def reset(self):
pass
@abstractmethod
def step(self, action):
pass
@abstractmethod
def close(self):
pass
| class BaseEnvironment(ABC):
@abstractmethod
| def initialize(self, train_mode):
pass
@abstractmethod
def reset(self):
pass
@abstractmethod
def step(self, action):
pass
@abstractmethod
def close(self):
pass
| from abc import ABC, abstractmethod
from unityagents import UnityEnvironment
class BaseEnvironment(ABC):
@abstractmethod
| 26 | 64 | 63 | 11 | 14 | piotrbazan/deep-reinforcement-learning | p1_navigation/environment.py | Python | BaseEnvironment | BaseEnvironment | 6 | 22 | 6 | 8 | f946cce6bef16c5f2ba4c855156e1e2db8503c92 | bigcode/the-stack | train |
1fc7bd6e98de87c3fda0d8cc | train | function | def stochastic_from_keras(
model: tf.keras.models.Model,
input_tensors=None,
clone_function=None,
expect_determinism=False,
temp_weights_path="tmp/weights",
):
"""
Creates a stochastic instance from a given `tf.keras.models.Sequential` model:
The new model will have the same structure (l... | def stochastic_from_keras(
model: tf.keras.models.Model,
input_tensors=None,
clone_function=None,
expect_determinism=False,
temp_weights_path="tmp/weights",
):
| """
Creates a stochastic instance from a given `tf.keras.models.Sequential` model:
The new model will have the same structure (layers) and weights as the passed model.
All stochastic layers (e.g. tf.keras.layers.Dropout) will be used for randomization during randomized predictions.
If no stochastic... | import shutil
import tensorflow as tf
from uncertainty_wizard.models._stochastic._stochastic_mode import StochasticMode
from ._abstract_stochastic import Stochastic
from ._functional_stochastic import StochasticFunctional
from ._sequential_stochastic import StochasticSequential
def stochastic_from_keras(
model: ... | 100 | 242 | 807 | 42 | 57 | p1ndsvin/uncertainty-wizard | uncertainty_wizard/models/_stochastic/_from_keras.py | Python | stochastic_from_keras | stochastic_from_keras | 12 | 90 | 12 | 18 | f1e3099e02d3cc7a266d792a84cbe7074c37c522 | bigcode/the-stack | train |
072eafebaa9ecc6f1094147f | train | class | class TestRandomOps(test.TestCase):
def test_random_binomial(self):
with self.test_session():
np.random.seed(123)
x = keras.backend.random_binomial((1000, 1000), p=0.5)
self.assertAllClose(np.mean(keras.backend.eval(x)), 0.5, atol=0.1)
def test_truncated_normal(self):
with self.test_sess... | class TestRandomOps(test.TestCase):
| def test_random_binomial(self):
with self.test_session():
np.random.seed(123)
x = keras.backend.random_binomial((1000, 1000), p=0.5)
self.assertAllClose(np.mean(keras.backend.eval(x)), 0.5, atol=0.1)
def test_truncated_normal(self):
with self.test_session():
np.random.seed(123)
... | (label_lens, dtype='int32')
res = keras.backend.eval(
keras.backend.ctc_batch_cost(labels, inputs, input_lens, label_lens))
self.assertAllClose(res[:, 0], loss_log_probs, atol=1e-05)
class TestRandomOps(test.TestCase):
| 64 | 64 | 207 | 8 | 56 | tucaiyong/tensorflow | tensorflow/python/keras/_impl/keras/backend_test.py | Python | TestRandomOps | TestRandomOps | 1,126 | 1,142 | 1,126 | 1,127 | 6f31cabd1246713d2054681ba61f1e8ed4880a6d | bigcode/the-stack | train |
66a5439857e7c82f4b15f8d0 | train | class | class BackendLinearAlgebraTest(test.TestCase):
def test_dot(self):
x = keras.backend.placeholder(shape=(2, 3))
y = keras.backend.placeholder(shape=(3, 4))
xy = keras.backend.dot(x, y)
self.assertEqual(xy.get_shape().as_list(), [2, 4])
x = keras.backend.placeholder(shape=(32, 28, 3))
y = kera... | class BackendLinearAlgebraTest(test.TestCase):
| def test_dot(self):
x = keras.backend.placeholder(shape=(2, 3))
y = keras.backend.placeholder(shape=(3, 4))
xy = keras.backend.dot(x, y)
self.assertEqual(xy.get_shape().as_list(), [2, 4])
x = keras.backend.placeholder(shape=(32, 28, 3))
y = keras.backend.placeholder(shape=(3, 4))
xy = ker... | 0.5, atol=1e-1)
def test_count_params(self):
with self.test_session():
x = keras.backend.zeros((4, 5))
val = keras.backend.count_params(x)
self.assertAllClose(val, 20)
def test_constant(self):
with self.test_session():
ref_val = np.random.random((3, 4)).astype('float32')
x = ... | 256 | 256 | 956 | 10 | 246 | tucaiyong/tensorflow | tensorflow/python/keras/_impl/keras/backend_test.py | Python | BackendLinearAlgebraTest | BackendLinearAlgebraTest | 357 | 459 | 357 | 358 | 0d7907ebacc60981e149ad833ce49a05f4e18ef4 | bigcode/the-stack | train |
ae0425357afaffe7f402c54b | train | function | def compare_single_input_op_to_numpy(keras_op,
np_op,
input_shape,
dtype='float32',
negative_values=True,
keras_args=None,
... | def compare_single_input_op_to_numpy(keras_op,
np_op,
input_shape,
dtype='float32',
negative_values=True,
keras_args=None,
... | keras_args = keras_args or []
keras_kwargs = keras_kwargs or {}
np_args = np_args or []
np_kwargs = np_kwargs or {}
inputs = 2. * np.random.random(input_shape)
if negative_values:
inputs -= 1.
keras_output = keras_op(keras.backend.variable(inputs, dtype=dtype),
*keras_args, *... | import variables
from tensorflow.python.platform import test
from tensorflow.python.util import tf_inspect
def compare_single_input_op_to_numpy(keras_op,
np_op,
input_shape,
dtype='float32',
... | 69 | 69 | 231 | 50 | 18 | tucaiyong/tensorflow | tensorflow/python/keras/_impl/keras/backend_test.py | Python | compare_single_input_op_to_numpy | compare_single_input_op_to_numpy | 30 | 55 | 30 | 38 | c07c3285679b504e9f980db40f8d898ff96ccf87 | bigcode/the-stack | train |
714b10a5790512343d20b2f8 | train | class | class BackendVariableTest(test.TestCase):
def test_zeros(self):
with self.test_session():
x = keras.backend.zeros((3, 4))
val = keras.backend.eval(x)
self.assertAllClose(val, np.zeros((3, 4)))
def test_ones(self):
with self.test_session():
x = keras.backend.ones((3, 4))
val =... | class BackendVariableTest(test.TestCase):
| def test_zeros(self):
with self.test_session():
x = keras.backend.zeros((3, 4))
val = keras.backend.eval(x)
self.assertAllClose(val, np.zeros((3, 4)))
def test_ones(self):
with self.test_session():
x = keras.backend.ones((3, 4))
val = keras.backend.eval(x)
self.assertAll... | _placeholder = keras.backend.placeholder(shape=())
feed_dict = {y_placeholder: 3.}
fetches = [keras.backend.update(y, y_placeholder * 10.)]
f = keras.backend.function(inputs=[x_placeholder],
outputs=[x_placeholder + 1.],
updates=[(x, x... | 206 | 206 | 687 | 8 | 198 | tucaiyong/tensorflow | tensorflow/python/keras/_impl/keras/backend_test.py | Python | BackendVariableTest | BackendVariableTest | 278 | 354 | 278 | 279 | ab8a8f56309fc71dd20118c171e852e299429c2f | bigcode/the-stack | train |
75ddca7b8d63cdc8f58cc911 | train | class | class BackendNNOpsTest(test.TestCase):
def test_bias_add(self):
with self.test_session():
keras_op = keras.backend.bias_add
np_op = np.add
compare_two_inputs_op_to_numpy(keras_op, np_op,
input_shape_a=(4, 7),
input_shape_... | class BackendNNOpsTest(test.TestCase):
| def test_bias_add(self):
with self.test_session():
keras_op = keras.backend.bias_add
np_op = np.add
compare_two_inputs_op_to_numpy(keras_op, np_op,
input_shape_a=(4, 7),
input_shape_b=(7,))
compare_two_inputs_op_to_n... | 1],
padding[2][0]:-padding[2][1]] = x
return y
with self.test_session():
compare_single_input_op_to_numpy(
keras.backend.spatial_3d_padding,
ref_op,
input_shape=(2, 3, 2, 3, 2),
keras_args=[((2, 3), (1, 2), (2, 3))],
keras_kwargs={'data_format... | 255 | 256 | 4,599 | 10 | 245 | tucaiyong/tensorflow | tensorflow/python/keras/_impl/keras/backend_test.py | Python | BackendNNOpsTest | BackendNNOpsTest | 664 | 1,042 | 664 | 665 | 297ecb32050a30b4be7b9520f574a341adabd8ce | bigcode/the-stack | train |
c7747a2718fd0a8a7b736382 | train | class | class TestCTC(test.TestCase):
def test_ctc_decode(self):
with self.test_session():
depth = 6
seq_len_0 = 5
input_prob_matrix_0 = np.asarray(
[[0.30999, 0.309938, 0.0679938, 0.0673362, 0.0708352, 0.173908],
[0.215136, 0.439699, 0.0370931, 0.0393967, 0.0381581, 0.230517],
... | class TestCTC(test.TestCase):
| def test_ctc_decode(self):
with self.test_session():
depth = 6
seq_len_0 = 5
input_prob_matrix_0 = np.asarray(
[[0.30999, 0.309938, 0.0679938, 0.0673362, 0.0708352, 0.173908],
[0.215136, 0.439699, 0.0370931, 0.0393967, 0.0381581, 0.230517],
[0.199959, 0.489485, 0.... | .assertEqual(normed.get_shape().as_list(), [10, 3, 10, 10])
self.assertEqual(mean.get_shape().as_list(), [3,])
self.assertEqual(var.get_shape().as_list(), [3,])
# case: gamma=None
gamma = None
normed, mean, var = keras.backend.normalize_batch_in_training(
x, gamma, beta, reduction_axes, eps... | 256 | 256 | 1,276 | 8 | 248 | tucaiyong/tensorflow | tensorflow/python/keras/_impl/keras/backend_test.py | Python | TestCTC | TestCTC | 1,045 | 1,123 | 1,045 | 1,046 | a7f2f7708e869d02077d38de7d5173cf058233cd | bigcode/the-stack | train |
ad4e3276f321c363991263d7 | train | class | class BackendShapeOpsTest(test.TestCase):
def test_reshape(self):
with self.test_session():
compare_single_input_op_to_numpy(keras.backend.reshape, np.reshape,
input_shape=(4, 7),
keras_args=[(2, 14)],
... | class BackendShapeOpsTest(test.TestCase):
| def test_reshape(self):
with self.test_session():
compare_single_input_op_to_numpy(keras.backend.reshape, np.reshape,
input_shape=(4, 7),
keras_args=[(2, 14)],
np_args=[(2, 14)])
def test_... | np.clip,
input_shape=(6, 4),
keras_kwargs={'min_value': 0.1, 'max_value': 2.4},
np_kwargs={'a_min': 0.1, 'a_max': 1.4})
with self.test_session():
compare_single_input_op_to_numpy(
keras.backend.pow, np.power,
input_shape=(6, 4),
keras_args=[3],
... | 256 | 256 | 1,940 | 9 | 247 | tucaiyong/tensorflow | tensorflow/python/keras/_impl/keras/backend_test.py | Python | BackendShapeOpsTest | BackendShapeOpsTest | 462 | 661 | 462 | 463 | 50965dc1783046fbb28e17b76e0af90456bb414e | bigcode/the-stack | train |
4c4c1d69a8553e71cb6b399f | train | class | class BackendUtilsTest(test.TestCase):
def test_backend(self):
self.assertEqual(keras.backend.backend(), 'tensorflow')
def test_espilon(self):
epsilon = 1e-2
keras.backend.set_epsilon(epsilon)
self.assertEqual(keras.backend.epsilon(), epsilon)
keras.backend.set_epsilon(1e-7)
def test_floatx... | class BackendUtilsTest(test.TestCase):
| def test_backend(self):
self.assertEqual(keras.backend.backend(), 'tensorflow')
def test_espilon(self):
epsilon = 1e-2
keras.backend.set_epsilon(epsilon)
self.assertEqual(keras.backend.epsilon(), epsilon)
keras.backend.set_epsilon(1e-7)
def test_floatx(self):
floatx = 'float64'
keras... | compare_two_inputs_op_to_numpy(keras_op,
np_op,
input_shape_a,
input_shape_b,
dtype='float32',
keras_args=None,
... | 256 | 256 | 1,810 | 8 | 248 | tucaiyong/tensorflow | tensorflow/python/keras/_impl/keras/backend_test.py | Python | BackendUtilsTest | BackendUtilsTest | 87 | 275 | 87 | 88 | 64c8db87d315b3866c558c01f38ebd143ea13a50 | bigcode/the-stack | train |
874999a8714a5a296a4f7339 | train | function | def compare_two_inputs_op_to_numpy(keras_op,
np_op,
input_shape_a,
input_shape_b,
dtype='float32',
keras_args=None,
... | def compare_two_inputs_op_to_numpy(keras_op,
np_op,
input_shape_a,
input_shape_b,
dtype='float32',
keras_args=None,
... | keras_args = keras_args or []
keras_kwargs = keras_kwargs or {}
np_args = np_args or []
np_kwargs = np_kwargs or {}
input_a = np.random.random(input_shape_a)
input_b = np.random.random(input_shape_b)
keras_output = keras_op(keras.backend.variable(input_a, dtype=dtype),
keras.back... | ; '
'Expected ' + str(np_output) + ' but got ' +
str(keras_output))
def compare_two_inputs_op_to_numpy(keras_op,
np_op,
input_shape_a,
input_shape_b,
... | 74 | 74 | 249 | 51 | 23 | tucaiyong/tensorflow | tensorflow/python/keras/_impl/keras/backend_test.py | Python | compare_two_inputs_op_to_numpy | compare_two_inputs_op_to_numpy | 58 | 84 | 58 | 66 | 4d453bd73c98402f5a56634bd47c7b0158f4b491 | bigcode/the-stack | train |
ce0f96684c5712fd5bfff778 | train | class | class MeasureToViewMap(object):
"""Measure To View Map stores a map from names of Measures to
specific View Datas
"""
def __init__(self):
# stores the one-to-many mapping from Measures to View Datas
self._measure_to_view_data_list_map = defaultdict(list)
# stores a map from the... | class MeasureToViewMap(object):
| """Measure To View Map stores a map from names of Measures to
specific View Datas
"""
def __init__(self):
# stores the one-to-many mapping from Measures to View Datas
self._measure_to_view_data_list_map = defaultdict(list)
# stores a map from the registered View names to the Vi... | # Copyright 2018, OpenCensus Authors
#
# 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 to in w... | 160 | 225 | 751 | 7 | 152 | meridional/opencensus-python | opencensus/stats/measure_to_view_map.py | Python | MeasureToViewMap | MeasureToViewMap | 21 | 116 | 21 | 21 | 260f77771c8f8d54dbe995b66bd8c0a56e97804b | bigcode/the-stack | train |
c1e7e3d109a6a61aaf4da37e | train | class | class RescaleMask(PostprocessorWithSpecificTargets):
__provider__ = 'rescale_mask'
annotation_types = (BackgroundMattingAnnotation, )
prediction_types = (BackgroundMattingPrediction, )
@classmethod
def parameters(cls):
params = super().parameters()
params.update({
'min':... | class RescaleMask(PostprocessorWithSpecificTargets):
| __provider__ = 'rescale_mask'
annotation_types = (BackgroundMattingAnnotation, )
prediction_types = (BackgroundMattingPrediction, )
@classmethod
def parameters(cls):
params = super().parameters()
params.update({
'min': NumberField(optional=True, default=0, description='m... | .
See the License for the specific language governing permissions and
limitations under the License.
"""
import cv2
from .postprocessor import PostprocessorWithSpecificTargets
from ..config import NumberField
from ..representation import BackgroundMattingAnnotation, BackgroundMattingPrediction
class RescaleMask(Postpr... | 64 | 64 | 209 | 10 | 53 | Ohtani-y/open_model_zoo | tools/accuracy_checker/openvino/tools/accuracy_checker/postprocessor/rescale_mask.py | Python | RescaleMask | RescaleMask | 23 | 48 | 23 | 23 | 7f3c77b824b8ae9167f9d0260175573423854265 | bigcode/the-stack | train |
b07bab0f7d8a631ee0ecd4a0 | train | class | class TestSample:
"""Tests that samples are properly calculated."""
def test_sample_dimensions(self):
"""Tests if the samples returned by the sample function have
the correct dimensions
"""
# Explicitly resetting is necessary as the internal
# state is set to None in __... | class TestSample:
| """Tests that samples are properly calculated."""
def test_sample_dimensions(self):
"""Tests if the samples returned by the sample function have
the correct dimensions
"""
# Explicitly resetting is necessary as the internal
# state is set to None in __init__ and only pr... | ()
)
res = qubit_device_2_wires.var(obs)
assert np.isclose(res, expected_output, atol=tol, rtol=0)
def test_var_estimate(self):
"""Test that the variance is not analytically calculated"""
dev = qml.device("default.qubit", wires=1, shots=3)
@qml.qnode(dev, diff_met... | 151 | 151 | 505 | 4 | 146 | mauriceweber/pennylane | tests/devices/test_default_qubit.py | Python | TestSample | TestSample | 1,052 | 1,105 | 1,052 | 1,052 | b87b530ab18e8fcf6d4607d598200b911b7f082d | bigcode/the-stack | train |
8039479d08ba6a0180d08d61 | train | class | class TestGetSlice:
"""Tests for the _get_slice function."""
def test_get_slice(self):
"""Test that the _get_slice function returns the expected slice and allows us to slice
correctly into an array."""
sl = _get_slice(1, 1, 3)
array = np.arange(27).reshape((3, 3, 3))
ta... | class TestGetSlice:
| """Tests for the _get_slice function."""
def test_get_slice(self):
"""Test that the _get_slice function returns the expected slice and allows us to slice
correctly into an array."""
sl = _get_slice(1, 1, 3)
array = np.arange(27).reshape((3, 3, 3))
target = array[:, 1, :... | .cache_info().hits
original_misses = dev.map_wires.cache_info().misses
# The first call is computed: it's a miss as it didn't come from the cache
dev.map_wires(wires_to_map)
# The number of misses increased
assert dev.map_wires.cache_info().misses > original_misses
# T... | 124 | 124 | 415 | 5 | 118 | mauriceweber/pennylane | tests/devices/test_default_qubit.py | Python | TestGetSlice | TestGetSlice | 2,027 | 2,072 | 2,027 | 2,027 | fdbb1c2917bf5a10952f0e252fbb6800eeedfff0 | bigcode/the-stack | train |
e6c3f6dd519c304f1c9b4df7 | train | class | class TestExpval:
"""Tests that expectation values are properly calculated or that the proper errors are raised."""
@pytest.mark.parametrize(
"operation,input,expected_output",
[
(qml.PauliX, [1 / math.sqrt(2), 1 / math.sqrt(2)], 1),
(qml.PauliX, [1 / math.sqrt(2), -1 / ... | class TestExpval:
| """Tests that expectation values are properly calculated or that the proper errors are raised."""
@pytest.mark.parametrize(
"operation,input,expected_output",
[
(qml.PauliX, [1 / math.sqrt(2), 1 / math.sqrt(2)], 1),
(qml.PauliX, [1 / math.sqrt(2), -1 / math.sqrt(2)], -1)... | ]), qml.QubitStateVector(np.array([0, 1, 0, 0]), wires=[0, 1])]
)
def test_apply_errors_basis_state(self, qubit_device_2_wires):
with pytest.raises(
ValueError, match="BasisState parameter must consist of 0 or 1 integers."
):
qubit_device_2_wires.apply([qml.Basis... | 256 | 256 | 1,605 | 5 | 251 | mauriceweber/pennylane | tests/devices/test_default_qubit.py | Python | TestExpval | TestExpval | 792 | 922 | 792 | 792 | b1d631f566c1109e6195154d2be8b4e5854b3ad7 | bigcode/the-stack | train |
11b7f7396b3332993f3371b0 | train | class | class TestVar:
"""Tests that variances are properly calculated."""
@pytest.mark.parametrize(
"operation,input,expected_output",
[
(qml.PauliX, [1 / math.sqrt(2), 1 / math.sqrt(2)], 0),
(qml.PauliX, [1 / math.sqrt(2), -1 / math.sqrt(2)], 0),
(qml.PauliX, [1, 0... | class TestVar:
| """Tests that variances are properly calculated."""
@pytest.mark.parametrize(
"operation,input,expected_output",
[
(qml.PauliX, [1 / math.sqrt(2), 1 / math.sqrt(2)], 0),
(qml.PauliX, [1 / math.sqrt(2), -1 / math.sqrt(2)], 0),
(qml.PauliX, [1, 0], 1),
... | , qubit_device_2_wires, tol, operation, input, expected_output, par
):
"""Tests that expectation values are properly calculated for two-wire observables with parameters."""
obs = operation(np.array(par), wires=[0, 1])
qubit_device_2_wires.reset()
qubit_device_2_wires.apply(
... | 256 | 256 | 1,473 | 4 | 251 | mauriceweber/pennylane | tests/devices/test_default_qubit.py | Python | TestVar | TestVar | 925 | 1,049 | 925 | 925 | 233c5b95fea9de95aec04e1b9e337b2469531759 | bigcode/the-stack | train |
b8162557d693c97b1b0a6a6c | train | class | class TestInverseDecomposition:
"""Integration tests for decompositions of inverse gates"""
def test_inverse_S(self, tol):
"""Test that applying the inverse of the S gate
works without decomposition"""
dev = qml.device("default.qubit", wires=1)
@qml.qnode(dev, diff_method="par... | class TestInverseDecomposition:
| """Integration tests for decompositions of inverse gates"""
def test_inverse_S(self, tol):
"""Test that applying the inverse of the S gate
works without decomposition"""
dev = qml.device("default.qubit", wires=1)
@qml.qnode(dev, diff_method="parameter-shift")
def test_... | ", "c"])
spy = mocker.spy(dev, "_scatter")
dev._apply_state_vector(state=state, device_wires=state_wires)
assert np.all(dev._state.flatten() == state)
spy.assert_not_called()
def test_partial_subsystem(self, mocker):
"""Test applying a state vector to a subset of wires of ... | 202 | 202 | 675 | 6 | 196 | mauriceweber/pennylane | tests/devices/test_default_qubit.py | Python | TestInverseDecomposition | TestInverseDecomposition | 2,194 | 2,265 | 2,194 | 2,194 | b7d3addda96263797fd6b73980412cb4363be317 | bigcode/the-stack | train |
3441760bfadbe660d540ca5f | train | class | @pytest.mark.parametrize("theta, phi, varphi", list(zip(THETA, PHI, VARPHI)))
class TestTensorSample:
"""Test tensor expectation values"""
def test_paulix_pauliy(self, theta, phi, varphi, tol_stochastic):
"""Test that a tensor product involving PauliX and PauliY works correctly"""
dev = qml.dev... | @pytest.mark.parametrize("theta, phi, varphi", list(zip(THETA, PHI, VARPHI)))
class TestTensorSample:
| """Test tensor expectation values"""
def test_paulix_pauliy(self, theta, phi, varphi, tol_stochastic):
"""Test that a tensor product involving PauliX and PauliY works correctly"""
dev = qml.device("default.qubit", wires=3, shots=int(1e6))
obs = qml.PauliX(0) @ qml.PauliY(2)
de... | phi)
- 8 * np.cos(2 * theta) * (3 + 3 * np.cos(varphi) + np.sin(varphi)) ** 2
- 24 * np.cos(phi) * (np.cos(phi) + 2 * np.sin(phi)) * np.sin(2 * varphi)
- 8
* np.cos(theta)
* (
4
* np.cos(phi)
* (
... | 256 | 256 | 1,832 | 29 | 227 | mauriceweber/pennylane | tests/devices/test_default_qubit.py | Python | TestTensorSample | TestTensorSample | 1,683 | 1,853 | 1,683 | 1,684 | 0052d282a488eaba9d562a6625949fb112b16bdb | bigcode/the-stack | train |
3039e5e700097b9f9cd6b453 | train | class | class TestDtypePreserved:
"""Test that the user-defined dtype of the device is preserved for QNode
evaluation"""
@pytest.mark.parametrize("r_dtype", [np.float32, np.float64])
@pytest.mark.parametrize(
"measurement",
[
qml.expval(qml.PauliY(0)),
qml.var(qml.PauliY... | class TestDtypePreserved:
| """Test that the user-defined dtype of the device is preserved for QNode
evaluation"""
@pytest.mark.parametrize("r_dtype", [np.float32, np.float64])
@pytest.mark.parametrize(
"measurement",
[
qml.expval(qml.PauliY(0)),
qml.var(qml.PauliY(0)),
qml.prob... | varphi)
- (1 + 6 * np.cos(varphi)) * np.sin(varphi)
)
+ np.sin(phi)
* (
15
+ 8 * np.cos(varphi)
- 11 * np.cos(2 * varphi)
+ 42 * np.sin(var... | 123 | 123 | 412 | 7 | 116 | mauriceweber/pennylane | tests/devices/test_default_qubit.py | Python | TestDtypePreserved | TestDtypePreserved | 1,856 | 1,903 | 1,856 | 1,856 | 51bfbb246e707e39f15b80dc766a3dabbc5991c0 | bigcode/the-stack | train |
72492f69215c346911fb452b | train | class | class TestHamiltonianSupport:
"""Tests the devices' native support for Hamiltonian observables."""
def test_do_not_split_analytic(self, mocker):
"""Tests that the Hamiltonian is not split for shots=None."""
dev = qml.device("default.qubit", wires=2)
H = qml.Hamiltonian(np.array([0.1, 0.... | class TestHamiltonianSupport:
| """Tests the devices' native support for Hamiltonian observables."""
def test_do_not_split_analytic(self, mocker):
"""Tests that the Hamiltonian is not split for shots=None."""
dev = qml.device("default.qubit", wires=2)
H = qml.Hamiltonian(np.array([0.1, 0.2]), [qml.PauliX(0), qml.Pauli... | ((state, matrix, wires))
with monkeypatch.context() as m:
m.setattr(dev, "_apply_unitary", mock_apply_tensordot)
dev._apply_operation(test_state, op)
res_state, res_mat, res_wires = history[0]
assert np.allclose(res_state, test_state)
assert np.all... | 256 | 256 | 1,055 | 6 | 250 | mauriceweber/pennylane | tests/devices/test_default_qubit.py | Python | TestHamiltonianSupport | TestHamiltonianSupport | 2,419 | 2,528 | 2,419 | 2,419 | 9b44381c97dd9310964d853056a3cd590a58ac72 | bigcode/the-stack | train |
2e0a0b561d14b31fc0869071 | train | class | @pytest.mark.parametrize("theta,phi,varphi", list(zip(THETA, PHI, VARPHI)))
class TestTensorExpval:
"""Test tensor expectation values"""
def test_paulix_pauliy(self, theta, phi, varphi, tol):
"""Test that a tensor product involving PauliX and PauliY works correctly"""
dev = qml.device("default.... | @pytest.mark.parametrize("theta,phi,varphi", list(zip(THETA, PHI, VARPHI)))
class TestTensorExpval:
| """Test tensor expectation values"""
def test_paulix_pauliy(self, theta, phi, varphi, tol):
"""Test that a tensor product involving PauliX and PauliY works correctly"""
dev = qml.device("default.qubit", wires=3)
dev.reset()
obs = qml.PauliX(0) @ qml.PauliY(2)
dev.apply... | ])
return qml.sample(qml.PauliZ(0)), qml.sample(qml.PauliZ(1))
outcomes = circuit()
assert np.array_equal(outcomes[0], outcomes[1])
@pytest.mark.parametrize("num_wires", [3, 4, 5, 6, 7, 8])
def test_multi_samples_return_correlated_results_more_wires_than_size_of_observable(
... | 256 | 256 | 2,129 | 29 | 227 | mauriceweber/pennylane | tests/devices/test_default_qubit.py | Python | TestTensorExpval | TestTensorExpval | 1,348 | 1,556 | 1,348 | 1,349 | bbdfc433ddc3facf34f4003710a50c679899e094 | bigcode/the-stack | train |
75ca8a4d978a681192099e7b | train | class | class TestWiresIntegration:
"""Test that the device integrates with PennyLane's wire management."""
def make_circuit_probs(self, wires):
"""Factory for a qnode returning probabilities using arbitrary wire labels."""
dev = qml.device("default.qubit", wires=wires)
n_wires = len(wires)
... | class TestWiresIntegration:
| """Test that the device integrates with PennyLane's wire management."""
def make_circuit_probs(self, wires):
"""Factory for a qnode returning probabilities using arbitrary wire labels."""
dev = qml.device("default.qubit", wires=wires)
n_wires = len(wires)
@qml.qnode(dev, diff_m... | =tol, rtol=0)
assert np.allclose(prob_analytic(x), prob(x), atol=0.1, rtol=0)
assert not np.array_equal(prob_analytic(x), prob(x))
def test_call_generate_samples(self, monkeypatch):
"""Test analytic_probability call when generating samples"""
self.analytic_counter = False
d... | 218 | 218 | 728 | 6 | 211 | mauriceweber/pennylane | tests/devices/test_default_qubit.py | Python | TestWiresIntegration | TestWiresIntegration | 1,953 | 2,024 | 1,953 | 1,953 | a96e7dbb814dcda28e8024122304aca01c4e5c35 | bigcode/the-stack | train |
6f6ae1655752aa43d2d8b5f8 | train | function | def test_analytic_deprecation():
"""Tests if the kwarg `analytic` is used and displays error message."""
msg = "The analytic argument has been replaced by shots=None. "
msg += "Please use shots=None instead of analytic=True."
with pytest.raises(
DeviceError,
match=msg,
):
qm... | def test_analytic_deprecation():
| """Tests if the kwarg `analytic` is used and displays error message."""
msg = "The analytic argument has been replaced by shots=None. "
msg += "Please use shots=None instead of analytic=True."
with pytest.raises(
DeviceError,
match=msg,
):
qml.device("default.qubit", wires=1... | )
VARPHI = np.linspace(0.02, 1, 3)
def include_inverses_with_test_data(test_data):
return test_data + [(item[0] + ".inv", item[1], item[2]) for item in test_data]
def test_analytic_deprecation():
| 64 | 64 | 88 | 7 | 57 | mauriceweber/pennylane | tests/devices/test_default_qubit.py | Python | test_analytic_deprecation | test_analytic_deprecation | 93 | 102 | 93 | 93 | 59cbac2d8b95ea417f90c9ae2c004fcfa63c86c9 | bigcode/the-stack | train |
3991743729c8e9216a7406e4 | train | class | @pytest.mark.parametrize("inverse", [True, False])
class TestApplyOps:
"""Tests for special methods listed in _apply_ops that use array manipulation tricks to apply
gates in DefaultQubit."""
state = np.arange(2**4).reshape((2, 2, 2, 2))
dev = qml.device("default.qubit", wires=4)
single_qubit_ops = ... | @pytest.mark.parametrize("inverse", [True, False])
class TestApplyOps:
| """Tests for special methods listed in _apply_ops that use array manipulation tricks to apply
gates in DefaultQubit."""
state = np.arange(2**4).reshape((2, 2, 2, 2))
dev = qml.device("default.qubit", wires=4)
single_qubit_ops = [
(qml.PauliX, dev._apply_x),
(qml.PauliY, dev._apply_y... | (27).reshape((3, 3, 3))
target = array[2]
assert sl == (2, slice(None, None, None), slice(None, None, None))
assert np.allclose(array[sl], target)
def test_get_slice_last(self):
"""Test that the _get_slice function returns the expected slice when accessing the last
axis of ... | 256 | 256 | 1,146 | 16 | 240 | mauriceweber/pennylane | tests/devices/test_default_qubit.py | Python | TestApplyOps | TestApplyOps | 2,075 | 2,161 | 2,075 | 2,076 | 0b559117a2605b2ed0659368c8a0662dacb01853 | bigcode/the-stack | train |
a9bc0c9f4b9f4a3e45128481 | train | function | def include_inverses_with_test_data(test_data):
return test_data + [(item[0] + ".inv", item[1], item[2]) for item in test_data]
| def include_inverses_with_test_data(test_data):
| return test_data + [(item[0] + ".inv", item[1], item[2]) for item in test_data]
| 0j]])
THETA = np.linspace(0.11, 1, 3)
PHI = np.linspace(0.32, 1, 3)
VARPHI = np.linspace(0.02, 1, 3)
def include_inverses_with_test_data(test_data):
| 64 | 64 | 39 | 11 | 53 | mauriceweber/pennylane | tests/devices/test_default_qubit.py | Python | include_inverses_with_test_data | include_inverses_with_test_data | 89 | 90 | 89 | 89 | f014812c1a312ffd963302230ca87800ef7bd335 | bigcode/the-stack | train |
3ac4f205df7c2ed57bc253c5 | train | class | @pytest.mark.parametrize("theta, phi, varphi", list(zip(THETA, PHI, VARPHI)))
class TestTensorVar:
"""Tests for variance of tensor observables"""
def test_paulix_pauliy(self, theta, phi, varphi, tol):
"""Test that a tensor product involving PauliX and PauliY works correctly"""
dev = qml.device(... | @pytest.mark.parametrize("theta, phi, varphi", list(zip(THETA, PHI, VARPHI)))
class TestTensorVar:
| """Tests for variance of tensor observables"""
def test_paulix_pauliy(self, theta, phi, varphi, tol):
"""Test that a tensor product involving PauliX and PauliY works correctly"""
dev = qml.device("default.qubit", wires=3)
obs = qml.PauliX(0) @ qml.PauliY(2)
dev.apply(
... | ], [1.61296440 + 0.3498192j, 1.23920938 + 0j]]
)
Identity = np.array([[1, 0], [0, 1]])
H = np.kron(np.kron(Identity, Identity), A)
obs = qml.Hermitian(H, wires=[2, 1, 0])
dev.apply(
[qml.RY(theta, wires=[0]), qml.RY(phi, wires=[1]), qml.CNOT(wires=[0, 1])],
... | 256 | 256 | 1,186 | 29 | 227 | mauriceweber/pennylane | tests/devices/test_default_qubit.py | Python | TestTensorVar | TestTensorVar | 1,559 | 1,680 | 1,559 | 1,560 | 273f11ee9163a2f0e1b1372e1dc84b7feac17d0c | bigcode/the-stack | train |
d2ff5cd29de1b5aca87e5ec0 | train | class | class TestDefaultQubitIntegration:
"""Integration tests for default.qubit. This test ensures it integrates
properly with the PennyLane interface, in particular QNode."""
def test_defines_correct_capabilities(self):
"""Test that the device defines the right capabilities"""
dev = qml.device(... | class TestDefaultQubitIntegration:
| """Integration tests for default.qubit. This test ensures it integrates
properly with the PennyLane interface, in particular QNode."""
def test_defines_correct_capabilities(self):
"""Test that the device defines the right capabilities"""
dev = qml.device("default.qubit", wires=1)
c... | dev._wires_measured = {0, 1}
dev._samples = dev.generate_samples()
s3 = dev.sample(qml.PauliX(0) @ qml.PauliZ(1))
assert np.array_equal(s3.shape, (17,))
def test_sample_values(self, qubit_device_2_wires, tol):
"""Tests if the samples returned by sample have
the corre... | 256 | 256 | 2,428 | 7 | 249 | mauriceweber/pennylane | tests/devices/test_default_qubit.py | Python | TestDefaultQubitIntegration | TestDefaultQubitIntegration | 1,108 | 1,345 | 1,108 | 1,108 | 867bdff02ead8eadb115060b6530b31ab3ecafe9 | bigcode/the-stack | train |
27c9ae46471a36343718c8c1 | train | class | class TestStateVector:
"""Unit tests for the _apply_state_vector method"""
def test_full_subsystem(self, mocker):
"""Test applying a state vector to the full subsystem"""
dev = DefaultQubit(wires=["a", "b", "c"])
state = np.array([1, 0, 0, 0, 1, 0, 1, 1]) / 2.0
state_wires = qml... | class TestStateVector:
| """Unit tests for the _apply_state_vector method"""
def test_full_subsystem(self, mocker):
"""Test applying a state vector to the full subsystem"""
dev = DefaultQubit(wires=["a", "b", "c"])
state = np.array([1, 0, 0, 0, 1, 0, 1, 1]) / 2.0
state_wires = qml.wires.Wires(["a", "b",... | 2])
op = op(wires=[3, 1, 2])
matrix = op.inv().matrix() if inverse else op.matrix()
matrix = matrix.reshape((2, 2) * 3)
state_out_einsum = np.einsum("abcdef,kdfe->kacb", matrix, self.state)
assert np.allclose(state_out, state_out_einsum)
class TestStateVector:
| 91 | 91 | 304 | 5 | 86 | mauriceweber/pennylane | tests/devices/test_default_qubit.py | Python | TestStateVector | TestStateVector | 2,164 | 2,191 | 2,164 | 2,164 | a9dc66c3218cf36ec9b3f7ff7347465e34396f4a | bigcode/the-stack | train |
07fab079dd68d3057b4430ff | train | class | class TestProbabilityIntegration:
"""Test probability method for when analytic is True/False"""
def mock_analytic_counter(self, wires=None):
self.analytic_counter += 1
return np.array([1, 0, 0, 0], dtype=float)
@pytest.mark.parametrize("x", [[0.2, 0.5], [0.4, 0.9], [0.8, 0.3]])
def tes... | class TestProbabilityIntegration:
| """Test probability method for when analytic is True/False"""
def mock_analytic_counter(self, wires=None):
self.analytic_counter += 1
return np.array([1, 0, 0, 0], dtype=float)
@pytest.mark.parametrize("x", [[0.2, 0.5], [0.4, 0.9], [0.8, 0.3]])
def test_probability(self, x, tol):
... | qml.density_matrix(wires=[2, 0])],
)
def test_complex_dtype(self, qubit_device_3_wires, c_dtype, measurement, tol):
"""Test that the default qubit plugin provides correct result for a simple circuit"""
p = 0.543
dev = qubit_device_3_wires
dev.C_DTYPE = c_dtype
@qml.qno... | 141 | 141 | 471 | 5 | 135 | mauriceweber/pennylane | tests/devices/test_default_qubit.py | Python | TestProbabilityIntegration | TestProbabilityIntegration | 1,906 | 1,950 | 1,906 | 1,906 | 85234bc73b67ad3f14cbcab38a945f0e6cac8bc3 | bigcode/the-stack | train |
b5c3bbc78c972a2808736fb2 | train | class | class TestApply:
"""Tests that operations and inverses of certain operations are applied correctly or that the proper
errors are raised.
"""
test_data_no_parameters = [
(qml.PauliX, [1, 0], np.array([0, 1])),
(qml.PauliX, [1 / math.sqrt(2), 1 / math.sqrt(2)], [1 / math.sqrt(2), 1 / math... | class TestApply:
| """Tests that operations and inverses of certain operations are applied correctly or that the proper
errors are raised.
"""
test_data_no_parameters = [
(qml.PauliX, [1, 0], np.array([0, 1])),
(qml.PauliX, [1 / math.sqrt(2), 1 / math.sqrt(2)], [1 / math.sqrt(2), 1 / math.sqrt(2)]),
... | 0, 0, 0, 0, 0, 0, 1],
]
)
H = np.array([[1.02789352, 1.61296440 - 0.3498192j], [1.61296440 + 0.3498192j, 1.23920938 + 0j]])
THETA = np.linspace(0.11, 1, 3)
PHI = np.linspace(0.32, 1, 3)
VARPHI = np.linspace(0.02, 1, 3)
def include_inverses_with_test_data(test_data):
return test_data + [(item[0] + ".inv", i... | 256 | 256 | 9,534 | 4 | 252 | mauriceweber/pennylane | tests/devices/test_default_qubit.py | Python | TestApply | TestApply | 105 | 789 | 105 | 105 | f4c588c64c6d24799df3909f53a7ac71002d3d89 | bigcode/the-stack | train |
fc50d11dff6c62d443f434c5 | train | class | class TestApplyOperationUnit:
"""Unit tests for the internal _apply_operation method."""
@pytest.mark.parametrize("inverse", [True, False])
def test_internal_apply_ops_case(self, inverse, monkeypatch):
"""Tests that if we provide an operation that has an internal
implementation, then we use... | class TestApplyOperationUnit:
| """Unit tests for the internal _apply_operation method."""
@pytest.mark.parametrize("inverse", [True, False])
def test_internal_apply_ops_case(self, inverse, monkeypatch):
"""Tests that if we provide an operation that has an internal
implementation, then we use that specific implementation.... | qml.S(wires=0)
return qml.probs(wires=0)
test_s()
operations = spy.call_args[0][0].operations
assert "S" not in [i.name for i in operations]
assert "PhaseShift" in [i.name for i in operations]
expected = np.array([1.0, 1.0j]) / np.sqrt(2)
assert np.allclose... | 256 | 256 | 1,324 | 6 | 250 | mauriceweber/pennylane | tests/devices/test_default_qubit.py | Python | TestApplyOperationUnit | TestApplyOperationUnit | 2,268 | 2,416 | 2,268 | 2,268 | 6aa029fe72e2f49b51c3e75d9e0ce75e26b75c90 | bigcode/the-stack | train |
a336aea1323005463ccaad9b | train | class | class GUIPalette(QWidget):
def __init__(self, grid_sz=(6, 3)):
QWidget.__init__(self)
self.color_width = 25
self.border = 6
self.win_width = grid_sz[0] * self.color_width + (grid_sz[0]+1) * self.border
self.win_height = grid_sz[1] * self.color_width + (grid_sz[1]+1) * self.bo... | class GUIPalette(QWidget):
| def __init__(self, grid_sz=(6, 3)):
QWidget.__init__(self)
self.color_width = 25
self.border = 6
self.win_width = grid_sz[0] * self.color_width + (grid_sz[0]+1) * self.border
self.win_height = grid_sz[1] * self.color_width + (grid_sz[1]+1) * self.border
self.setFixedS... | from PyQt4.QtCore import *
from PyQt4.QtGui import *
# import cv2
import numpy as np
class GUIPalette(QWidget):
| 32 | 232 | 775 | 6 | 25 | excalib/interactive-deep-colorization | ui/gui_palette.py | Python | GUIPalette | GUIPalette | 6 | 96 | 6 | 6 | a9ccb810aa3d88a605feeb6428e95dcd3307ddb6 | bigcode/the-stack | train |
9394fae80607f404519eff86 | train | function | def process_paragraph( paragraph ):
""" The function will return lists of bounding boxes, lines' text, and lines' probabilities
"""
# Lists of bounding boxes, text, and probabilities
line_box_list = []
line_text_list = []
line_prob_list = []
# Line under processing
current_line_text = []
current_line_prob = [... | def process_paragraph( paragraph ):
| """ The function will return lists of bounding boxes, lines' text, and lines' probabilities
"""
# Lists of bounding boxes, text, and probabilities
line_box_list = []
line_text_list = []
line_prob_list = []
# Line under processing
current_line_text = []
current_line_prob = []
# Bounding box temporary variable... | content_prob_file += lines_texts[i][j] + '\t' + str(lines_probs[i][j]) + '\n'
j = j + 1
# Write to disk the text file
text_filename = output_dir_name + "/" + basename + "_" + n_line + ".txt"
with open( text_filename, "w+" ) as f_text:
f_text.write( content_text_file )
# Write to disk the probabilities ... | 172 | 172 | 576 | 7 | 164 | acislab/HuMaIN_OCR_Quality_Improvement | src/get_lines_google.py | Python | process_paragraph | process_paragraph | 108 | 166 | 108 | 108 | 2ff33211e52f44280c1cde656ce631ef5c93c2a6 | bigcode/the-stack | train |
5e64edc778723c9becd38a78 | train | function | def crop_save( img_path_filename, lines_boxes, lines_texts, lines_probs, filename, basename, output_dir_name ):
""" Crop and save the image for each line, its text files, and its probabilities files. It also returns the bbox statistics.
"""
# Read the image
image = Image.open( img_path_filename )
# Get image's s... | def crop_save( img_path_filename, lines_boxes, lines_texts, lines_probs, filename, basename, output_dir_name ):
| """ Crop and save the image for each line, its text files, and its probabilities files. It also returns the bbox statistics.
"""
# Read the image
image = Image.open( img_path_filename )
# Get image's size
width, height = image.size
i = 0
text_local = ""
text_global = ""
while i < len(lines_boxes):
#######... | .ufl.edu/)
# 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 to in writing, software
# distributed... | 205 | 205 | 684 | 27 | 177 | acislab/HuMaIN_OCR_Quality_Improvement | src/get_lines_google.py | Python | crop_save | crop_save | 37 | 105 | 37 | 37 | 5b63bfd3006a996ce53058bbedd0832d1225e384 | bigcode/the-stack | train |
4135f5220c6f7f0d6ff8a881 | train | function | def process_image( img_path_filename, output_dir_name, output_path_filename):
""" Crop the text paragraphs and save the information about the cropped files
"""
########################### Google OCR #############################
client = vision.ImageAnnotatorClient()
lines_boxes_img = []
lines_texts_img = []
li... | def process_image( img_path_filename, output_dir_name, output_path_filename):
| """ Crop the text paragraphs and save the information about the cropped files
"""
########################### Google OCR #############################
client = vision.ImageAnnotatorClient()
lines_boxes_img = []
lines_texts_img = []
lines_probs_img = []
# Path + Base name for the block files
filename = img_pa... | if symbol.property.detected_break.type in [ breaks.EOL_SURE_SPACE, breaks.HYPHEN, breaks.LINE_BREAK ]:
line_box_list.append( [x1, y1, x2, y2] )
line_text_list.append( current_line_text )
line_prob_list.append( current_line_prob )
# Line under processing
current_line_text = []
current_line_pro... | 159 | 159 | 532 | 16 | 142 | acislab/HuMaIN_OCR_Quality_Improvement | src/get_lines_google.py | Python | process_image | process_image | 169 | 224 | 169 | 169 | 0914ba3d18cf5038067cb10797d1d40ac16305d1 | bigcode/the-stack | train |
c2c00687076830d270b30140 | train | class | class Mozjs(AutotoolsPackage):
"""SpiderMonkey is Mozilla's JavaScript engine written in C/C++.
It is used in various Mozilla products, including Firefox, and is
available under the MPL2."""
homepage = "https://firefox-source-docs.mozilla.org/js/index.html"
version('24.2.0', sha256='e62f3f331ddd90... | class Mozjs(AutotoolsPackage):
| """SpiderMonkey is Mozilla's JavaScript engine written in C/C++.
It is used in various Mozilla products, including Firefox, and is
available under the MPL2."""
homepage = "https://firefox-source-docs.mozilla.org/js/index.html"
version('24.2.0', sha256='e62f3f331ddd90df1e238c09d61a505c516fe9fd8c5c9... | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Mozjs(AutotoolsPackage):
| 63 | 235 | 784 | 9 | 54 | pbrady/spack | var/spack/repos/builtin/packages/mozjs/package.py | Python | Mozjs | Mozjs | 9 | 59 | 9 | 9 | f4a2b722b126e48fccb57abdd354e9e7bc746d1c | bigcode/the-stack | train |
8700105939a060cb7be05bc7 | train | function | def mensaje():
#emisor = "manizshinigami@gmail.com"
emisor = "som@compusoluciones.com"
receptor = "juruiz@compusoluciones.com"
# Configuracion del mail
html = """\
<html>
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" type="image/png" href="https://scontent.fgdl3-1.fna.fbcdn.net/... | def mensaje():
#emisor = "manizshinigami@gmail.com"
| emisor = "som@compusoluciones.com"
receptor = "juruiz@compusoluciones.com"
# Configuracion del mail
html = """\
<html>
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" type="image/png" href="https://scontent.fgdl3-1.fna.fbcdn.net/v/t1.0-1/p50x50/12734268_1063128193753865_101392577374515... | #!/usr/bin/python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
#Correo de SOM
# som@compusoluciones.com
# 123123Abc
#smtp = outlook.365.com
#993
def mensaje():
#emisor = "manizshinigami@gmail.com"
| 87 | 256 | 999 | 18 | 68 | shinigami39/plataforma | bienvenida.py | Python | mensaje | mensaje | 14 | 87 | 14 | 15 | 2f7c1bbe66962cbbf3fbf5bb291fd3b2ac9ac7b0 | bigcode/the-stack | train |
85c77b708c6aacdd127001a9 | train | function | def sleep_ms(milliseconds):
"""Sleep for the specified number of milliseconds.
Args:
milliseconds (int, long, float): duration in milliseconds.
"""
time.sleep(milliseconds / 1000.0)
| def sleep_ms(milliseconds):
| """Sleep for the specified number of milliseconds.
Args:
milliseconds (int, long, float): duration in milliseconds.
"""
time.sleep(milliseconds / 1000.0)
| "
"Module version string."
version = (2, 0, 1)
"Module version tuple."
def sleep(seconds):
"""Sleep for the specified number of seconds.
Args:
seconds (int, long, float): duration in seconds.
"""
time.sleep(seconds)
def sleep_ms(milliseconds):
| 64 | 64 | 44 | 5 | 59 | webmeister/python-periphery | periphery/__init__.py | Python | sleep_ms | sleep_ms | 20 | 27 | 20 | 20 | 84b9d93ec2534acbd1dcb33cb6ded0fa3f9e1b2d | bigcode/the-stack | train |
1f06f25f3dfbe43406f4cc6f | train | function | def sleep_us(microseconds):
"""Sleep for the specified number of microseconds.
Args:
microseconds (int, long, float): duration in microseconds.
"""
time.sleep(microseconds / 1000000.0)
| def sleep_us(microseconds):
| """Sleep for the specified number of microseconds.
Args:
microseconds (int, long, float): duration in microseconds.
"""
time.sleep(microseconds / 1000000.0)
| float): duration in seconds.
"""
time.sleep(seconds)
def sleep_ms(milliseconds):
"""Sleep for the specified number of milliseconds.
Args:
milliseconds (int, long, float): duration in milliseconds.
"""
time.sleep(milliseconds / 1000.0)
def sleep_us(microseconds):
| 64 | 64 | 52 | 7 | 57 | webmeister/python-periphery | periphery/__init__.py | Python | sleep_us | sleep_us | 30 | 37 | 30 | 30 | 9e8796a1b2500cd2305e363f5bf634fbb0fad4b5 | bigcode/the-stack | train |
04dbbfd75045b927f7dfe80e | train | function | def sleep(seconds):
"""Sleep for the specified number of seconds.
Args:
seconds (int, long, float): duration in seconds.
"""
time.sleep(seconds)
| def sleep(seconds):
| """Sleep for the specified number of seconds.
Args:
seconds (int, long, float): duration in seconds.
"""
time.sleep(seconds)
| import time
__version__ = "2.0.1"
"Module version string."
version = (2, 0, 1)
"Module version tuple."
def sleep(seconds):
| 39 | 64 | 37 | 4 | 35 | webmeister/python-periphery | periphery/__init__.py | Python | sleep | sleep | 10 | 17 | 10 | 10 | 38364c976785537b4de16d77e7eb7ff997d1398b | bigcode/the-stack | train |
339652151932d1c8902d10cf | train | function | def alpha_beta_pruning(curr_node, player, abp_class, forbidden_moves):
alpha = abp_class.get_alpha()
beta = abp_class.get_beta()
score = utils.calculate_score(curr_node.get_board(), player)
if score in [math.inf, -math.inf]:
curr_node.set_score(score)
return score
if curr_node.get_depth() == 2:
curr_node.... | def alpha_beta_pruning(curr_node, player, abp_class, forbidden_moves):
| alpha = abp_class.get_alpha()
beta = abp_class.get_beta()
score = utils.calculate_score(curr_node.get_board(), player)
if score in [math.inf, -math.inf]:
curr_node.set_score(score)
return score
if curr_node.get_depth() == 2:
curr_node.set_score(score)
return score
moves = utils.get_available_moves(cur... | import copy
import node
import utils
import math
import heuristics as h
def alpha_beta_pruning(curr_node, player, abp_class, forbidden_moves):
| 35 | 170 | 569 | 17 | 17 | douglasscorrea/boku-player | alpha_beta_pruning.py | Python | alpha_beta_pruning | alpha_beta_pruning | 7 | 80 | 7 | 7 | 2bd01ef5960bb1ff4f766eb6e8b90242397320d4 | bigcode/the-stack | train |
8d2d46aaee607511cbd0ee12 | train | class | class Pipeline(object):
__head = None
__tail = None
__ctxFactory = None
def __init__(self, ctxFactory):
self.__ctxFactory = ctxFactory
def addLast(self, handler):
if handler is None:
raise Exception("handler was None")
else:
print(" Pipeline: a... | class Pipeline(object):
| __head = None
__tail = None
__ctxFactory = None
def __init__(self, ctxFactory):
self.__ctxFactory = ctxFactory
def addLast(self, handler):
if handler is None:
raise Exception("handler was None")
else:
print(" Pipeline: adding handler " + str(han... | import abc
class Pipeline(object):
| 7 | 146 | 487 | 4 | 2 | CodeLionX/CommentSearchEngine | cse/pipeline/Pipeline.py | Python | Pipeline | Pipeline | 3 | 87 | 3 | 4 | 2065bd3a38e23e56bb0e7857bd918c539bb1a528 | bigcode/the-stack | train |
cbacdd714e94ebc8d3d11090 | train | class | class RacesView(View):
"""Class representing races resource."""
async def get(self) -> Response:
"""Get route function."""
db = self.request.app["db"]
if "eventId" in self.request.rel_url.query:
event_id = self.request.rel_url.query["eventId"]
if "racec... | class RacesView(View):
| """Class representing races resource."""
async def get(self) -> Response:
"""Get route function."""
db = self.request.app["db"]
if "eventId" in self.request.rel_url.query:
event_id = self.request.rel_url.query["eventId"]
if "raceclass" in self.request.re... | TimeEventsService,
)
from .utils import extract_token_from_request
load_dotenv()
HOST_SERVER = os.getenv("HOST_SERVER", "localhost")
HOST_PORT = os.getenv("HOST_PORT", "8080")
BASE_URL = f"http://{HOST_SERVER}:{HOST_PORT}"
class RacesView(View):
| 63 | 64 | 208 | 6 | 57 | langrenn-sprint/race-service | race_service/views/races.py | Python | RacesView | RacesView | 41 | 64 | 41 | 41 | 070fda69c02d426c72d294f6f4bae412b5dd2608 | bigcode/the-stack | train |
bacf274f345f42fda4034f90 | train | class | class RaceView(View):
"""Class representing a single race resource."""
async def get(self) -> Response:
"""Get route function."""
db = self.request.app["db"]
race_id = self.request.match_info["raceId"]
logging.debug(f"Got get request for race {race_id}")
try:... | class RaceView(View):
| """Class representing a single race resource."""
async def get(self) -> Response:
"""Get route function."""
db = self.request.app["db"]
race_id = self.request.match_info["raceId"]
logging.debug(f"Got get request for race {race_id}")
try:
race = aw... | ()
HOST_SERVER = os.getenv("HOST_SERVER", "localhost")
HOST_PORT = os.getenv("HOST_PORT", "8080")
BASE_URL = f"http://{HOST_SERVER}:{HOST_PORT}"
class RacesView(View):
"""Class representing races resource."""
async def get(self) -> Response:
"""Get route function."""
db = self.requ... | 253 | 254 | 849 | 5 | 248 | langrenn-sprint/race-service | race_service/views/races.py | Python | RaceView | RaceView | 67 | 171 | 67 | 67 | c5bf67bbeb8af601e00786a1da2d4058956cbbed | bigcode/the-stack | train |
ac972aa387171aae0981eb52 | train | class | class AssignmentTests(assignment_tests.AssignmentTests):
def test_get_role_assignment_by_domain_not_found(self):
self.skip_test_overrides('N/A: LDAP does not support multiple domains')
def test_del_role_assignment_by_domain_not_found(self):
self.skip_test_overrides('N/A: LDAP does not support ... | class AssignmentTests(assignment_tests.AssignmentTests):
| def test_get_role_assignment_by_domain_not_found(self):
self.skip_test_overrides('N/A: LDAP does not support multiple domains')
def test_del_role_assignment_by_domain_not_found(self):
self.skip_test_overrides('N/A: LDAP does not support multiple domains')
def test_get_and_remove_role_grant... | _test_overrides('N/A: LDAP does not support multiple domains')
def test_move_user_between_domains(self):
self.skip_test_overrides('Domains are read-only against LDAP')
def test_move_group_between_domains(self):
self.skip_test_overrides('N/A: LDAP does not support multiple domains')
def te... | 168 | 168 | 563 | 10 | 158 | jiwanlimbu/aura | keystone/tests/unit/test_backend_ldap.py | Python | AssignmentTests | AssignmentTests | 156 | 213 | 156 | 157 | 63dc58950570d3092b55573f534dcd339f680ac8 | bigcode/the-stack | train |
e5ec1c330437829ce3345282 | train | class | class LdapFilterTests(identity_tests.FilterTests, LDAPTestSetup):
def setUp(self):
self.useFixture(database.Database())
super(LdapFilterTests, self).setUp()
_assert_backends(self, identity='ldap')
def config_overrides(self):
super(LdapFilterTests, self).config_overrides()
... | class LdapFilterTests(identity_tests.FilterTests, LDAPTestSetup):
| def setUp(self):
self.useFixture(database.Database())
super(LdapFilterTests, self).setUp()
_assert_backends(self, identity='ldap')
def config_overrides(self):
super(LdapFilterTests, self).config_overrides()
self.config_fixture.config(group='identity', driver='ldap')
... | ,
# which should fail.
self.assertRaises(
exception.MultipleSQLDriversInConfig,
self.identity_api.domain_configs._load_config_from_file,
self.resource_api,
[unit.TESTCONF + '/domain_configs_one_extra_sql/' +
'keystone.domain2.conf'],
... | 79 | 79 | 265 | 14 | 65 | jiwanlimbu/aura | keystone/tests/unit/test_backend_ldap.py | Python | LdapFilterTests | LdapFilterTests | 3,096 | 3,123 | 3,096 | 3,097 | 194f78a43e34d31643dd8feeb1828357e83aa883 | bigcode/the-stack | train |
df3678929f710f2bc251c9ee | train | class | class LDAPPosixGroupsTest(LDAPTestSetup):
def setUp(self):
self.useFixture(database.Database())
super(LDAPPosixGroupsTest, self).setUp()
_assert_backends(self, identity='ldap')
def load_fixtures(self, fixtures):
# Override super impl since need to create group container.
... | class LDAPPosixGroupsTest(LDAPTestSetup):
| def setUp(self):
self.useFixture(database.Database())
super(LDAPPosixGroupsTest, self).setUp()
_assert_backends(self, identity='ldap')
def load_fixtures(self, fixtures):
# Override super impl since need to create group container.
create_group_container(self.identity_api)... | it's used to build the enabled member filter
mixin_impl.tree_dn = sample_dn
# The filter that _get_enabled is going to build contains the
# tree_dn, which better be escaped in this case.
exp_filter = '(%s=%s=%s,%s)' % (
mixin_impl.member_attribute, mixin_impl.id_attr, objec... | 166 | 166 | 555 | 11 | 155 | jiwanlimbu/aura | keystone/tests/unit/test_backend_ldap.py | Python | LDAPPosixGroupsTest | LDAPPosixGroupsTest | 2,051 | 2,104 | 2,051 | 2,052 | 93b89f55561dd62d2a7ab05749a9c648329ed0b9 | bigcode/the-stack | train |
eb847b73b632a2572f0537d6 | train | class | class LDAPIdentityEnabledEmulation(LDAPIdentity):
def setUp(self):
super(LDAPIdentityEnabledEmulation, self).setUp()
_assert_backends(self, identity='ldap')
def load_fixtures(self, fixtures):
# Override super impl since need to create group container.
create_group_container(self... | class LDAPIdentityEnabledEmulation(LDAPIdentity):
| def setUp(self):
super(LDAPIdentityEnabledEmulation, self).setUp()
_assert_backends(self, identity='ldap')
def load_fixtures(self, fixtures):
# Override super impl since need to create group container.
create_group_container(self.identity_api)
super(LDAPIdentity, self).l... | ': ['crap']
}
)
user_ref = self.identity_api.get_user('crap')
self.assertEqual('crap', user_ref['id'])
self.assertEqual('Foo Bar', user_ref['name'])
class LDAPLimitTests(unit.TestCase, identity_tests.LimitTests):
def setUp(self):
super(LDAPLimitTests, self).setU... | 256 | 256 | 2,428 | 10 | 245 | jiwanlimbu/aura | keystone/tests/unit/test_backend_ldap.py | Python | LDAPIdentityEnabledEmulation | LDAPIdentityEnabledEmulation | 1,795 | 2,048 | 1,795 | 1,795 | 502347988e98df236d16492406cbcfabbb01f284 | bigcode/the-stack | train |
c2473b91cf78a43b3fc43646 | train | class | class LDAPIdentity(BaseLDAPIdentity, unit.TestCase):
def setUp(self):
# NOTE(dstanek): The database must be setup prior to calling the
# parent's setUp. The parent's setUp uses services (like
# credentials) that require a database.
self.useFixture(database.Database())
super(... | class LDAPIdentity(BaseLDAPIdentity, unit.TestCase):
| def setUp(self):
# NOTE(dstanek): The database must be setup prior to calling the
# parent's setUp. The parent's setUp uses services (like
# credentials) that require a database.
self.useFixture(database.Database())
super(LDAPIdentity, self).setUp()
_assert_backends(s... | , self).
test_list_role_assignment_by_user_with_domain_group_roles)
def test_list_role_assignment_using_sourced_groups_with_domains(self):
"""Multiple domain assignments are not supported."""
self.assertRaises(
(exception.Forbidden, exception.ValidationError,
ex... | 256 | 256 | 6,590 | 11 | 245 | jiwanlimbu/aura | keystone/tests/unit/test_backend_ldap.py | Python | LDAPIdentity | LDAPIdentity | 1,042 | 1,766 | 1,042 | 1,043 | 230da118eed25b1634fd173d2f76fd6d45ad0aac | bigcode/the-stack | train |
f303c9e34da1499b6067870f | train | class | class MultiLDAPandSQLIdentityDomainConfigsInSQL(MultiLDAPandSQLIdentity):
"""Class to test the use of domain configs stored in the database.
Repeat the same tests as MultiLDAPandSQLIdentity, but instead of using the
domain specific config files, store the domain specific values in the
database.
""... | class MultiLDAPandSQLIdentityDomainConfigsInSQL(MultiLDAPandSQLIdentity):
| """Class to test the use of domain configs stored in the database.
Repeat the same tests as MultiLDAPandSQLIdentity, but instead of using the
domain specific config files, store the domain specific values in the
database.
"""
def assert_backends(self):
_assert_backends(self,
... | _group_roles()
def test_list_role_assignment_using_sourced_groups_with_domains(self):
# With SQL Assignment this method should work, so override the override
# from BaseLDAPIdentity
base = super(BaseLDAPIdentity, self)
base.test_list_role_assignment_using_sourced_groups_with_domains... | 256 | 256 | 1,887 | 17 | 239 | jiwanlimbu/aura | keystone/tests/unit/test_backend_ldap.py | Python | MultiLDAPandSQLIdentityDomainConfigsInSQL | MultiLDAPandSQLIdentityDomainConfigsInSQL | 2,610 | 2,815 | 2,610 | 2,610 | 02905d8d8c9edd07b815a9768f5c839d6637b829 | bigcode/the-stack | train |
5d32c14dfc3060ee1be3e11a | train | class | class DomainSpecificLDAPandSQLIdentity(
BaseLDAPIdentity, unit.SQLDriverOverrides, unit.TestCase,
BaseMultiLDAPandSQLIdentity):
"""Class to test when all domains use specific configs, including SQL.
We define a set of domains and domain-specific backends:
- A separate LDAP backend for the defa... | class DomainSpecificLDAPandSQLIdentity(
BaseLDAPIdentity, unit.SQLDriverOverrides, unit.TestCase,
BaseMultiLDAPandSQLIdentity):
| """Class to test when all domains use specific configs, including SQL.
We define a set of domains and domain-specific backends:
- A separate LDAP backend for the default domain
- A separate SQL backend for domain1
Although the default driver still exists, we don't use it.
"""
DOMAIN_COU... | self.assertRaises(exception.MultipleSQLDriversInConfig,
self.identity_api.domain_configs.get_domain_conf,
self.domains['domain1']['id'])
# Now we delete the domain by using the backend driver directly,
# which causes the domain to be deleted without ... | 255 | 256 | 1,584 | 30 | 225 | jiwanlimbu/aura | keystone/tests/unit/test_backend_ldap.py | Python | DomainSpecificLDAPandSQLIdentity | DomainSpecificLDAPandSQLIdentity | 2,818 | 3,002 | 2,818 | 2,820 | 3a9daedb3f643be1849bd5718e8ba0c868800606 | bigcode/the-stack | train |
4a4b93efa801128ba21406bf | train | class | class ResourceTests(resource_tests.ResourceTests):
def test_create_duplicate_project_name_in_different_domains(self):
self.skip_test_overrides('Domains are read-only against LDAP')
def test_move_project_between_domains(self):
self.skip_test_overrides('Domains are read-only against LDAP')
... | class ResourceTests(resource_tests.ResourceTests):
| def test_create_duplicate_project_name_in_different_domains(self):
self.skip_test_overrides('Domains are read-only against LDAP')
def test_move_project_between_domains(self):
self.skip_test_overrides('Domains are read-only against LDAP')
def test_move_project_between_domains_with_clashing_... | rides('N/A: LDAP does not support multiple domains')
def test_get_roles_for_groups_on_domain(self):
self.skip_test_overrides(
'N/A: LDAP does not implement get_roles_for_groups; '
'see bug 1333712 for details')
def test_get_roles_for_groups_on_project(self):
self.skip_t... | 205 | 205 | 684 | 8 | 197 | jiwanlimbu/aura | keystone/tests/unit/test_backend_ldap.py | Python | ResourceTests | ResourceTests | 216 | 297 | 216 | 217 | 62cb2604e55ba5b2255e3b806eca49907aff1b4c | bigcode/the-stack | train |
15f89ea3a689a8898156ccb3 | train | class | class MultiLDAPandSQLIdentity(BaseLDAPIdentity, unit.SQLDriverOverrides,
unit.TestCase, BaseMultiLDAPandSQLIdentity):
"""Class to test common SQL plus individual LDAP backends.
We define a set of domains and domain-specific backends:
- A separate LDAP backend for the default ... | class MultiLDAPandSQLIdentity(BaseLDAPIdentity, unit.SQLDriverOverrides,
unit.TestCase, BaseMultiLDAPandSQLIdentity):
| """Class to test common SQL plus individual LDAP backends.
We define a set of domains and domain-specific backends:
- A separate LDAP backend for the default domain
- A separate LDAP backend for domain1
- domain2 shares the same LDAP as domain1, but uses a different
tree attach point
- A... | except expected_status:
pass
def setup_initial_domains(self):
def create_domain(domain):
try:
ref = self.resource_api.create_domain(
domain['id'], domain)
except exception.Conflict:
ref = (
... | 255 | 256 | 3,174 | 27 | 228 | jiwanlimbu/aura | keystone/tests/unit/test_backend_ldap.py | Python | MultiLDAPandSQLIdentity | MultiLDAPandSQLIdentity | 2,270 | 2,607 | 2,270 | 2,271 | ead568901e9454fcd03c867526ba72ec10690594 | bigcode/the-stack | train |
910c3e660f030532b7f3ecec | train | function | def _assert_backends(testcase, **kwargs):
def _get_backend_cls(testcase, subsystem):
observed_backend = getattr(testcase, subsystem + '_api').driver
return observed_backend.__class__
def _get_domain_specific_backend_cls(manager, domain):
observed_backend = manager.domain_configs.get_do... | def _assert_backends(testcase, **kwargs):
| def _get_backend_cls(testcase, subsystem):
observed_backend = getattr(testcase, subsystem + '_api').driver
return observed_backend.__class__
def _get_domain_specific_backend_cls(manager, domain):
observed_backend = manager.domain_configs.get_domain_driver(domain)
return observed... |
from keystone import identity
from keystone.identity.backends.ldap import common as common_ldap
from keystone.identity.mapping_backends import mapping as map
from keystone.tests import unit
from keystone.tests.unit.assignment import test_backends as assignment_tests
from keystone.tests.unit import default_fixtures
fro... | 155 | 155 | 518 | 11 | 143 | jiwanlimbu/aura | keystone/tests/unit/test_backend_ldap.py | Python | _assert_backends | _assert_backends | 50 | 111 | 50 | 51 | 94909261dd6c635fb8d1745eedea374b29c39667 | bigcode/the-stack | train |
a3a5d4db27d0277bbfb6d309 | train | class | class LDAPLimitTests(unit.TestCase, identity_tests.LimitTests):
def setUp(self):
super(LDAPLimitTests, self).setUp()
self.useFixture(ldapdb.LDAPDatabase())
self.useFixture(database.Database())
self.load_backends()
self.load_fixtures(default_fixtures)
identity_tests.L... | class LDAPLimitTests(unit.TestCase, identity_tests.LimitTests):
| def setUp(self):
super(LDAPLimitTests, self).setUp()
self.useFixture(ldapdb.LDAPDatabase())
self.useFixture(database.Database())
self.load_backends()
self.load_fixtures(default_fixtures)
identity_tests.LimitTests.setUp(self)
_assert_backends(self,
... | Name': ['crap']
}
)
user_ref = self.identity_api.get_user('crap')
self.assertEqual('crap', user_ref['id'])
self.assertEqual('Foo Bar', user_ref['name'])
class LDAPLimitTests(unit.TestCase, identity_tests.LimitTests):
| 63 | 64 | 197 | 14 | 49 | jiwanlimbu/aura | keystone/tests/unit/test_backend_ldap.py | Python | LDAPLimitTests | LDAPLimitTests | 1,769 | 1,792 | 1,769 | 1,769 | c77dc8fb852b84dde143b6e4051be82272e0e298 | bigcode/the-stack | train |
7bed7f69c36b651505a06598 | train | class | class IdentityTests(identity_tests.IdentityTests):
def test_delete_user_with_group_project_domain_links(self):
self.skip_test_overrides('N/A: LDAP does not support multiple domains')
def test_delete_group_with_user_project_domain_links(self):
self.skip_test_overrides('N/A: LDAP does not suppor... | class IdentityTests(identity_tests.IdentityTests):
| def test_delete_user_with_group_project_domain_links(self):
self.skip_test_overrides('N/A: LDAP does not support multiple domains')
def test_delete_group_with_user_project_domain_links(self):
self.skip_test_overrides('N/A: LDAP does not support multiple domains')
def test_create_duplicate_... | the groups base entry (ou=Groups,cn=example,cn=com)
group_api = identity_api.driver.group
conn = group_api.get_connection()
dn = 'ou=Groups,cn=example,cn=com'
conn.add_s(dn, [('objectclass', ['organizationalUnit']),
('ou', ['Groups'])])
class IdentityTests(identity_tests.IdentityTes... | 80 | 80 | 267 | 8 | 72 | jiwanlimbu/aura | keystone/tests/unit/test_backend_ldap.py | Python | IdentityTests | IdentityTests | 123 | 153 | 123 | 124 | 945bd7fd1db9787612eaf4342c0af1c6921f5749 | bigcode/the-stack | train |
4f50ad893051b3fe4669933f | train | class | class BaseLDAPIdentity(IdentityTests, AssignmentTests, ResourceTests):
def setUp(self):
super(BaseLDAPIdentity, self).setUp()
self.ldapdb = self.useFixture(ldapdb.LDAPDatabase())
self.load_backends()
self.load_fixtures(default_fixtures)
def _get_domain_fixture(self):
"... | class BaseLDAPIdentity(IdentityTests, AssignmentTests, ResourceTests):
| def setUp(self):
super(BaseLDAPIdentity, self).setUp()
self.ldapdb = self.useFixture(ldapdb.LDAPDatabase())
self.load_backends()
self.load_fixtures(default_fixtures)
def _get_domain_fixture(self):
"""Return the static domain, since domains in LDAP are read-only."""
... | has been removed')
def test_enable_project_with_disabled_parent(self):
self.skip_test_overrides('Resource LDAP has been removed')
def test_disable_hierarchical_leaf_project(self):
self.skip_test_overrides('Resource LDAP has been removed')
def test_disable_hierarchical_not_leaf_project(se... | 256 | 256 | 6,822 | 14 | 242 | jiwanlimbu/aura | keystone/tests/unit/test_backend_ldap.py | Python | BaseLDAPIdentity | BaseLDAPIdentity | 310 | 1,039 | 310 | 311 | cb7335dd9a87534ff63a9906e80ee480d1ed9c89 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.