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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
70b6363428caeed0356dfde5 | train | function | def create_atari_environment(name=None, sticky_actions=True,
max_episode_steps=2000):
game_version = 'v0' if sticky_actions else 'v4'
name = '{}NoFrameskip-{}'.format(name, game_version)
env = gym.make(name)
env = env.env
env = preprocessing(env, max_episode_steps=max_ep... | def create_atari_environment(name=None, sticky_actions=True,
max_episode_steps=2000):
| game_version = 'v0' if sticky_actions else 'v4'
name = '{}NoFrameskip-{}'.format(name, game_version)
env = gym.make(name)
env = env.env
env = preprocessing(env, max_episode_steps=max_episode_steps)
return env
| import cv2
import gym
import numpy as np
from gym.spaces.box import Box
def create_atari_environment(name=None, sticky_actions=True,
max_episode_steps=2000):
| 40 | 64 | 81 | 20 | 19 | DZ9/tianshou | tianshou/env/atari.py | Python | create_atari_environment | create_atari_environment | 7 | 14 | 7 | 8 | 7822f9a156ac9f6d6b6e2c1dd27f23261e74f987 | bigcode/the-stack | train |
28b6ae2a4002965f851c1ff8 | train | class | class InstanceMethodReplayer(FunctionReplayer):
pass
| class InstanceMethodReplayer(FunctionReplayer):
| pass
| ):
self.spy = spy
self.index = 0
def replay(self, fn, *args, **kwargs):
return_value = self.spy.get_call(fn, self.index).return_value
self.index += 1
return return_value
class InstanceMethodReplayer(FunctionReplayer):
| 64 | 64 | 12 | 9 | 54 | bywires/chara | chara/replayers/sequence.py | Python | InstanceMethodReplayer | InstanceMethodReplayer | 15 | 16 | 15 | 15 | c3f2ef06e115046fb5a2fd120194e59cd72be10e | bigcode/the-stack | train |
df5635d3f76748717975f149 | train | class | class StaticMethodReplayer(FunctionReplayer):
pass
| class StaticMethodReplayer(FunctionReplayer):
| pass
| ):
return_value = self.spy.get_call(fn, self.index).return_value
self.index += 1
return return_value
class InstanceMethodReplayer(FunctionReplayer):
pass
class ClassMethodReplayer(InstanceMethodReplayer):
pass
class StaticMethodReplayer(FunctionReplayer):
| 64 | 64 | 12 | 9 | 54 | bywires/chara | chara/replayers/sequence.py | Python | StaticMethodReplayer | StaticMethodReplayer | 23 | 24 | 23 | 23 | f551986e2a58652d15f2b7492990402f89535424 | bigcode/the-stack | train |
e5d54b1d0017a9fa8e994372 | train | class | class FunctionReplayer(Replayer):
def __init__(self, spy):
self.spy = spy
self.index = 0
def replay(self, fn, *args, **kwargs):
return_value = self.spy.get_call(fn, self.index).return_value
self.index += 1
return return_value
| class FunctionReplayer(Replayer):
| def __init__(self, spy):
self.spy = spy
self.index = 0
def replay(self, fn, *args, **kwargs):
return_value = self.spy.get_call(fn, self.index).return_value
self.index += 1
return return_value
| from .interface import Replayer
class FunctionReplayer(Replayer):
| 14 | 64 | 70 | 7 | 6 | bywires/chara | chara/replayers/sequence.py | Python | FunctionReplayer | FunctionReplayer | 4 | 12 | 4 | 4 | e4f4e5fa7bb9f4b6ba074e195b1e0b32ea576975 | bigcode/the-stack | train |
c43abecc92a8dc33652a8c7f | train | class | class ClassMethodReplayer(InstanceMethodReplayer):
pass
| class ClassMethodReplayer(InstanceMethodReplayer):
| pass
| def replay(self, fn, *args, **kwargs):
return_value = self.spy.get_call(fn, self.index).return_value
self.index += 1
return return_value
class InstanceMethodReplayer(FunctionReplayer):
pass
class ClassMethodReplayer(InstanceMethodReplayer):
| 64 | 64 | 14 | 11 | 52 | bywires/chara | chara/replayers/sequence.py | Python | ClassMethodReplayer | ClassMethodReplayer | 19 | 20 | 19 | 19 | 23845392d076ca7da1dd5677a79d559c4fd6ce6a | bigcode/the-stack | train |
eea085dd48d08a163055602f | train | function | @bp.route('/logout')
def logout():
session.clear()
return redirect(url_for('index'))
| @bp.route('/logout')
def logout():
| session.clear()
return redirect(url_for('index'))
| ['password'], password):
error = 'Incorrect password.'
if error is None:
session.clear()
session['userid'] = user['userid']
return redirect(url_for('index'))
flash(error)
return render_template('auth/login.html')
@bp.route('/logout')
def... | 64 | 64 | 21 | 9 | 55 | zberwaldt/exercise-tracker-api | exercise_tracker_api/auth.py | Python | logout | logout | 106 | 109 | 106 | 107 | d9d6605907082aca5872b777f1dd95d6d234294a | bigcode/the-stack | train |
00d1d20ac5a4e09e40c78daa | train | function | @bp.before_app_request
def load_logged_in_user():
userid = session.get('userid')
if userid is None:
g.user = None
else:
g.user = get_db().execute(
'SELECT * FROM user WHERE userid = ?', (userid,)
).fetchone()
| @bp.before_app_request
def load_logged_in_user():
| userid = session.get('userid')
if userid is None:
g.user = None
else:
g.user = get_db().execute(
'SELECT * FROM user WHERE userid = ?', (userid,)
).fetchone()
| g.user['userid']
db = get_db()
db.execute(
'DELETE FROM user WHERE userid=?',
(userid,)
)
db.commit()
session.clear()
flash('Account Deleted')
return redirect(url_for('index'))
@bp.before_app_request
def load_logged_in_user():
| 64 | 64 | 62 | 12 | 52 | zberwaldt/exercise-tracker-api | exercise_tracker_api/auth.py | Python | load_logged_in_user | load_logged_in_user | 124 | 133 | 124 | 125 | b2ebba4e3ce53ff07dbf59cdc9198164f99d7ace | bigcode/the-stack | train |
9fe76343fec6f0f7e894dd27 | train | function | @bp.route('/delete')
def delete_account():
userid = g.user['userid']
db = get_db()
db.execute(
'DELETE FROM user WHERE userid=?',
(userid,)
)
db.commit()
session.clear()
flash('Account Deleted')
return redirect(url_for('index'))
| @bp.route('/delete')
def delete_account():
| userid = g.user['userid']
db = get_db()
db.execute(
'DELETE FROM user WHERE userid=?',
(userid,)
)
db.commit()
session.clear()
flash('Account Deleted')
return redirect(url_for('index'))
| ()
session['userid'] = user['userid']
return redirect(url_for('index'))
flash(error)
return render_template('auth/login.html')
@bp.route('/logout')
def logout():
session.clear()
return redirect(url_for('index'))
@bp.route('/delete')
def delete_account():
| 64 | 64 | 65 | 10 | 54 | zberwaldt/exercise-tracker-api | exercise_tracker_api/auth.py | Python | delete_account | delete_account | 111 | 122 | 111 | 112 | 2129ab1d46d440d0abe36759f6de26bd901a88ef | bigcode/the-stack | train |
76026d37b31ad1267b5435dc | train | function | @bp.route('/login', methods=('GET', 'POST'))
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
db = get_db()
error = None
user = db.execute(
'SELECT * FROM user WHERE username = ?', (username... | @bp.route('/login', methods=('GET', 'POST'))
def login():
| if request.method == 'POST':
username = request.form['username']
password = request.form['password']
db = get_db()
error = None
user = db.execute(
'SELECT * FROM user WHERE username = ?', (username,)
).fetchone()
if user is None:
... | "
dbquery += values
db.execute(
dbquery,
dbparams
)
db.commit()
return redirect(url_for('auth.login'))
flash(error)
return render_template('auth/register.html')
@bp.route('/login', methods=('GET', 'PO... | 64 | 64 | 150 | 16 | 48 | zberwaldt/exercise-tracker-api | exercise_tracker_api/auth.py | Python | login | login | 80 | 104 | 80 | 81 | b3c7406346c62b24cce9c722f637fe888b4492dc | bigcode/the-stack | train |
ac8e621dbec48bf19ce4f93e | train | function | @bp.route('/register', methods=('GET', 'POST'))
def register():
userid = str(uuid.uuid4())[:8]
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
bio = request.form['bio']
twitter = request.form['twitter']
facebo... | @bp.route('/register', methods=('GET', 'POST'))
def register():
| userid = str(uuid.uuid4())[:8]
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
bio = request.form['bio']
twitter = request.form['twitter']
facebook = request.form['facebook']
instagram = request.form['... | import functools
import uuid
from flask import (
Blueprint, flash, g, redirect, render_template, request, session, url_for
)
from werkzeug.security import check_password_hash, generate_password_hash
from exercise_tracker_api.db import get_db
bp = Blueprint('auth', __name__, url_prefix='/auth')
@bp.route('/regis... | 82 | 109 | 365 | 16 | 66 | zberwaldt/exercise-tracker-api | exercise_tracker_api/auth.py | Python | register | register | 14 | 78 | 14 | 15 | 671f0be1e9ac86ec7d8ed2e064388acab3088328 | bigcode/the-stack | train |
84526d4f15049763c22adb9a | train | function | def login_required(view):
@functools.wraps(view)
def wrapped_view(**kwargs):
if g.user is None:
flash("You must be logged in to do that.")
return redirect(url_for('auth.login'))
return view(**kwargs)
return wrapped_view | def login_required(view):
@functools.wraps(view)
| def wrapped_view(**kwargs):
if g.user is None:
flash("You must be logged in to do that.")
return redirect(url_for('auth.login'))
return view(**kwargs)
return wrapped_view | userid = session.get('userid')
if userid is None:
g.user = None
else:
g.user = get_db().execute(
'SELECT * FROM user WHERE userid = ?', (userid,)
).fetchone()
def login_required(view):
@functools.wraps(view)
| 64 | 64 | 60 | 14 | 50 | zberwaldt/exercise-tracker-api | exercise_tracker_api/auth.py | Python | login_required | login_required | 136 | 144 | 136 | 137 | 12e4fcd4fe5a16e60e2a86a029b878a15f55dcb0 | bigcode/the-stack | train |
237a231fedb42593d6a99326 | train | class | class PolicyOp(enum.Enum):
Policy_add = 1
Policy_remove = 2 | class PolicyOp(enum.Enum):
| Policy_add = 1
Policy_remove = 2 | import enum
class PolicyOp(enum.Enum):
| 9 | 64 | 19 | 6 | 2 | tl24/pycasbin | casbin/model/policy_op.py | Python | PolicyOp | PolicyOp | 3 | 5 | 3 | 3 | 1d2117e2d89777eeb1129aa204315b2dfbbf791c | bigcode/the-stack | train |
4e8ac9275d4cdef00ddda5de | train | function | def inside(head):
"Return True if head inside screen."
return -300 < head.x < 300 and -300 < head.y < 300
| def inside(head):
| "Return True if head inside screen."
return -300 < head.x < 300 and -300 < head.y < 300
| square, vector
p1xy = vector(-100, 0)
p1aim = vector(4, 0)
p1body = set()
p2xy = vector(100, 0)
p2aim = vector(-4, 0)
p2body = set()
def inside(head):
| 64 | 64 | 33 | 4 | 60 | brandonborn15/free-python-games | freegames/tron.py | Python | inside | inside | 23 | 25 | 23 | 23 | 0bcf17c72357dcc3d9f2ffb60d92b93b5cc77fb4 | bigcode/the-stack | train |
3d549bbb5755a70d3bf336e7 | train | function | def draw():
"Advance players and draw game."
p1xy.move(p1aim)
p1head = p1xy.copy()
p2xy.move(p2aim)
p2head = p2xy.copy()
if not inside(p1head) or p1head in p2body:
print('Player blue wins!')
return
if not inside(p2head) or p2head in p1body:
print('Player red wins!'... | def draw():
| "Advance players and draw game."
p1xy.move(p1aim)
p1head = p1xy.copy()
p2xy.move(p2aim)
p2head = p2xy.copy()
if not inside(p1head) or p1head in p2body:
print('Player blue wins!')
return
if not inside(p2head) or p2head in p1body:
print('Player red wins!')
re... | p2xy = vector(100, 0)
p2aim = vector(-4, 0)
p2body = set()
def inside(head):
"Return True if head inside screen."
return -300 < head.x < 300 and -300 < head.y < 300
def draw():
| 64 | 64 | 168 | 3 | 60 | brandonborn15/free-python-games | freegames/tron.py | Python | draw | draw | 27 | 49 | 27 | 27 | 5b47f39a292da965b822cfc7ea08882dc252cc55 | bigcode/the-stack | train |
adcb0e35f28e0f66385f3b5c | train | class | class TaylorNonLinearDiffuser(Component):
"""Hillslope evolution using a Taylor Series expansion of the Andrews-
Bucknam formulation of nonlinear hillslope flux derived following following
Ganti et al., 2012. The flux is given as:
qs = KS ( 1 + (S/Sc)**2 + (S / Sc)**4 + .. + (S / Sc)**2(n - 1) )
... | class TaylorNonLinearDiffuser(Component):
| """Hillslope evolution using a Taylor Series expansion of the Andrews-
Bucknam formulation of nonlinear hillslope flux derived following following
Ganti et al., 2012. The flux is given as:
qs = KS ( 1 + (S/Sc)**2 + (S / Sc)**4 + .. + (S / Sc)**2(n - 1) )
where K is is the diffusivity, S is the... | # -*- coding: utf-8 -*-
"""TaylorNonLinearDiffuser Component.
@author: R Glade
@author: K Barnhart
@author: G Tucker
"""
# Cubic hillslope flux component
import numpy as np
from landlab import Component, LinkStatus
class TaylorNonLinearDiffuser(Component):
| 64 | 256 | 3,010 | 8 | 55 | clebouteiller/landlab | landlab/components/taylor_nonlinear_hillslope_flux/taylor_nonlinear_hillslope_flux.py | Python | TaylorNonLinearDiffuser | TaylorNonLinearDiffuser | 16 | 345 | 16 | 16 | c0895e4f6393d1f60c06e14a37ed819fa7580493 | bigcode/the-stack | train |
8753ea7c259578ea0aa649c9 | train | class | class Edge:
def __init__(self, src, dest, wt):
self.src = src
self.dest = dest
self.wt = wt
| class Edge:
| def __init__(self, src, dest, wt):
self.src = src
self.dest = dest
self.wt = wt
| 1 sec
Sample Input 1 :
4 4
0 1 3
0 3 5
1 2 1
2 3 8
Sample Output 1 :
1 2 1
0 1 3
0 3 5
'''
class Edge:
| 64 | 64 | 35 | 3 | 61 | jarvis-1805/DSAwithPYTHON | Graphs/Graphs/Kruskal_Algorithm.py | Python | Edge | Edge | 40 | 44 | 40 | 40 | a9b69726822bf658e3366c50ec8e3cfb95c54190 | bigcode/the-stack | train |
e934de521d2f5b89072fb68c | train | function | def kruskal(edges, nVertices):
parent = [i for i in range(nVertices)]
edges = sorted(edges, key = lambda edge:edge.wt)
count = 0
output = []
i = 0
while count < (nVertices-1):
currentEdge = edges[i]
srcParent = getParent(currentEdge.src, parent)
destParent = getParen... | def kruskal(edges, nVertices):
| parent = [i for i in range(nVertices)]
edges = sorted(edges, key = lambda edge:edge.wt)
count = 0
output = []
i = 0
while count < (nVertices-1):
currentEdge = edges[i]
srcParent = getParent(currentEdge.src, parent)
destParent = getParent(currentEdge.dest, parent)
... | li = [int(ele) for ele in input().split()]
n = li[0]
E = li[1]
edges = []
def getParent(v, parent):
if v== parent[v]:
return v
return getParent(parent[v], parent)
def kruskal(edges, nVertices):
| 64 | 64 | 133 | 9 | 55 | jarvis-1805/DSAwithPYTHON | Graphs/Graphs/Kruskal_Algorithm.py | Python | kruskal | kruskal | 56 | 74 | 56 | 56 | 051194f2b3365a9f7f7be97ba4f281f017fe5451 | bigcode/the-stack | train |
f237d1b2e3f60c25229be78b | train | function | def getParent(v, parent):
if v== parent[v]:
return v
return getParent(parent[v], parent)
| def getParent(v, parent):
| if v== parent[v]:
return v
return getParent(parent[v], parent)
| init__(self, src, dest, wt):
self.src = src
self.dest = dest
self.wt = wt
li = [int(ele) for ele in input().split()]
n = li[0]
E = li[1]
edges = []
def getParent(v, parent):
| 64 | 64 | 27 | 7 | 57 | jarvis-1805/DSAwithPYTHON | Graphs/Graphs/Kruskal_Algorithm.py | Python | getParent | getParent | 51 | 54 | 51 | 51 | f142d28c2f1964e79ad65a08828d1ee2f2ed717b | bigcode/the-stack | train |
a07872b406bfa9507ec8e52f | train | function | def grayTrans(img):
img = img.numpy()[0][0]*255.0
img = (img).astype(np.uint8)
return img
| def grayTrans(img):
| img = img.numpy()[0][0]*255.0
img = (img).astype(np.uint8)
return img
| load the images dataset
dataRoot = './data/HED-BSDS/'
# create data loaders from dataset
testPath = dataRoot + 'test.lst'
testDataset = TestDataset(testPath, dataRoot)
testDataloader = DataLoader(testDataset, batch_size=nBatch)
def grayTrans(img):
| 64 | 64 | 34 | 5 | 59 | fabianarchila98/Lab6 | test.py | Python | grayTrans | grayTrans | 34 | 37 | 34 | 34 | eaa1492eeb9824d672e22b27c1a166e216e48d92 | bigcode/the-stack | train |
7eae9a4470f448752c2c30fc | train | class | class MyUserView(View):
model = MyUser
def get(self, request, username):
try:
user = MyUser.objects.get(username=username)
except MyUser.DoesNotExist:
raise Http404
return render(request, 'core/user.html', {'user': user})
| class MyUserView(View):
| model = MyUser
def get(self, request, username):
try:
user = MyUser.objects.get(username=username)
except MyUser.DoesNotExist:
raise Http404
return render(request, 'core/user.html', {'user': user})
| , questionid, slug):
try:
question = Question.objects.get(pk=questionid)
except Question.DoesNotExist:
raise Http404
question.views += 1
question.save()
return render(request, 'core/question.html', {'question': question})
class MyUserView(View):
| 64 | 64 | 62 | 6 | 58 | nyddle/toster | core/views.py | Python | MyUserView | MyUserView | 45 | 53 | 45 | 45 | c8e8a6f2ac3f4911335ea75daa8aedf55ae6be9f | bigcode/the-stack | train |
e7b6cfd8288282a49aec4113 | train | class | class FeedView(View):
def get(self, request):
return render(request, 'core/feed.html', { 'stream' : any_stream(request.user) })
| class FeedView(View):
| def get(self, request):
return render(request, 'core/feed.html', { 'stream' : any_stream(request.user) })
| .serializers import QuestionSerializer, MyUserSerializer
from taggit.models import Tag
from bookmarks.handlers import library
from bookmarks.models import Bookmark
from django.contrib.auth import get_user_model as user_model
from actstream import action
from actstream.models import model_stream, any_stream
class F... | 64 | 64 | 33 | 5 | 58 | nyddle/toster | core/views.py | Python | FeedView | FeedView | 26 | 29 | 26 | 27 | 7b84b9e2c08da0812bced214a2a3cee421ea5119 | bigcode/the-stack | train |
d215ad644d5bca22544729d6 | train | class | class HomeView(View):
def get(self, request):
return render(request, 'base.html')
| class HomeView(View):
| def get(self, request):
return render(request, 'base.html')
| """
queryset = Question.objects.all()
serializer_class = QuestionSerializer
class MyUserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = MyUser.objects.all()
serializer_class = MyUserSerializer
class HomeView(View):
| 64 | 64 | 21 | 5 | 58 | nyddle/toster | core/views.py | Python | HomeView | HomeView | 105 | 107 | 105 | 105 | d33a239bb4a57caed06d274e111e498f60b4cec7 | bigcode/the-stack | train |
8e3b19be07e17ad037124991 | train | class | class MyUserListView(ListView):
model = MyUser
| class MyUserListView(ListView):
| model = MyUser
| in=[tag,])
q = self.request.GET.get("q")
if q:
return queryset.filter(question__icontains=q)
return queryset
class PopularQuestionListView(ListView):
model = Question
queryset = Question.objects.order_by('-rating')
class MyUserListView(ListView):
| 64 | 64 | 14 | 8 | 56 | nyddle/toster | core/views.py | Python | MyUserListView | MyUserListView | 77 | 78 | 77 | 77 | 64994d8ed71f19611b0c132279fda11cf5a0cc82 | bigcode/the-stack | train |
e152352885c4430d1d63b21a | train | class | class PopularQuestionListView(ListView):
model = Question
queryset = Question.objects.order_by('-rating')
| class PopularQuestionListView(ListView):
| model = Question
queryset = Question.objects.order_by('-rating')
| ' in self.kwargs:
tag = self.kwargs['tag']
return queryset.filter(tags__name__in=[tag,])
q = self.request.GET.get("q")
if q:
return queryset.filter(question__icontains=q)
return queryset
class PopularQuestionListView(ListView):
| 64 | 64 | 23 | 8 | 55 | nyddle/toster | core/views.py | Python | PopularQuestionListView | PopularQuestionListView | 72 | 74 | 72 | 72 | 1257f704d8affa281a93b843b49b8ae84e7c8536 | bigcode/the-stack | train |
72828e96e096d58261f6a90e | train | class | class MyUserQuestionListView(ListView):
model = Question
def get_queryset(self):
self.author = get_object_or_404(MyUser, name=self.kwargs['username'])
return Question.objects.filter(author=self.author)
| class MyUserQuestionListView(ListView):
| model = Question
def get_queryset(self):
self.author = get_object_or_404(MyUser, name=self.kwargs['username'])
return Question.objects.filter(author=self.author)
| if q:
return queryset.filter(question__icontains=q)
return queryset
class PopularQuestionListView(ListView):
model = Question
queryset = Question.objects.order_by('-rating')
class MyUserListView(ListView):
model = MyUser
class MyUserQuestionListView(ListView):
| 64 | 64 | 48 | 9 | 54 | nyddle/toster | core/views.py | Python | MyUserQuestionListView | MyUserQuestionListView | 81 | 86 | 81 | 81 | 583d7b6e8837691ac7b6f9293c0baf7e74a7e513 | bigcode/the-stack | train |
07a90cdf87ef644431f5aa82 | train | class | class Members(View):
def get(self, request):
print('user', request.user)
print('session', request.session.keys())
return render(request, 'core/member.html')
| class Members(View):
| def get(self, request):
print('user', request.user)
print('session', request.session.keys())
return render(request, 'core/member.html')
| '
form_class = AskQuestionForm
success_url = '/questions'
def form_valid(self, form):
form.save()
return super(AskQuestionView, self).form_valid(form)
class TagListView(ListView):
model = Tag
#TODO: MembersView?
class Members(View):
| 64 | 64 | 38 | 4 | 60 | nyddle/toster | core/views.py | Python | Members | Members | 125 | 129 | 125 | 125 | af0767ee53362edd1b63612a0bb7da112f301883 | bigcode/the-stack | train |
dea18fe1b750b4579d418444 | train | class | class QuestionViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = Question.objects.all()
serializer_class = QuestionSerializer
| class QuestionViewSet(viewsets.ModelViewSet):
| """
API endpoint that allows users to be viewed or edited.
"""
queryset = Question.objects.all()
serializer_class = QuestionSerializer
| model = MyUser
class MyUserQuestionListView(ListView):
model = Question
def get_queryset(self):
self.author = get_object_or_404(MyUser, name=self.kwargs['username'])
return Question.objects.filter(author=self.author)
class QuestionViewSet(viewsets.ModelViewSet):
| 64 | 64 | 40 | 10 | 54 | nyddle/toster | core/views.py | Python | QuestionViewSet | QuestionViewSet | 89 | 94 | 89 | 89 | 550372d57cdb9c82422ad2c0596a1abcccafc2a1 | bigcode/the-stack | train |
05230b2a1f2ef04632fe55ee | train | class | class QuestionView(View):
model = Question
def get(self, request, questionid, slug):
try:
question = Question.objects.get(pk=questionid)
except Question.DoesNotExist:
raise Http404
question.views += 1
question.save()
return render(request, 'core/... | class QuestionView(View):
| model = Question
def get(self, request, questionid, slug):
try:
question = Question.objects.get(pk=questionid)
except Question.DoesNotExist:
raise Http404
question.views += 1
question.save()
return render(request, 'core/question.html', {'question... | .auth import get_user_model as user_model
from actstream import action
from actstream.models import model_stream, any_stream
class FeedView(View):
def get(self, request):
return render(request, 'core/feed.html', { 'stream' : any_stream(request.user) })
class QuestionView(View):
| 64 | 64 | 74 | 5 | 59 | nyddle/toster | core/views.py | Python | QuestionView | QuestionView | 31 | 42 | 31 | 31 | 545420ad9772288fa554c2c2901e09a3dbc165c2 | bigcode/the-stack | train |
3f10a43421bcfcf37e3b4d42 | train | class | class BookmarksView(View):
def get(self, request):
bookmarks = Bookmark.objects.filter_with_contents(user=self.request.user)
return render(request, 'core/bookmark_list.html', { 'bookmarks' : bookmarks })
| class BookmarksView(View):
| def get(self, request):
bookmarks = Bookmark.objects.filter_with_contents(user=self.request.user)
return render(request, 'core/bookmark_list.html', { 'bookmarks' : bookmarks })
| (form)
class TagListView(ListView):
model = Tag
#TODO: MembersView?
class Members(View):
def get(self, request):
print('user', request.user)
print('session', request.session.keys())
return render(request, 'core/member.html')
class BookmarksView(View):
| 64 | 64 | 46 | 6 | 58 | nyddle/toster | core/views.py | Python | BookmarksView | BookmarksView | 132 | 136 | 132 | 133 | 2ff06e6ee1013792bfb8c98c1fb82f271a0f716b | bigcode/the-stack | train |
3fb4c77b3e1f6e2a65f3f76f | train | class | class MyUserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = MyUser.objects.all()
serializer_class = MyUserSerializer
| class MyUserViewSet(viewsets.ModelViewSet):
| """
API endpoint that allows users to be viewed or edited.
"""
queryset = MyUser.objects.all()
serializer_class = MyUserSerializer
| args['username'])
return Question.objects.filter(author=self.author)
class QuestionViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = Question.objects.all()
serializer_class = QuestionSerializer
class MyUserViewSet(viewsets.ModelViewSe... | 64 | 64 | 43 | 11 | 52 | nyddle/toster | core/views.py | Python | MyUserViewSet | MyUserViewSet | 97 | 102 | 97 | 97 | 0b39304e3965c890017906ab2f5e0222ae3d6840 | bigcode/the-stack | train |
eae0a6d331546b455f8723f5 | train | class | class AskQuestionView(FormView):
template_name = 'core/new_question.html'
form_class = AskQuestionForm
success_url = '/questions'
def form_valid(self, form):
form.save()
return super(AskQuestionView, self).form_valid(form)
| class AskQuestionView(FormView):
| template_name = 'core/new_question.html'
form_class = AskQuestionForm
success_url = '/questions'
def form_valid(self, form):
form.save()
return super(AskQuestionView, self).form_valid(form)
| .ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = MyUser.objects.all()
serializer_class = MyUserSerializer
class HomeView(View):
def get(self, request):
return render(request, 'base.html')
class AskQuestionView(FormView):
| 64 | 64 | 58 | 7 | 57 | nyddle/toster | core/views.py | Python | AskQuestionView | AskQuestionView | 110 | 117 | 110 | 110 | ae9a463caa09c9c4f53d2a14ff5a7b673551d369 | bigcode/the-stack | train |
61f2981e59a43cc2d61de233 | train | class | class QuestionListView(ListView):
model = Question
queryset = Question.objects.order_by('-pub_date')
def get_queryset(self):
queryset = super(QuestionListView, self).get_queryset()
if 'tag' in self.kwargs:
tag = self.kwargs['tag']
return queryset.filter(tags__name__i... | class QuestionListView(ListView):
| model = Question
queryset = Question.objects.order_by('-pub_date')
def get_queryset(self):
queryset = super(QuestionListView, self).get_queryset()
if 'tag' in self.kwargs:
tag = self.kwargs['tag']
return queryset.filter(tags__name__in=[tag,])
q = self.request... | def get(self, request, username):
try:
user = MyUser.objects.get(username=username)
except MyUser.DoesNotExist:
raise Http404
return render(request, 'core/user.html', {'user': user})
#TODO: merge with popular view
class QuestionListView(ListView):
| 64 | 64 | 103 | 7 | 56 | nyddle/toster | core/views.py | Python | QuestionListView | QuestionListView | 57 | 69 | 57 | 57 | 122c5a45a3916e36c5ce9a2366ca9b47bda29427 | bigcode/the-stack | train |
de29ffb31b9c6c4e4f8d47f3 | train | class | class TagListView(ListView):
model = Tag
| class TagListView(ListView):
| model = Tag
| AskQuestionView(FormView):
template_name = 'core/new_question.html'
form_class = AskQuestionForm
success_url = '/questions'
def form_valid(self, form):
form.save()
return super(AskQuestionView, self).form_valid(form)
class TagListView(ListView):
| 64 | 64 | 12 | 7 | 57 | nyddle/toster | core/views.py | Python | TagListView | TagListView | 120 | 121 | 120 | 120 | 814e01188b4ad9c7adc84abe0bdf8217e41f88b0 | bigcode/the-stack | train |
d95ce42a71c10b91ce78deee | train | function | def store_settings():
# Stores the setting info from the GUI into
# the Mini-Monitor settings file. Returns the value 0
# if Success, -1 if an error.
try:
# gather the data from the interface
logger_id = site_entry.get().replace(' ', '')
use_gas = True if enable_gas.get()=='1'... | def store_settings():
# Stores the setting info from the GUI into
# the Mini-Monitor settings file. Returns the value 0
# if Success, -1 if an error.
| try:
# gather the data from the interface
logger_id = site_entry.get().replace(' ', '')
use_gas = True if enable_gas.get()=='1' else False
meter_ids = meter_ids_entry.get()
internet_type = inet_type.get()
w_ssid = wifi_ssid_entry.get()
w_pass = wifi_pass_entr... | and Mac executable
and put on the /boot partition of the Mini-Monitor SD card.
PyInstaller, http://www.pyinstaller.org/documentation.html is used compile
the Python script into an executable file. To create a Windows executable,
PyInstaller must be run on a Windows machine. To create a Mac executable,
it must be run... | 256 | 256 | 870 | 42 | 213 | alanmitchell/mini-monitor | config_util/settings_editor.py | Python | store_settings | store_settings | 34 | 124 | 34 | 38 | dd8d73f8de51f2835d442269219d02241b880f3d | bigcode/the-stack | train |
cacd5bd3c715b1809d52e42a | train | function | def inet_visibility():
"""Manage visibility of Internet Type widgets.
"""
wifi_frame.grid_remove()
cell_frame.grid_remove()
i_type = inet_type.get()
if i_type=='ethernet':
pass
elif i_type=='wifi':
wifi_frame.grid()
elif i_type=='cellular':
cell_frame.grid()
| def inet_visibility():
| """Manage visibility of Internet Type widgets.
"""
wifi_frame.grid_remove()
cell_frame.grid_remove()
i_type = inet_type.get()
if i_type=='ethernet':
pass
elif i_type=='wifi':
wifi_frame.grid()
elif i_type=='cellular':
cell_frame.grid()
| settings and Store again.'
tkinter.messagebox.showinfo('Success', msg)
return 0
except Exception as e:
tkinter.messagebox.showerror('Error Occurred', 'An Error occurred while attempting to store settings:\n%s' % str(e))
return -1
def inet_visibility():
| 64 | 64 | 71 | 4 | 59 | alanmitchell/mini-monitor | config_util/settings_editor.py | Python | inet_visibility | inet_visibility | 126 | 137 | 126 | 126 | 856111a2f2d515c539673368c0568b01086d9e5b | bigcode/the-stack | train |
41120137120ce64f3ab625e4 | train | function | def select_other_setting():
global other_settings_fn
other_settings_fn = tkinter.filedialog.askopenfilename()
other_settings_var.set(SETTINGS_FILE_TMPL % other_settings_fn)
| def select_other_setting():
| global other_settings_fn
other_settings_fn = tkinter.filedialog.askopenfilename()
other_settings_var.set(SETTINGS_FILE_TMPL % other_settings_fn)
| _frame.grid()
def gas_id_visibility():
"""Manage visibility of Gas Meter ID widgets.
"""
if enable_gas.get()=='1':
meter_ids_label.grid()
meter_ids_entry.grid()
else:
meter_ids_label.grid_remove()
meter_ids_entry.grid_remove()
def select_other_setting():
| 64 | 64 | 40 | 5 | 59 | alanmitchell/mini-monitor | config_util/settings_editor.py | Python | select_other_setting | select_other_setting | 150 | 153 | 150 | 150 | 8518c3c78282024b935b55e4b33309d9b7027ae9 | bigcode/the-stack | train |
5da14d5d99c79d7ba9e066f0 | train | function | def gas_id_visibility():
"""Manage visibility of Gas Meter ID widgets.
"""
if enable_gas.get()=='1':
meter_ids_label.grid()
meter_ids_entry.grid()
else:
meter_ids_label.grid_remove()
meter_ids_entry.grid_remove()
| def gas_id_visibility():
| """Manage visibility of Gas Meter ID widgets.
"""
if enable_gas.get()=='1':
meter_ids_label.grid()
meter_ids_entry.grid()
else:
meter_ids_label.grid_remove()
meter_ids_entry.grid_remove()
| .
"""
wifi_frame.grid_remove()
cell_frame.grid_remove()
i_type = inet_type.get()
if i_type=='ethernet':
pass
elif i_type=='wifi':
wifi_frame.grid()
elif i_type=='cellular':
cell_frame.grid()
def gas_id_visibility():
| 64 | 64 | 56 | 5 | 59 | alanmitchell/mini-monitor | config_util/settings_editor.py | Python | gas_id_visibility | gas_id_visibility | 139 | 147 | 139 | 139 | 62302150050b9739cda7deed19c78f1c6175fdc4 | bigcode/the-stack | train |
d931cbc70e68af6b97a131ba | train | class | class ProfileTestClass(TestCase):
'''
This is a class that perform unnittest behaviour on the Profile Model.
'''
def setUp(self):
self.profile_one = Profile(profile_photo='images/mine.jpg',bio='Currently doing datascience in moringa',user_id=3)
def test_instance(... | class ProfileTestClass(TestCase):
| '''
This is a class that perform unnittest behaviour on the Profile Model.
'''
def setUp(self):
self.profile_one = Profile(profile_photo='images/mine.jpg',bio='Currently doing datascience in moringa',user_id=3)
def test_instance(self):
self.assertTrue(isinstan... | (self):
self.image_one.save()
new_caption = 'That image is cool'
done = self.image_one.update_caption(self.image_one.id,new_caption)
self.assertEqual(done,new_caption)
def tearDown(self):
Image.objects.all().delete()
class ProfileTestClass(TestCase):
| 63 | 67 | 225 | 8 | 55 | Biphyl/instagram | social/tests.py | Python | ProfileTestClass | ProfileTestClass | 41 | 73 | 41 | 42 | badf32a8fd6081e6d0d995e261a8527a2cd89095 | bigcode/the-stack | train |
99dc6578b3f6b159fb5275a6 | train | class | class ImageTestClass(TestCase):
'''
This is a class that perform unnittest behaviour on the Image Model.
'''
def setUp(self):
self.image_one = Image(image='images/lagoon.jpeg',image_name='Lovine', image_caption='This is something natural',likes=40, id=1,user_id=3)
def... | class ImageTestClass(TestCase):
| '''
This is a class that perform unnittest behaviour on the Image Model.
'''
def setUp(self):
self.image_one = Image(image='images/lagoon.jpeg',image_name='Lovine', image_caption='This is something natural',likes=40, id=1,user_id=3)
def test_instance(self):
Im... | from django.test import TestCase
from . models import Image,Profile,Comments
class ImageTestClass(TestCase):
| 24 | 70 | 236 | 7 | 16 | Biphyl/instagram | social/tests.py | Python | ImageTestClass | ImageTestClass | 4 | 36 | 4 | 4 | 2f0a670729493de02539d8a2bf779c0fa69c8d02 | bigcode/the-stack | train |
6246dc4f70963126e840571a | train | function | def clear(s):
return re.sub("[() -]","",s)
| def clear(s):
| return re.sub("[() -]","",s)
| _by_id(contact.id).firstname
assert contact.lastname == db.get_contact_by_id(contact.id).lastname
assert clear(contact.address) == clear(db.get_contact_by_id(contact.id).address)
assert contact.all_emails == merge_contact_info_emails(db.get_contact_by_id(contact.id))
def clear(s):
| 64 | 64 | 16 | 4 | 60 | arushanovanz/python_training | test/contacts/test_all_information_contact.py | Python | clear | clear | 22 | 23 | 22 | 22 | 694458a144789008e42d49e87b243f926847414b | bigcode/the-stack | train |
f917bf1f95689eb90d0d015d | train | function | def merge_contact_info_emails(contact):
return "\n".join(filter(lambda x: x != "",
map(lambda x: clear(x),
filter(lambda x: x is not None,
[contact.email,contact.email2,contact.email3]))))
| def merge_contact_info_emails(contact):
| return "\n".join(filter(lambda x: x != "",
map(lambda x: clear(x),
filter(lambda x: x is not None,
[contact.email,contact.email2,contact.email3]))))
| lastname
assert clear(contact.address) == clear(db.get_contact_by_id(contact.id).address)
assert contact.all_emails == merge_contact_info_emails(db.get_contact_by_id(contact.id))
def clear(s):
return re.sub("[() -]","",s)
def merge_contact_info_emails(contact):
| 64 | 64 | 53 | 8 | 56 | arushanovanz/python_training | test/contacts/test_all_information_contact.py | Python | merge_contact_info_emails | merge_contact_info_emails | 25 | 29 | 25 | 25 | 8698c7cc1574eae91e2f904245f42828b256885e | bigcode/the-stack | train |
523f6390568cd87535588287 | train | function | def test_compare_information_home_page_db(app,db):
contacts_from_home_page = app.contact.get_contact_list()
for contact in contacts_from_home_page:
assert contact.firstname == db.get_contact_by_id(contact.id).firstname
assert contact.lastname == db.get_contact_by_id(contact.id).lastname
... | def test_compare_information_home_page_db(app,db):
| contacts_from_home_page = app.contact.get_contact_list()
for contact in contacts_from_home_page:
assert contact.firstname == db.get_contact_by_id(contact.id).firstname
assert contact.lastname == db.get_contact_by_id(contact.id).lastname
assert clear(contact.address) == clear(... | _edit_page.firstname
assert contact_from_home_page.lastname == contact_from_edit_page.lastname
assert contact_from_home_page.address == clear(contact_from_edit_page.address)
assert contact_from_home_page.all_emails == merge_contact_info_emails(contact_from_edit_page)
def test_compare_information_home_page_d... | 64 | 64 | 100 | 11 | 53 | arushanovanz/python_training | test/contacts/test_all_information_contact.py | Python | test_compare_information_home_page_db | test_compare_information_home_page_db | 13 | 19 | 13 | 13 | 1ae579f9b12ddaecec30392029fa5bc5df2b2011 | bigcode/the-stack | train |
9fb091fb8d95e93a2a684e65 | train | function | def test_all_information_on_home_page(app):
contact_from_home_page =app.contact.get_contact_list()[0]
contact_from_edit_page = app.contact.get_contact_info_from_edit_page(0)
assert contact_from_home_page.firstname == contact_from_edit_page.firstname
assert contact_from_home_page.lastname == contact_from... | def test_all_information_on_home_page(app):
| contact_from_home_page =app.contact.get_contact_list()[0]
contact_from_edit_page = app.contact.get_contact_info_from_edit_page(0)
assert contact_from_home_page.firstname == contact_from_edit_page.firstname
assert contact_from_home_page.lastname == contact_from_edit_page.lastname
assert contact_from_... | import re
def test_all_information_on_home_page(app):
| 12 | 64 | 103 | 9 | 2 | arushanovanz/python_training | test/contacts/test_all_information_contact.py | Python | test_all_information_on_home_page | test_all_information_on_home_page | 4 | 10 | 4 | 4 | bd26bbfa945e9d09f0fe863abc5f61e122dfa12e | bigcode/the-stack | train |
96f120719f7205ed27505e86 | train | class | class VersioningGetTagRequestResponse(BaseType):
def __init__(self, commit=None):
required = {
"commit": False,
}
self.commit = commit
for k, v in required.items():
if self[k] is None and v:
raise ValueError('attribute {} is required'.format(k))
@staticmethod
def from_json(d)... | class VersioningGetTagRequestResponse(BaseType):
| def __init__(self, commit=None):
required = {
"commit": False,
}
self.commit = commit
for k, v in required.items():
if self[k] is None and v:
raise ValueError('attribute {} is required'.format(k))
@staticmethod
def from_json(d):
from .VersioningCommit import VersioningCom... | # THIS FILE IS AUTO-GENERATED. DO NOT EDIT
from verta._swagger.base_type import BaseType
class VersioningGetTagRequestResponse(BaseType):
| 33 | 64 | 132 | 10 | 22 | stefan-petrov-toptal/modeldb | client/verta/verta/_swagger/_public/modeldb/versioning/model/VersioningGetTagRequestResponse.py | Python | VersioningGetTagRequestResponse | VersioningGetTagRequestResponse | 4 | 24 | 4 | 4 | 674eed34fc8aa3dc0158dfb448becef1f90ecebc | bigcode/the-stack | train |
d4ef9b9597435026d10bf831 | train | class | class CSVReader(FeaturizationTransformerPrimitiveBase[Inputs, Outputs, Hyperparams]):
"""
BBN D3M CSV Reader Primitive
Arguments:
"""
__git_commit__=utils.current_git_commit(os.path.dirname(__file__))
metadata = metadata_module.PrimitiveMetadata({
'id': 'a771e153-67d7-4f69-b5f9-1a764e... | class CSVReader(FeaturizationTransformerPrimitiveBase[Inputs, Outputs, Hyperparams]):
| """
BBN D3M CSV Reader Primitive
Arguments:
"""
__git_commit__=utils.current_git_commit(os.path.dirname(__file__))
metadata = metadata_module.PrimitiveMetadata({
'id': 'a771e153-67d7-4f69-b5f9-1a764e502a23',
'version': __version__,
'name': "CSV Reader",
'descrip... | m.metadata import hyperparams, params, utils
#from d3m import container
#from d3m.metadata import base as metadata_modul
from d3m.primitive_interfaces import base
from d3m.primitive_interfaces.featurization import FeaturizationTransformerPrimitiveBase
from . import __author__, __version__
Inputs = Dataset
Outputs = L... | 256 | 256 | 2,243 | 19 | 237 | BBN-E/d3m-bbn-primitives | bbn_primitives/time_series/csv_reader.py | Python | CSVReader | CSVReader | 48 | 270 | 48 | 49 | c4a7c51cf24afb51f2a9fa6261bf7098ab6f9b8c | bigcode/the-stack | train |
56357d7cdfb3779833de7486 | train | class | class Hyperparams(hyperparams.Hyperparams):
resampling_rate = hyperparams.Bounded[float](
semantic_types = [
'https://metadata.datadrivendiscovery.org/types/ControlParameter',
],
default = 1.0,
lower = 0.0, upper = None,
description = 'Resampling rate'
)
read_as_mono = hyp... | class Hyperparams(hyperparams.Hyperparams):
| resampling_rate = hyperparams.Bounded[float](
semantic_types = [
'https://metadata.datadrivendiscovery.org/types/ControlParameter',
],
default = 1.0,
lower = 0.0, upper = None,
description = 'Resampling rate'
)
read_as_mono = hyperparams.Hyperparameter[bool](
seman... | .featurization import FeaturizationTransformerPrimitiveBase
from . import __author__, __version__
Inputs = Dataset
Outputs = List #[d3m_ndarray]
_logger = logging.getLogger('d3m.primitives.data_preprocessing.csv_reader.CSVReader')
class Hyperparams(hyperparams.Hyperparams):
| 64 | 64 | 137 | 10 | 54 | BBN-E/d3m-bbn-primitives | bbn_primitives/time_series/csv_reader.py | Python | Hyperparams | Hyperparams | 30 | 46 | 30 | 30 | 515247da3bbfedf0b3d939e159034ffc9db57d5c | bigcode/the-stack | train |
759ff42fa46935e2ac452b8f | train | function | def get_config(config_file=None, section=None):
"""Gets the user defined config and validates it.
Args:
config_file:
Path to config file to use. If None, uses defaults.
section (str):
Name of section in the config to extract (i.e., 'fetchers',
'processing', '... | def get_config(config_file=None, section=None):
| """Gets the user defined config and validates it.
Args:
config_file:
Path to config file to use. If None, uses defaults.
section (str):
Name of section in the config to extract (i.e., 'fetchers',
'processing', 'pickers', etc.) If None, whole config is returne... | or \
not isinstance(target[key], dict):
target[key] = value
else:
update_dict(target[key], value)
return
def merge_dicts(dicts):
"""Merges a list of dictionaries into a new dictionary.
The order of the dictionaries in the list provides precedence of the
... | 151 | 151 | 504 | 10 | 140 | dchurchwell-usgs/groundmotion-processing | gmprocess/utils/config.py | Python | get_config | get_config | 212 | 273 | 212 | 212 | b45e47e60ddc05836584c7f26eb0b54075c778ef | bigcode/the-stack | train |
d4b20df8d5818ee0c3f5a0ab | train | function | def __proj_to_conf_file(path):
# We are switching from absolute to relative paths in this conf file. For
# backward compatibility, we're going to try to support both absolute and
# relative paths, which is why we need this "try" block to first assume
# an absolute path and if the conf does not exist the... | def __proj_to_conf_file(path):
# We are switching from absolute to relative paths in this conf file. For
# backward compatibility, we're going to try to support both absolute and
# relative paths, which is why we need this "try" block to first assume
# an absolute path and if the conf does not exist the... | proj_conf_file = os.path.join(path, 'projects.conf')
projects_conf = ConfigObj(proj_conf_file, encoding='utf-8')
project = projects_conf['project']
current_project = projects_conf['projects'][project]
conf_path = current_project['conf_path']
conf_file = os.path.join(conf_path, 'config.yml')
... | def __proj_to_conf_file(path):
# We are switching from absolute to relative paths in this conf file. For
# backward compatibility, we're going to try to support both absolute and
# relative paths, which is why we need this "try" block to first assume
# an absolute path and if the conf does not exist the... | 77 | 64 | 181 | 77 | 0 | dchurchwell-usgs/groundmotion-processing | gmprocess/utils/config.py | Python | __proj_to_conf_file | __proj_to_conf_file | 303 | 316 | 303 | 307 | d191af22a3e3002fb29aa74bc9a8e6f52947d244 | bigcode/the-stack | train |
8d1d376580266df2ac19d755 | train | function | def update_config(custom_cfg_file):
"""Merge custom config with default.
Args:
custom_cfg_file (str):
Path to custom config.
Returns:
dict: Merged config dictionary.
"""
config = get_config()
if not os.path.isfile(custom_cfg_file):
return config
try:
... | def update_config(custom_cfg_file):
| """Merge custom config with default.
Args:
custom_cfg_file (str):
Path to custom config.
Returns:
dict: Merged config dictionary.
"""
config = get_config()
if not os.path.isfile(custom_cfg_file):
return config
try:
with open(custom_cfg_file, 'r... | config = yaml.load(f)
CONF_SCHEMA.validate(config)
if section is not None:
if section not in config:
raise IndexError('Section %s not found in config file.' % section)
else:
config = config[section]
return config
def update_config(custom_cfg_file):
| 64 | 64 | 129 | 7 | 56 | dchurchwell-usgs/groundmotion-processing | gmprocess/utils/config.py | Python | update_config | update_config | 276 | 300 | 276 | 276 | 6720d547c04f4f71b5948b16f850b1266f50457e | bigcode/the-stack | train |
747aac37965239e6bc8668a7 | train | function | def update_dict(target, source):
"""Merge values from source dictionary into target dictionary.
Args:
target (dict):
Dictionary to be updated with values from source dictionary.
source (dict):
Dictionary with values to be transferred to target dictionary.
"""
fo... | def update_dict(target, source):
| """Merge values from source dictionary into target dictionary.
Args:
target (dict):
Dictionary to be updated with values from source dictionary.
source (dict):
Dictionary with values to be transferred to target dictionary.
"""
for key, value in source.items():
... | lta': float,
'hanningWindow': float,
'threshDetect': float,
'threshDetect2': float,
'threshRestart': float
},
'travel_time': {
'model': str
}
}
})
def update_dict(target, source):
| 64 | 64 | 112 | 7 | 57 | dchurchwell-usgs/groundmotion-processing | gmprocess/utils/config.py | Python | update_dict | update_dict | 172 | 189 | 172 | 172 | 4b0c2398c48a6c2e1548967249052662252824eb | bigcode/the-stack | train |
3af9f5ec22eba05e2957e835 | train | function | def merge_dicts(dicts):
"""Merges a list of dictionaries into a new dictionary.
The order of the dictionaries in the list provides precedence of the
values, with values from subsequent dictionaries overriding earlier
ones.
Args:
dicts (list of dictionaries):
List of dictionarie... | def merge_dicts(dicts):
| """Merges a list of dictionaries into a new dictionary.
The order of the dictionaries in the list provides precedence of the
values, with values from subsequent dictionaries overriding earlier
ones.
Args:
dicts (list of dictionaries):
List of dictionaries to be merged.
Ret... | for key, value in source.items():
if not isinstance(value, dict) or \
key not in target.keys() or \
not isinstance(target[key], dict):
target[key] = value
else:
update_dict(target[key], value)
return
def merge_dicts(dicts):
| 64 | 64 | 110 | 7 | 56 | dchurchwell-usgs/groundmotion-processing | gmprocess/utils/config.py | Python | merge_dicts | merge_dicts | 192 | 209 | 192 | 192 | 72b340fe997682c96210d80c373e0e19fd9bc0bc | bigcode/the-stack | train |
1cc452ca695c22db94b6ab05 | train | function | @app.route('/')
def status():
return json.dumps({'code': 1, 'msg': 'API is running'})
| @app.route('/')
def status():
| return json.dumps({'code': 1, 'msg': 'API is running'})
| -8
# author: wyi
from gevent import monkey
monkey.patch_socket()
from flask_script import Manager
from cmd import Test
from app import create_app
import json
app = create_app()
manager = Manager(app)
manager.add_command('test', Test())
@app.route('/')
def status():
| 64 | 64 | 24 | 6 | 58 | snowman620/uPool | wsgi.py | Python | status | status | 19 | 21 | 19 | 20 | 9a4535b7ed3a027d8898f6fb0e6a34b2c6f31c03 | bigcode/the-stack | train |
ce61804379f6add621242a1f | train | function | def main():
argc = len(sys.argv)
n = 100_000
if argc > 1:
n = int(sys.argv[1])
start = time.time()
num = fibonacci(n)
elapsed = time.time() - start
print("Number:", num)
print("Elapsed:", elapsed)
| def main():
| argc = len(sys.argv)
n = 100_000
if argc > 1:
n = int(sys.argv[1])
start = time.time()
num = fibonacci(n)
elapsed = time.time() - start
print("Number:", num)
print("Elapsed:", elapsed)
| import sys
import time
def fibonacci(n):
a = 0
b = 1
for i in range(n):
c = a + b
a = b
b = c
return a
def main():
| 53 | 64 | 69 | 3 | 49 | nikolabebic95/PythonLoopOptimizer | inputs/fibonacci.py | Python | main | main | 15 | 28 | 15 | 15 | 42b0583000f7dc27494ba7a0a3f4e1ce8beac942 | bigcode/the-stack | train |
b36733bd3fedfe65ca82340b | train | function | def fibonacci(n):
a = 0
b = 1
for i in range(n):
c = a + b
a = b
b = c
return a
| def fibonacci(n):
| a = 0
b = 1
for i in range(n):
c = a + b
a = b
b = c
return a
| import sys
import time
def fibonacci(n):
| 10 | 64 | 44 | 4 | 5 | nikolabebic95/PythonLoopOptimizer | inputs/fibonacci.py | Python | fibonacci | fibonacci | 5 | 12 | 5 | 5 | 3e88eaa7f04f1dfbd3b0d04b6c339b50744d5017 | bigcode/the-stack | train |
6a9794ec6d449fabf4abcfa6 | train | class | @pulumi.input_type
class ProjectSinkBigqueryOptionsArgs:
def __init__(__self__, *,
use_partitioned_tables: pulumi.Input[bool]):
"""
:param pulumi.Input[bool] use_partitioned_tables: Whether to use [BigQuery's partition tables](https://cloud.google.com/bigquery/docs/partitioned-table... | @pulumi.input_type
class ProjectSinkBigqueryOptionsArgs:
| def __init__(__self__, *,
use_partitioned_tables: pulumi.Input[bool]):
"""
:param pulumi.Input[bool] use_partitioned_tables: Whether to use [BigQuery's partition tables](https://cloud.google.com/bigquery/docs/partitioned-tables).
By default, Logging creates dated tabl... | present and [special query syntax](https://cloud.google.com/bigquery/docs/querying-partitioned-tables)
has to be used instead. In both cases, tables are sharded based on UTC timezone.
"""
return pulumi.get(self, "use_partitioned_tables")
@use_partitioned_tables.setter
def use_partition... | 111 | 111 | 373 | 14 | 97 | dimpu47/pulumi-gcp | sdk/python/pulumi_gcp/logging/_inputs.py | Python | ProjectSinkBigqueryOptionsArgs | ProjectSinkBigqueryOptionsArgs | 476 | 501 | 476 | 477 | 405c3eec51d06062c64f2429318fa42cb9e95daf | bigcode/the-stack | train |
414a66198c89156c6fc79de5 | train | class | @pulumi.input_type
class MetricBucketOptionsLinearBucketsArgs:
def __init__(__self__, *,
num_finite_buckets: Optional[pulumi.Input[float]] = None,
offset: Optional[pulumi.Input[float]] = None,
width: Optional[pulumi.Input[float]] = None):
"""
:param... | @pulumi.input_type
class MetricBucketOptionsLinearBucketsArgs:
| def __init__(__self__, *,
num_finite_buckets: Optional[pulumi.Input[float]] = None,
offset: Optional[pulumi.Input[float]] = None,
width: Optional[pulumi.Input[float]] = None):
"""
:param pulumi.Input[float] num_finite_buckets: Must be greater than 0... | ")
@num_finite_buckets.setter
def num_finite_buckets(self, value: Optional[pulumi.Input[float]]):
pulumi.set(self, "num_finite_buckets", value)
@property
@pulumi.getter
def scale(self) -> Optional[pulumi.Input[float]]:
"""
Must be greater than 0.
"""
return ... | 138 | 138 | 462 | 14 | 124 | dimpu47/pulumi-gcp | sdk/python/pulumi_gcp/logging/_inputs.py | Python | MetricBucketOptionsLinearBucketsArgs | MetricBucketOptionsLinearBucketsArgs | 222 | 274 | 222 | 223 | db2aa8e28d20f1510a74da778f8a3f80e01c4879 | bigcode/the-stack | train |
ce72e30147db85ddbeca59b0 | train | class | @pulumi.input_type
class MetricBucketOptionsArgs:
def __init__(__self__, *,
explicit_buckets: Optional[pulumi.Input['MetricBucketOptionsExplicitBucketsArgs']] = None,
exponential_buckets: Optional[pulumi.Input['MetricBucketOptionsExponentialBucketsArgs']] = None,
l... | @pulumi.input_type
class MetricBucketOptionsArgs:
| def __init__(__self__, *,
explicit_buckets: Optional[pulumi.Input['MetricBucketOptionsExplicitBucketsArgs']] = None,
exponential_buckets: Optional[pulumi.Input['MetricBucketOptionsExponentialBucketsArgs']] = None,
linear_buckets: Optional[pulumi.Input['MetricBucket... | ed_tables", use_partitioned_tables)
@property
@pulumi.getter(name="usePartitionedTables")
def use_partitioned_tables(self) -> pulumi.Input[bool]:
"""
Whether to use [BigQuery's partition tables](https://cloud.google.com/bigquery/docs/partitioned-tables).
By default, Logging creates ... | 215 | 215 | 717 | 12 | 203 | dimpu47/pulumi-gcp | sdk/python/pulumi_gcp/logging/_inputs.py | Python | MetricBucketOptionsArgs | MetricBucketOptionsArgs | 80 | 142 | 80 | 81 | 114377f49a27d3e632a2207c94c96c2d330d168d | bigcode/the-stack | train |
61140578df31217bfb76d72c | train | class | @pulumi.input_type
class BillingAccountSinkBigqueryOptionsArgs:
def __init__(__self__, *,
use_partitioned_tables: pulumi.Input[bool]):
"""
:param pulumi.Input[bool] use_partitioned_tables: Whether to use [BigQuery's partition tables](https://cloud.google.com/bigquery/docs/partitione... | @pulumi.input_type
class BillingAccountSinkBigqueryOptionsArgs:
| def __init__(__self__, *,
use_partitioned_tables: pulumi.Input[bool]):
"""
:param pulumi.Input[bool] use_partitioned_tables: Whether to use [BigQuery's partition tables](https://cloud.google.com/bigquery/docs/partitioned-tables).
By default, Logging creates dated tabl... | , _tables
__all__ = [
'BillingAccountSinkBigqueryOptionsArgs',
'FolderSinkBigqueryOptionsArgs',
'MetricBucketOptionsArgs',
'MetricBucketOptionsExplicitBucketsArgs',
'MetricBucketOptionsExponentialBucketsArgs',
'MetricBucketOptionsLinearBucketsArgs',
'MetricMetricDescriptorArgs',
'Metric... | 112 | 112 | 374 | 15 | 97 | dimpu47/pulumi-gcp | sdk/python/pulumi_gcp/logging/_inputs.py | Python | BillingAccountSinkBigqueryOptionsArgs | BillingAccountSinkBigqueryOptionsArgs | 24 | 49 | 24 | 25 | 51395b23d0f8710eced448188cbcaab404e0ecdb | bigcode/the-stack | train |
abb028b7b6db3df9477a1d96 | train | class | @pulumi.input_type
class OrganizationSinkBigqueryOptionsArgs:
def __init__(__self__, *,
use_partitioned_tables: pulumi.Input[bool]):
"""
:param pulumi.Input[bool] use_partitioned_tables: Whether to use [BigQuery's partition tables](https://cloud.google.com/bigquery/docs/partitioned-... | @pulumi.input_type
class OrganizationSinkBigqueryOptionsArgs:
| def __init__(__self__, *,
use_partitioned_tables: pulumi.Input[bool]):
"""
:param pulumi.Input[bool] use_partitioned_tables: Whether to use [BigQuery's partition tables](https://cloud.google.com/bigquery/docs/partitioned-tables).
By default, Logging creates dated tabl... | def value_type(self) -> Optional[pulumi.Input[str]]:
"""
The type of data that can be assigned to the label.
Default value is `STRING`.
Possible values are `BOOL`, `INT64`, and `STRING`.
"""
return pulumi.get(self, "value_type")
@value_type.setter
def value_type... | 111 | 111 | 373 | 14 | 97 | dimpu47/pulumi-gcp | sdk/python/pulumi_gcp/logging/_inputs.py | Python | OrganizationSinkBigqueryOptionsArgs | OrganizationSinkBigqueryOptionsArgs | 448 | 473 | 448 | 449 | 44e70011f81ce9bed8f9e538bf5c108230af30f2 | bigcode/the-stack | train |
09e4f5e335b9afe60ba838b1 | train | class | @pulumi.input_type
class MetricBucketOptionsExponentialBucketsArgs:
def __init__(__self__, *,
growth_factor: Optional[pulumi.Input[float]] = None,
num_finite_buckets: Optional[pulumi.Input[float]] = None,
scale: Optional[pulumi.Input[float]] = None):
"""
... | @pulumi.input_type
class MetricBucketOptionsExponentialBucketsArgs:
| def __init__(__self__, *,
growth_factor: Optional[pulumi.Input[float]] = None,
num_finite_buckets: Optional[pulumi.Input[float]] = None,
scale: Optional[pulumi.Input[float]] = None):
"""
:param pulumi.Input[float] growth_factor: Must be greater than... | ]):
"""
:param pulumi.Input[List[pulumi.Input[float]]] bounds: The values must be monotonically increasing.
"""
pulumi.set(__self__, "bounds", bounds)
@property
@pulumi.getter
def bounds(self) -> pulumi.Input[List[pulumi.Input[float]]]:
"""
The values must be... | 143 | 143 | 477 | 15 | 128 | dimpu47/pulumi-gcp | sdk/python/pulumi_gcp/logging/_inputs.py | Python | MetricBucketOptionsExponentialBucketsArgs | MetricBucketOptionsExponentialBucketsArgs | 167 | 219 | 167 | 168 | c2e53896d5d746d0e88b7200ccd856ec8c7768ca | bigcode/the-stack | train |
d0b867aac740f81f66561c14 | train | class | @pulumi.input_type
class MetricMetricDescriptorArgs:
def __init__(__self__, *,
metric_kind: pulumi.Input[str],
value_type: pulumi.Input[str],
display_name: Optional[pulumi.Input[str]] = None,
labels: Optional[pulumi.Input[List[pulumi.Input['MetricM... | @pulumi.input_type
class MetricMetricDescriptorArgs:
| def __init__(__self__, *,
metric_kind: pulumi.Input[str],
value_type: pulumi.Input[str],
display_name: Optional[pulumi.Input[str]] = None,
labels: Optional[pulumi.Input[List[pulumi.Input['MetricMetricDescriptorLabelArgs']]]] = None,
... | num_finite_buckets(self) -> Optional[pulumi.Input[float]]:
"""
Must be greater than 0.
"""
return pulumi.get(self, "num_finite_buckets")
@num_finite_buckets.setter
def num_finite_buckets(self, value: Optional[pulumi.Input[float]]):
pulumi.set(self, "num_finite_buckets",... | 256 | 256 | 1,218 | 12 | 244 | dimpu47/pulumi-gcp | sdk/python/pulumi_gcp/logging/_inputs.py | Python | MetricMetricDescriptorArgs | MetricMetricDescriptorArgs | 277 | 385 | 277 | 278 | 5ac5e273fa86134ef9dc70898684ad7b5b47b80a | bigcode/the-stack | train |
a2e85df72c62682b28ab42fd | train | class | @pulumi.input_type
class MetricMetricDescriptorLabelArgs:
def __init__(__self__, *,
key: pulumi.Input[str],
description: Optional[pulumi.Input[str]] = None,
value_type: Optional[pulumi.Input[str]] = None):
"""
:param pulumi.Input[str] key: The label... | @pulumi.input_type
class MetricMetricDescriptorLabelArgs:
| def __init__(__self__, *,
key: pulumi.Input[str],
description: Optional[pulumi.Input[str]] = None,
value_type: Optional[pulumi.Input[str]] = None):
"""
:param pulumi.Input[str] key: The label key.
:param pulumi.Input[str] description: A desc... |
@pulumi.getter
def unit(self) -> Optional[pulumi.Input[str]]:
"""
The unit in which the metric value is reported. It is only applicable if the valueType is
`INT64`, `DOUBLE`, or `DISTRIBUTION`. The supported units are a subset of
[The Unified Code for Units of Measure](http://un... | 146 | 146 | 487 | 13 | 133 | dimpu47/pulumi-gcp | sdk/python/pulumi_gcp/logging/_inputs.py | Python | MetricMetricDescriptorLabelArgs | MetricMetricDescriptorLabelArgs | 388 | 445 | 388 | 389 | 8ff5c59165e55f8f0c4429ddcdd7d6a1831205e8 | bigcode/the-stack | train |
200a3c4ad55bc8ab6851bb06 | train | class | @pulumi.input_type
class FolderSinkBigqueryOptionsArgs:
def __init__(__self__, *,
use_partitioned_tables: pulumi.Input[bool]):
"""
:param pulumi.Input[bool] use_partitioned_tables: Whether to use [BigQuery's partition tables](https://cloud.google.com/bigquery/docs/partitioned-tables... | @pulumi.input_type
class FolderSinkBigqueryOptionsArgs:
| def __init__(__self__, *,
use_partitioned_tables: pulumi.Input[bool]):
"""
:param pulumi.Input[bool] use_partitioned_tables: Whether to use [BigQuery's partition tables](https://cloud.google.com/bigquery/docs/partitioned-tables).
By default, Logging creates dated tabl... | present and [special query syntax](https://cloud.google.com/bigquery/docs/querying-partitioned-tables)
has to be used instead. In both cases, tables are sharded based on UTC timezone.
"""
return pulumi.get(self, "use_partitioned_tables")
@use_partitioned_tables.setter
def use_partition... | 111 | 111 | 373 | 14 | 97 | dimpu47/pulumi-gcp | sdk/python/pulumi_gcp/logging/_inputs.py | Python | FolderSinkBigqueryOptionsArgs | FolderSinkBigqueryOptionsArgs | 52 | 77 | 52 | 53 | 0970f8b7d9f44cff29e39f77a5fc8aaa2c97927a | bigcode/the-stack | train |
425ecebaf0045a0f38d2a763 | train | class | @pulumi.input_type
class MetricBucketOptionsExplicitBucketsArgs:
def __init__(__self__, *,
bounds: pulumi.Input[List[pulumi.Input[float]]]):
"""
:param pulumi.Input[List[pulumi.Input[float]]] bounds: The values must be monotonically increasing.
"""
pulumi.set(__self_... | @pulumi.input_type
class MetricBucketOptionsExplicitBucketsArgs:
| def __init__(__self__, *,
bounds: pulumi.Input[List[pulumi.Input[float]]]):
"""
:param pulumi.Input[List[pulumi.Input[float]]] bounds: The values must be monotonically increasing.
"""
pulumi.set(__self__, "bounds", bounds)
@property
@pulumi.getter
def bo... | (self, "linear_buckets")
@linear_buckets.setter
def linear_buckets(self, value: Optional[pulumi.Input['MetricBucketOptionsLinearBucketsArgs']]):
pulumi.set(self, "linear_buckets", value)
@pulumi.input_type
class MetricBucketOptionsExplicitBucketsArgs:
| 64 | 64 | 165 | 14 | 50 | dimpu47/pulumi-gcp | sdk/python/pulumi_gcp/logging/_inputs.py | Python | MetricBucketOptionsExplicitBucketsArgs | MetricBucketOptionsExplicitBucketsArgs | 145 | 164 | 145 | 146 | 9fd5a3827fb472d9bf7005939bdb928d833bf354 | bigcode/the-stack | train |
a9a41343d370c687285dd85b | train | class | class MetaBlockStateReference(IdentifiedObject):
def __init__(self, positiveFlowIn=False, StandardControlBlock_MetaBlockConnectable=None, MetaBlockConnectable=None, MemberOf_MetaBlockReference=None, *args, **kw_args):
"""Initialises a new 'MetaBlockStateReference' instance.
@param positiveFlowIn: ... | class MetaBlockStateReference(IdentifiedObject):
| def __init__(self, positiveFlowIn=False, StandardControlBlock_MetaBlockConnectable=None, MetaBlockConnectable=None, MemberOf_MetaBlockReference=None, *args, **kw_args):
"""Initialises a new 'MetaBlockStateReference' instance.
@param positiveFlowIn: If true then any flows associated with a terminal ... | 1 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense... | 252 | 252 | 842 | 10 | 241 | MaximeBaudette/PyCIM | CIM14/IEC61970/Dynamics/MetaBlockStateReference.py | Python | MetaBlockStateReference | MetaBlockStateReference | 23 | 100 | 23 | 24 | ae27addf90e43d831383a87e38ed9ecf49508013 | bigcode/the-stack | train |
ec6787516f185b8c737206b7 | train | class | class ClientRequest:
GET_METHODS = {
hdrs.METH_GET,
hdrs.METH_HEAD,
hdrs.METH_OPTIONS,
hdrs.METH_TRACE,
}
POST_METHODS = {hdrs.METH_PATCH, hdrs.METH_POST, hdrs.METH_PUT}
ALL_METHODS = GET_METHODS.union(POST_METHODS).union({hdrs.METH_DELETE})
DEFAULT_HEADERS = {
... | class ClientRequest:
| GET_METHODS = {
hdrs.METH_GET,
hdrs.METH_HEAD,
hdrs.METH_OPTIONS,
hdrs.METH_TRACE,
}
POST_METHODS = {hdrs.METH_PATCH, hdrs.METH_POST, hdrs.METH_PUT}
ALL_METHODS = GET_METHODS.union(POST_METHODS).union({hdrs.METH_DELETE})
DEFAULT_HEADERS = {
hdrs.ACCEPT: '*/*'... | ssl is not None:
raise ValueError("verify_ssl, ssl_context, fingerprint and ssl "
"parameters are mutually exclusive")
else:
ssl = False
if ssl_context is not None:
warnings.warn("ssl_context is deprecated, use ssl=context instead",
... | 255 | 256 | 2,843 | 4 | 251 | CoderLeague/research_aiohttp | aiohttp/client_reqrep.py | Python | ClientRequest | ClientRequest | 128 | 526 | 128 | 128 | 9c11c2b7cd0043ce4b0348fa8549e3a53005a68f | bigcode/the-stack | train |
e6c52fd4df024082b0cc0f0d | train | class | class ClientResponse(HeadersMixin):
# from the Status-Line of the response
version = None # HTTP-Version
status = None # Status-Code
reason = None # Reason-Phrase
content = None # Payload stream
headers = None # Response headers, CIMultiDictProxy
raw_headers = None # Response raw h... | class ClientResponse(HeadersMixin):
# from the Status-Line of the response
| version = None # HTTP-Version
status = None # Status-Code
reason = None # Reason-Phrase
content = None # Payload stream
headers = None # Response headers, CIMultiDictProxy
raw_headers = None # Response raw headers, a sequence of pairs
_connection = None # current connection
fl... | if self.version == HttpVersion11:
connection = 'close'
if connection is not None:
self.headers[hdrs.CONNECTION] = connection
# status + headers
status_line = '{0} {1} HTTP/{2[0]}.{2[1]}\r\n'.format(
self.method, path, self.version)
... | 256 | 256 | 2,130 | 17 | 238 | CoderLeague/research_aiohttp | aiohttp/client_reqrep.py | Python | ClientResponse | ClientResponse | 529 | 863 | 529 | 531 | 868198aacdc2674279dc57ea235794412d550fc8 | bigcode/the-stack | train |
0fafc650bc33f6e942044bea | train | function | def _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint):
if verify_ssl is not None and not verify_ssl:
warnings.warn("verify_ssl is deprecated, use ssl=False instead",
DeprecationWarning,
stacklevel=3)
if ssl is not None:
raise ValueEr... | def _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint):
| if verify_ssl is not None and not verify_ssl:
warnings.warn("verify_ssl is deprecated, use ssl=False instead",
DeprecationWarning,
stacklevel=3)
if ssl is not None:
raise ValueError("verify_ssl, ssl_context, fingerprint and ssl "
... | , *_ = transport.get_extra_info('peername')
raise ServerFingerprintMismatch(self._fingerprint,
got, host, port)
if ssl is not None:
SSL_ALLOWED_TYPES = (ssl.SSLContext, bool, Fingerprint, type(None))
else: # pragma: no cover
SSL_ALLOWED_TYPES = type(Non... | 86 | 86 | 289 | 16 | 70 | CoderLeague/research_aiohttp | aiohttp/client_reqrep.py | Python | _merge_ssl_params | _merge_ssl_params | 90 | 122 | 90 | 90 | 167b91b2fca5bc1e23c10ee1abce569129ab0851 | bigcode/the-stack | train |
577b49b3d39f68c11bd454c0 | train | class | class Fingerprint:
HASHFUNC_BY_DIGESTLEN = {
16: md5,
20: sha1,
32: sha256,
}
def __init__(self, fingerprint):
digestlen = len(fingerprint)
hashfunc = self.HASHFUNC_BY_DIGESTLEN.get(digestlen)
if not hashfunc:
raise ValueError('fingerprint has inv... | class Fingerprint:
| HASHFUNC_BY_DIGESTLEN = {
16: md5,
20: sha1,
32: sha256,
}
def __init__(self, fingerprint):
digestlen = len(fingerprint)
hashfunc = self.HASHFUNC_BY_DIGESTLEN.get(digestlen)
if not hashfunc:
raise ValueError('fingerprint has invalid length')
... | no cover
import chardet
__all__ = ('ClientRequest', 'ClientResponse', 'RequestInfo', 'Fingerprint')
ContentDisposition = collections.namedtuple(
'ContentDisposition', ('type', 'parameters', 'filename'))
RequestInfo = collections.namedtuple(
'RequestInfo', ('url', 'method', 'headers'))
class Fingerpri... | 75 | 76 | 255 | 4 | 71 | CoderLeague/research_aiohttp | aiohttp/client_reqrep.py | Python | Fingerprint | Fingerprint | 50 | 81 | 50 | 50 | 555343853c302d23e715ed1dbe0eb71fd867c633 | bigcode/the-stack | train |
31baa274790477c71a03d73e | train | class | class ConferenceInfoSchema(Schema):
"""Conference info schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
acronym = fields.Str()
country = fields.Str()
dates = fields.Str()
identifiers = fields.List(fields.Nested(IdentifierSchema))
place = field... | class ConferenceInfoSchema(Schema):
| """Conference info schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
acronym = fields.Str()
country = fields.Str()
dates = fields.Str()
identifiers = fields.List(fields.Nested(IdentifierSchema))
place = fields.Str(required=True)
series = fi... | meta = fields.Str()
class AlternativeTitleSchema(Schema):
"""Alternative title schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
language = fields.Str()
type = fields.Str()
value = fields.Str(required=True)
class ConferenceInfoSchema(Schema):
| 64 | 64 | 89 | 7 | 57 | NRodriguezcuellar/invenio-app-ils | invenio_app_ils/documents/loaders/jsonschemas/document.py | Python | ConferenceInfoSchema | ConferenceInfoSchema | 91 | 106 | 91 | 91 | da5a113639f39c960ffdbfbbcaf5066704fa5a7f | bigcode/the-stack | train |
81bf55e3fe947512afcf702d | train | class | class SubjectSchema(Schema):
"""Subject schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
scheme = fields.Str(required=True)
value = fields.Str(required=True)
| class SubjectSchema(Schema):
| """Subject schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
scheme = fields.Str(required=True)
value = fields.Str(required=True)
| fields.Str()
user = fields.Str()
value = fields.Str(required=True)
class KeywordSchema(Schema):
"""Keyword schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
source = fields.Str()
value = fields.Str()
class SubjectSchema(Schema):
| 64 | 64 | 45 | 6 | 58 | NRodriguezcuellar/invenio-app-ils | invenio_app_ils/documents/loaders/jsonschemas/document.py | Python | SubjectSchema | SubjectSchema | 163 | 172 | 163 | 163 | a1c1668d7c011d43290d4ee71e89eb0ce9d537db | bigcode/the-stack | train |
40357519a00648fa32a01b9f | train | class | class OpenDefinitionLicenseSchema(Schema):
"""Open definition license."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
id = fields.Str(required=True)
| class OpenDefinitionLicenseSchema(Schema):
| """Open definition license."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
id = fields.Str(required=True)
| for the schema."""
unknown = EXCLUDE
artid = fields.Str()
journal_issue = fields.Str()
journal_title = fields.Str()
journal_volume = fields.Str()
note = fields.Str()
pages = fields.Str()
year = fields.Int()
class OpenDefinitionLicenseSchema(Schema):
| 64 | 64 | 40 | 8 | 56 | NRodriguezcuellar/invenio-app-ils | invenio_app_ils/documents/loaders/jsonschemas/document.py | Python | OpenDefinitionLicenseSchema | OpenDefinitionLicenseSchema | 192 | 200 | 192 | 192 | b0108a4ddd6e8543e2cbbf0f7012df863cfc9164 | bigcode/the-stack | train |
5a9fb1b7d3f4042b32dd113a | train | class | class PublicationInfoSchema(Schema):
"""Publication info schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
artid = fields.Str()
journal_issue = fields.Str()
journal_title = fields.Str()
journal_volume = fields.Str()
note = fields.Str()
page... | class PublicationInfoSchema(Schema):
| """Publication info schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
artid = fields.Str()
journal_issue = fields.Str()
journal_title = fields.Str()
journal_volume = fields.Str()
note = fields.Str()
pages = fields.Str()
year = fields.In... | source = fields.Str()
value = fields.Str()
class SubjectSchema(Schema):
"""Subject schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
scheme = fields.Str(required=True)
value = fields.Str(required=True)
class PublicationInfoSchema(Schema):
| 64 | 64 | 77 | 7 | 57 | NRodriguezcuellar/invenio-app-ils | invenio_app_ils/documents/loaders/jsonschemas/document.py | Python | PublicationInfoSchema | PublicationInfoSchema | 175 | 189 | 175 | 175 | cccd54fd93f75e28430705cd2f6ece54df22b5d8 | bigcode/the-stack | train |
1a80d967a91eb3b76208186a | train | class | class CopyrightsSchema(Schema):
"""Copyright schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
holder = fields.Str()
material = fields.Str()
statement = fields.Str()
url = fields.Str()
year = fields.Int()
| class CopyrightsSchema(Schema):
| """Copyright schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
holder = fields.Str()
material = fields.Str()
statement = fields.Str()
url = fields.Str()
year = fields.Int()
| acronym = fields.Str()
country = fields.Str()
dates = fields.Str()
identifiers = fields.List(fields.Nested(IdentifierSchema))
place = fields.Str(required=True)
series = fields.Str()
title = fields.Str(required=True)
year = fields.Int()
class CopyrightsSchema(Schema):
| 64 | 64 | 60 | 7 | 57 | NRodriguezcuellar/invenio-app-ils | invenio_app_ils/documents/loaders/jsonschemas/document.py | Python | CopyrightsSchema | CopyrightsSchema | 109 | 121 | 109 | 109 | ca4b21756c7d8e957030b02084062b1fa9edf171 | bigcode/the-stack | train |
d4d6a8c1597abff385c87701 | train | class | class LicenseSchema(Schema):
"""License schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
internal_notes = fields.Str()
license = fields.Nested(OpenDefinitionLicenseSchema, required=True)
material = fields.Str()
| class LicenseSchema(Schema):
| """License schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
internal_notes = fields.Str()
license = fields.Nested(OpenDefinitionLicenseSchema, required=True)
material = fields.Str()
| note = fields.Str()
pages = fields.Str()
year = fields.Int()
class OpenDefinitionLicenseSchema(Schema):
"""Open definition license."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
id = fields.Str(required=True)
class LicenseSchema(Schema):
| 64 | 64 | 56 | 6 | 58 | NRodriguezcuellar/invenio-app-ils | invenio_app_ils/documents/loaders/jsonschemas/document.py | Python | LicenseSchema | LicenseSchema | 203 | 213 | 203 | 203 | 7121b4e4d56985af715723e39dcd05535fc0539a | bigcode/the-stack | train |
1e75a06440377a89bb8be67d | train | class | class InternalNoteSchema(Schema):
"""Internal note schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
field = fields.Str()
user = fields.Str()
value = fields.Str(required=True)
| class InternalNoteSchema(Schema):
| """Internal note schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
field = fields.Str()
user = fields.Str()
value = fields.Str(required=True)
| ()
class ImprintSchema(Schema):
"""Imprint schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
date = fields.Str()
place = fields.Str()
publisher = fields.Str()
reprint = fields.Str()
class InternalNoteSchema(Schema):
| 64 | 64 | 51 | 7 | 57 | NRodriguezcuellar/invenio-app-ils | invenio_app_ils/documents/loaders/jsonschemas/document.py | Python | InternalNoteSchema | InternalNoteSchema | 138 | 148 | 138 | 138 | d7b2c8ba3312a7d7d26f9c05d8c19baf4e4d96c7 | bigcode/the-stack | train |
ec1d8b57b8a338286219e46d | train | class | class IdentifierSchema(Schema):
"""Identifier schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
material = fields.Str()
scheme = fields.Str(required=True)
value = fields.Str(required=True)
| class IdentifierSchema(Schema):
| """Identifier schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
material = fields.Str()
scheme = fields.Str(required=True)
value = fields.Str(required=True)
| from invenio_app_ils.documents.api import Document
from invenio_app_ils.records.loaders.schemas.changed_by import (
ChangedBySchema,
set_changed_by,
)
from invenio_app_ils.records.loaders.schemas.preserve_cover_metadata import (
preserve_cover_metadata,
)
class IdentifierSchema(Schema):
| 64 | 64 | 51 | 6 | 58 | NRodriguezcuellar/invenio-app-ils | invenio_app_ils/documents/loaders/jsonschemas/document.py | Python | IdentifierSchema | IdentifierSchema | 24 | 34 | 24 | 24 | 3bb6819ca7e16b15abcc8b084291184c4aed8e1b | bigcode/the-stack | train |
4cb5c264a4abd58fc03aec29 | train | class | class ImprintSchema(Schema):
"""Imprint schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
date = fields.Str()
place = fields.Str()
publisher = fields.Str()
reprint = fields.Str()
| class ImprintSchema(Schema):
| """Imprint schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
date = fields.Str()
place = fields.Str()
publisher = fields.Str()
reprint = fields.Str()
| Schema(Schema):
"""Copyright schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
holder = fields.Str()
material = fields.Str()
statement = fields.Str()
url = fields.Str()
year = fields.Int()
class ImprintSchema(Schema):
| 64 | 64 | 56 | 7 | 57 | NRodriguezcuellar/invenio-app-ils | invenio_app_ils/documents/loaders/jsonschemas/document.py | Python | ImprintSchema | ImprintSchema | 124 | 135 | 124 | 124 | 6297608d2084b1f20a94ad4cf88413513e85a1a0 | bigcode/the-stack | train |
5b374a10df87288f860c144b | train | class | class AlternativeTitleSchema(Schema):
"""Alternative title schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
language = fields.Str()
type = fields.Str()
value = fields.Str(required=True)
| class AlternativeTitleSchema(Schema):
| """Alternative title schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
language = fields.Str()
type = fields.Str()
value = fields.Str(required=True)
| .Str())
type = fields.Str()
class UrlSchema(Schema):
"""URL schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
description = fields.Str()
value = fields.URL(required=True)
meta = fields.Str()
class AlternativeTitleSchema(Schema):
| 64 | 64 | 51 | 7 | 57 | NRodriguezcuellar/invenio-app-ils | invenio_app_ils/documents/loaders/jsonschemas/document.py | Python | AlternativeTitleSchema | AlternativeTitleSchema | 78 | 88 | 78 | 78 | 15964f540f6936a0b4d6580b0c3b41fdebfc9c6f | bigcode/the-stack | train |
776acef2f0d6a8927d72cd58 | train | class | class DocumentSchemaV1(RecordMetadataSchemaJSONV1):
"""Document schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
abstract = fields.Str()
alternative_abstracts = fields.List(fields.Str())
alternative_identifiers = fields.List(fields.Nested(IdentifierSc... | class DocumentSchemaV1(RecordMetadataSchemaJSONV1):
| """Document schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
abstract = fields.Str()
alternative_abstracts = fields.List(fields.Str())
alternative_identifiers = fields.List(fields.Nested(IdentifierSchema))
alternative_titles = fields.List(fields.N... | PublicationInfoSchema(Schema):
"""Publication info schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
artid = fields.Str()
journal_issue = fields.Str()
journal_title = fields.Str()
journal_volume = fields.Str()
note = fields.Str()
pages = f... | 185 | 185 | 617 | 13 | 172 | NRodriguezcuellar/invenio-app-ils | invenio_app_ils/documents/loaders/jsonschemas/document.py | Python | DocumentSchemaV1 | DocumentSchemaV1 | 216 | 296 | 216 | 216 | ec55c3728a8ef6e35d6321e937a89a205170a187 | bigcode/the-stack | train |
dd977ddeac3d4ad2e27e547f | train | class | class UrlSchema(Schema):
"""URL schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
description = fields.Str()
value = fields.URL(required=True)
meta = fields.Str()
| class UrlSchema(Schema):
| """URL schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
description = fields.Str()
value = fields.URL(required=True)
meta = fields.Str()
|
affiliations = fields.List(fields.Nested(AffiliationSchema))
alternative_names = fields.List(fields.Str())
full_name = fields.Str(required=True)
identifiers = fields.List(fields.Nested(IdentifierSchema))
roles = fields.List(fields.Str())
type = fields.Str()
class UrlSchema(Schema):
| 64 | 64 | 49 | 6 | 58 | NRodriguezcuellar/invenio-app-ils | invenio_app_ils/documents/loaders/jsonschemas/document.py | Python | UrlSchema | UrlSchema | 65 | 75 | 65 | 65 | ce7a847ced6d347a5ef4808e90efb2da8d3f029d | bigcode/the-stack | train |
ade458061ddfa9dd54024561 | train | class | class AuthorSchema(Schema):
"""Author schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
affiliations = fields.List(fields.Nested(AffiliationSchema))
alternative_names = fields.List(fields.Str())
full_name = fields.Str(required=True)
identifiers = f... | class AuthorSchema(Schema):
| """Author schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
affiliations = fields.List(fields.Nested(AffiliationSchema))
alternative_names = fields.List(fields.Str())
full_name = fields.Str(required=True)
identifiers = fields.List(fields.Nested(Ide... | value = fields.Str(required=True)
class AffiliationSchema(Schema):
"""Affiliation schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
identifiers = fields.List(fields.Nested(IdentifierSchema))
name = fields.Str(required=True)
class AuthorSchema(Schema):
| 64 | 64 | 86 | 6 | 58 | NRodriguezcuellar/invenio-app-ils | invenio_app_ils/documents/loaders/jsonschemas/document.py | Python | AuthorSchema | AuthorSchema | 49 | 62 | 49 | 49 | 3be987c28e1d10fd1f14dba14d9d4a80a3b31acb | bigcode/the-stack | train |
3582caef76e93b185a294f42 | train | class | class KeywordSchema(Schema):
"""Keyword schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
source = fields.Str()
value = fields.Str()
| class KeywordSchema(Schema):
| """Keyword schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
source = fields.Str()
value = fields.Str()
| reprint = fields.Str()
class InternalNoteSchema(Schema):
"""Internal note schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
field = fields.Str()
user = fields.Str()
value = fields.Str(required=True)
class KeywordSchema(Schema):
| 64 | 64 | 41 | 6 | 58 | NRodriguezcuellar/invenio-app-ils | invenio_app_ils/documents/loaders/jsonschemas/document.py | Python | KeywordSchema | KeywordSchema | 151 | 160 | 151 | 151 | bbba017893024a6ee551fd251f2191aa086b8fb8 | bigcode/the-stack | train |
b1f8e54e0824e3abb0f76046 | train | class | class AffiliationSchema(Schema):
"""Affiliation schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
identifiers = fields.List(fields.Nested(IdentifierSchema))
name = fields.Str(required=True)
| class AffiliationSchema(Schema):
| """Affiliation schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
identifiers = fields.List(fields.Nested(IdentifierSchema))
name = fields.Str(required=True)
| preserve_cover_metadata,
)
class IdentifierSchema(Schema):
"""Identifier schema."""
class Meta:
"""Meta attributes for the schema."""
unknown = EXCLUDE
material = fields.Str()
scheme = fields.Str(required=True)
value = fields.Str(required=True)
class AffiliationSchema(Schema... | 64 | 64 | 51 | 7 | 57 | NRodriguezcuellar/invenio-app-ils | invenio_app_ils/documents/loaders/jsonschemas/document.py | Python | AffiliationSchema | AffiliationSchema | 37 | 46 | 37 | 37 | cd89f4218123f2d720274e931398a2b93b470015 | bigcode/the-stack | train |
f49cf3751fbe4a0149adbbac | train | function | def get_service(hass, config, discovery_info=None):
"""Get the Matrix notification service."""
return MatrixNotificationService(config.get(CONF_DEFAULT_ROOM))
| def get_service(hass, config, discovery_info=None):
| """Get the Matrix notification service."""
return MatrixNotificationService(config.get(CONF_DEFAULT_ROOM))
| ,
BaseNotificationService,
ATTR_MESSAGE)
_LOGGER = logging.getLogger(__name__)
CONF_DEFAULT_ROOM = 'default_room'
DOMAIN = 'matrix'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_DEFAULT_ROOM): cv.string,
})
d... | 64 | 64 | 32 | 12 | 52 | zalke/home-assistant | homeassistant/components/matrix/notify.py | Python | get_service | get_service | 21 | 23 | 21 | 21 | 7d53d7d11ccfbb148355d2d85665329751bebe29 | bigcode/the-stack | train |
b8dc42e8053e80677dff0e61 | train | class | class MatrixNotificationService(BaseNotificationService):
"""Send Notifications to a Matrix Room."""
def __init__(self, default_room):
"""Set up the notification service."""
self._default_room = default_room
def send_message(self, message="", **kwargs):
"""Send the message to the m... | class MatrixNotificationService(BaseNotificationService):
| """Send Notifications to a Matrix Room."""
def __init__(self, default_room):
"""Set up the notification service."""
self._default_room = default_room
def send_message(self, message="", **kwargs):
"""Send the message to the matrix server."""
target_rooms = kwargs.get(ATTR_TA... | = 'matrix'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_DEFAULT_ROOM): cv.string,
})
def get_service(hass, config, discovery_info=None):
"""Get the Matrix notification service."""
return MatrixNotificationService(config.get(CONF_DEFAULT_ROOM))
class MatrixNotificationService(BaseNotificat... | 64 | 64 | 123 | 8 | 56 | zalke/home-assistant | homeassistant/components/matrix/notify.py | Python | MatrixNotificationService | MatrixNotificationService | 26 | 43 | 26 | 26 | 2d42581bb6784f5d2af822a64f5c1196306b45e7 | bigcode/the-stack | train |
432dd225e05afada364483ef | train | function | async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
return True
| async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
| return True
| _sensor import BinarySensorEntity
from homeassistant.core import callback
from .const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.config_entries import ConfigEntry
from homeassistant.util import slugify
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
| 64 | 64 | 24 | 20 | 43 | nova12324/HomeAssistant-Tapo-Control | custom_components/tapo_control/binary_sensor.py | Python | async_unload_entry | async_unload_entry | 10 | 11 | 10 | 10 | b5e761ab783bc17ad567861106ffe4117552fdda | bigcode/the-stack | train |
c243a0e357f77cce6dcf2a75 | train | function | async def async_setup_entry(hass, entry, async_add_entities):
events = hass.data[DOMAIN][entry.entry_id]["events"]
name = hass.data[DOMAIN][entry.entry_id]["name"]
camData = hass.data[DOMAIN][entry.entry_id]["camData"]
entities = {
event.uid: TapoBinarySensor(event.uid, events, name, camData)
... | async def async_setup_entry(hass, entry, async_add_entities):
| events = hass.data[DOMAIN][entry.entry_id]["events"]
name = hass.data[DOMAIN][entry.entry_id]["name"]
camData = hass.data[DOMAIN][entry.entry_id]["camData"]
entities = {
event.uid: TapoBinarySensor(event.uid, events, name, camData)
for event in events.get_platform("binary_sensor")
}
... |
from homeassistant.core import HomeAssistant
from homeassistant.config_entries import ConfigEntry
from homeassistant.util import slugify
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
return True
async def async_setup_entry(hass, entry, async_add_entities):
| 64 | 64 | 184 | 14 | 49 | nova12324/HomeAssistant-Tapo-Control | custom_components/tapo_control/binary_sensor.py | Python | async_setup_entry | async_setup_entry | 14 | 36 | 14 | 14 | da25f76c5c3833b4825cb0df9fa00d5848f86008 | bigcode/the-stack | train |
7557a2a034bde5c3f6762d05 | train | class | class TapoBinarySensor(BinarySensorEntity):
def __init__(self, uid, events, name, camData):
self._name = name
self._attributes = camData["basic_info"]
BinarySensorEntity.__init__(self)
self.uid = uid
self.events = events
@property
def is_on(self) -> bool:
re... | class TapoBinarySensor(BinarySensorEntity):
| def __init__(self, uid, events, name, camData):
self._name = name
self._attributes = camData["basic_info"]
BinarySensorEntity.__init__(self)
self.uid = uid
self.events = events
@property
def is_on(self) -> bool:
return self.events.get_uid(self.uid).value
... | }
async_add_entities(entities.values())
@callback
def async_check_entities():
new_entities = []
for event in events.get_platform("binary_sensor"):
if event.uid not in entities:
entities[event.uid] = TapoBinarySensor(event.uid, events, name, camData)
... | 102 | 102 | 343 | 9 | 92 | nova12324/HomeAssistant-Tapo-Control | custom_components/tapo_control/binary_sensor.py | Python | TapoBinarySensor | TapoBinarySensor | 39 | 93 | 39 | 39 | 6759ef51299fded946d5b29261997b0089ea24b0 | bigcode/the-stack | train |
d6f9af7c2852c2f93c9ae8d1 | train | class | class RqdataClient:
"""
Client for querying history data from RQData.
"""
def __init__(self):
""""""
self.username = SETTINGS["rqdata.username"]
self.password = SETTINGS["rqdata.password"]
self.inited = False
self.symbols = set()
def init(self, username="",... | class RqdataClient:
| """
Client for querying history data from RQData.
"""
def __init__(self):
""""""
self.username = SETTINGS["rqdata.username"]
self.password = SETTINGS["rqdata.password"]
self.inited = False
self.symbols = set()
def init(self, username="", password=""):
... | from datetime import datetime, timedelta
from typing import List
from rqdatac import init as rqdata_init
from rqdatac.services.basic import all_instruments as rqdata_all_instruments
from rqdatac.services.get_price import get_price as rqdata_get_price
from rqdatac.share.errors import AuthenticationFailed
from .setting... | 174 | 236 | 788 | 6 | 168 | JonnyORZ/vnpy | vnpy/trader/rqdata.py | Python | RqdataClient | RqdataClient | 27 | 157 | 27 | 27 | bb8d7b9e162fa6106e9c3064d49812ee5775e770 | bigcode/the-stack | train |
d6dfe157274dd10c88f0d661 | train | class | class Point:
# A method defining how to create a point: (self shoule be the first argument for any method within a Python class)
def __init__(self, x, y):
self.x = x
self.y = y
| class Point:
# A method defining how to create a point: (self shoule be the first argument for any method within a Python class)
| def __init__(self, x, y):
self.x = x
self.y = y
| class Point:
# A method defining how to create a point: (self shoule be the first argument for any method within a Python class)
| 30 | 64 | 53 | 30 | 0 | fangyiyu/CS50_web_programming | Python/classes0.py | Python | Point | Point | 1 | 5 | 1 | 2 | 3aa0a9f4fa9fb6590bdffe055757b33cebd9ca65 | bigcode/the-stack | train |
2e713fd843cda49289d34121 | train | class | class UniqueAssetTest(MulecoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 3
self.extra_args = [['-assetindex'], ['-assetindex'], ['-assetindex']]
def activate_assets(self):
self.log.info("Generating FOXD for node[0] and activating as... | class UniqueAssetTest(MulecoinTestFramework):
| def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 3
self.extra_args = [['-assetindex'], ['-assetindex'], ['-assetindex']]
def activate_assets(self):
self.log.info("Generating FOXD for node[0] and activating assets...")
n0 = self.nodes[0]
n... | (c) 2017 The Bitcoin Core developers
# Copyright (c) 2017-2018 The Mulecoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Testing unique asset use cases"""
import random
from test_framework.test_framework im... | 256 | 256 | 1,072 | 10 | 245 | mulecore/mulecoin | test/functional/feature_unique_assets.py | Python | UniqueAssetTest | UniqueAssetTest | 30 | 139 | 30 | 30 | 400dc06627dfdd3efc4f1ccb395ab2b944627e45 | bigcode/the-stack | train |
84c812f1475f76f9d686bee0 | train | function | def gen_root_asset_name():
size = random.randint(3, 14)
name = ""
for _ in range(1, size+1):
ch = random.randint(65, 65+25)
name += chr(ch)
return name
| def gen_root_asset_name():
| size = random.randint(3, 14)
name = ""
for _ in range(1, size+1):
ch = random.randint(65, 65+25)
name += chr(ch)
return name
| or http://www.opensource.org/licenses/mit-license.php.
"""Testing unique asset use cases"""
import random
from test_framework.test_framework import MulecoinTestFramework
from test_framework.util import assert_contains, assert_does_not_contain_key, assert_equal, assert_raises_rpc_error
def gen_root_asset_name():
| 64 | 64 | 56 | 6 | 57 | mulecore/mulecoin | test/functional/feature_unique_assets.py | Python | gen_root_asset_name | gen_root_asset_name | 13 | 19 | 13 | 13 | 82f7968a83f6c53620c7eb5f941c1e20065b5023 | bigcode/the-stack | train |
f05cb15e0d696206bb41d39f | train | function | def gen_unique_asset_name(root):
tag_ab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@$%&*()[]{}_.?-:"
name = root + "#"
tag_size = random.randint(1, 15)
for _ in range(1, tag_size+1):
tag_c = tag_ab[random.randint(0, len(tag_ab) - 1)]
name += tag_c
return name
| def gen_unique_asset_name(root):
| tag_ab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@$%&*()[]{}_.?-:"
name = root + "#"
tag_size = random.randint(1, 15)
for _ in range(1, tag_size+1):
tag_c = tag_ab[random.randint(0, len(tag_ab) - 1)]
name += tag_c
return name
|
def gen_root_asset_name():
size = random.randint(3, 14)
name = ""
for _ in range(1, size+1):
ch = random.randint(65, 65+25)
name += chr(ch)
return name
def gen_unique_asset_name(root):
| 64 | 64 | 89 | 7 | 56 | mulecore/mulecoin | test/functional/feature_unique_assets.py | Python | gen_unique_asset_name | gen_unique_asset_name | 21 | 28 | 21 | 21 | 282af019592607334d3bdeab6d729c2236e2df25 | bigcode/the-stack | train |
043cfedff11c2e282762c9ff | train | function | async def test_config_flow_vacuum_success(hass):
"""Test a successful config flow for a vacuum."""
test_vacuum_model = const.MODELS_VACUUM[0]
await config_flow_device_success(hass, test_vacuum_model)
| async def test_config_flow_vacuum_success(hass):
| """Test a successful config flow for a vacuum."""
test_vacuum_model = const.MODELS_VACUUM[0]
await config_flow_device_success(hass, test_vacuum_model)
| _plug_model = const.MODELS_SWITCH[0]
test_zeroconf_name = const.MODELS_SWITCH[0].replace(".", "-")
await zeroconf_device_success(hass, test_zeroconf_name, test_plug_model)
async def test_config_flow_vacuum_success(hass):
| 64 | 64 | 55 | 12 | 52 | mikan-megane/core | tests/components/xiaomi_miio/test_config_flow.py | Python | test_config_flow_vacuum_success | test_config_flow_vacuum_success | 391 | 394 | 391 | 391 | 3eb6c4afd0ad53735fef4480163966a0f1d0f98d | bigcode/the-stack | train |
2ef0dd6bab88d6f06f625189 | train | function | async def test_zeroconf_missing_data(hass):
"""Test a failed zeroconf discovery because of missing data."""
result = await hass.config_entries.flow.async_init(
const.DOMAIN,
context={"source": config_entries.SOURCE_ZEROCONF},
data={CONF_HOST: TEST_HOST, ZEROCONF_NAME: TEST_ZEROCONF_NAME}... | async def test_zeroconf_missing_data(hass):
| """Test a failed zeroconf discovery because of missing data."""
result = await hass.config_entries.flow.async_init(
const.DOMAIN,
context={"source": config_entries.SOURCE_ZEROCONF},
data={CONF_HOST: TEST_HOST, ZEROCONF_NAME: TEST_ZEROCONF_NAME},
)
assert result["type"] == "abort... | .flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_ZEROCONF}, data={}
)
assert result["type"] == "abort"
assert result["reason"] == "not_xiaomi_miio"
async def test_zeroconf_missing_data(hass):
| 64 | 64 | 108 | 12 | 52 | mikan-megane/core | tests/components/xiaomi_miio/test_config_flow.py | Python | test_zeroconf_missing_data | test_zeroconf_missing_data | 168 | 177 | 168 | 168 | a695e1d12f2aeb75e390316cf1f8a7ba097d5e29 | bigcode/the-stack | train |
d6abb958fe6bc8fcfe0c6cbb | train | function | def get_mock_info(
model=TEST_MODEL,
mac_address=TEST_MAC,
hardware_version=TEST_HARDWARE_VERSION,
firmware_version=TEST_FIRMWARE_VERSION,
):
"""Return a mock gateway info instance."""
gateway_info = Mock()
gateway_info.model = model
gateway_info.mac_address = mac_address
gateway_inf... | def get_mock_info(
model=TEST_MODEL,
mac_address=TEST_MAC,
hardware_version=TEST_HARDWARE_VERSION,
firmware_version=TEST_FIRMWARE_VERSION,
):
| """Return a mock gateway info instance."""
gateway_info = Mock()
gateway_info.model = model
gateway_info.mac_address = mac_address
gateway_info.hardware_version = hardware_version
gateway_info.firmware_version = firmware_version
return gateway_info
| umi-gateway-v3_miio12345678._miio._udp.local."
TEST_SUB_DEVICE_LIST = []
def get_mock_info(
model=TEST_MODEL,
mac_address=TEST_MAC,
hardware_version=TEST_HARDWARE_VERSION,
firmware_version=TEST_FIRMWARE_VERSION,
):
| 63 | 64 | 94 | 39 | 24 | mikan-megane/core | tests/components/xiaomi_miio/test_config_flow.py | Python | get_mock_info | get_mock_info | 28 | 41 | 28 | 33 | 3b422f06fbc7f68eea5051cd5f92b1c36c7b7c1c | bigcode/the-stack | train |
da427f2faadcc1ba2a7e7ae1 | train | function | async def test_config_flow_step_gateway_connect_error(hass):
"""Test config flow, gateway connection error."""
result = await hass.config_entries.flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "form"
assert result["step_id"] == "devi... | async def test_config_flow_step_gateway_connect_error(hass):
| """Test config flow, gateway connection error."""
result = await hass.config_entries.flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "form"
assert result["step_id"] == "device"
assert result["errors"] == {}
with patch(
... | a mock gateway info instance."""
gateway_info = Mock()
gateway_info.model = model
gateway_info.mac_address = mac_address
gateway_info.hardware_version = hardware_version
gateway_info.firmware_version = firmware_version
return gateway_info
async def test_config_flow_step_gateway_connect_error(h... | 64 | 64 | 176 | 12 | 51 | mikan-megane/core | tests/components/xiaomi_miio/test_config_flow.py | Python | test_config_flow_step_gateway_connect_error | test_config_flow_step_gateway_connect_error | 44 | 65 | 44 | 44 | 9589f15d6ea8bbabcef074312ff1f1462a935166 | bigcode/the-stack | train |
b314089fc4f37a0e337bc457 | train | function | async def test_config_flow_plug_success(hass):
"""Test a successful config flow for a plug."""
test_plug_model = const.MODELS_SWITCH[0]
await config_flow_device_success(hass, test_plug_model)
| async def test_config_flow_plug_success(hass):
| """Test a successful config flow for a plug."""
test_plug_model = const.MODELS_SWITCH[0]
await config_flow_device_success(hass, test_plug_model)
| result["data"] == {
const.CONF_FLOW_TYPE: const.CONF_DEVICE,
CONF_HOST: TEST_HOST,
CONF_TOKEN: TEST_TOKEN,
const.CONF_MODEL: model_to_test,
const.CONF_MAC: TEST_MAC,
}
async def test_config_flow_plug_success(hass):
| 64 | 64 | 49 | 11 | 53 | mikan-megane/core | tests/components/xiaomi_miio/test_config_flow.py | Python | test_config_flow_plug_success | test_config_flow_plug_success | 378 | 381 | 378 | 378 | 9c1a50e6b50e26b21637c7b4ac5f9ef079473401 | bigcode/the-stack | train |
e62b9e23dfff77c9653c98ca | train | function | async def test_config_flow_gateway_success(hass):
"""Test a successful config flow."""
result = await hass.config_entries.flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "form"
assert result["step_id"] == "device"
assert result["e... | async def test_config_flow_gateway_success(hass):
| """Test a successful config flow."""
result = await hass.config_entries.flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "form"
assert result["step_id"] == "device"
assert result["errors"] == {}
mock_info = get_mock_info()
... | .flow.async_configure(
result["flow_id"],
{CONF_HOST: TEST_HOST, CONF_TOKEN: TEST_TOKEN},
)
assert result["type"] == "form"
assert result["step_id"] == "device"
assert result["errors"] == {"base": "cannot_connect"}
async def test_config_flow_gateway_success(hass):
| 72 | 73 | 244 | 10 | 62 | mikan-megane/core | tests/components/xiaomi_miio/test_config_flow.py | Python | test_config_flow_gateway_success | test_config_flow_gateway_success | 68 | 99 | 68 | 68 | cd4156ca1b6b7a766d731c5d6aff66380a34cec2 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.