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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
306ce6ac32c87c110e97047a | train | class | @typechecked
class DataRESTAPI:
"""Kraken User's data API."""
def __init__(self, client: Client) -> None:
self.client = client
def account_balance(self) -> httpx.Response:
"""Retrieve all cash balances, net of pending withdrawals."""
return self.client.post(
url=private... | @typechecked
class DataRESTAPI:
| """Kraken User's data API."""
def __init__(self, client: Client) -> None:
self.client = client
def account_balance(self) -> httpx.Response:
"""Retrieve all cash balances, net of pending withdrawals."""
return self.client.post(
url=private_url("Balance"),
dat... | License for the specific language governing permissions and
# limitations under the License.
"""Kraken User's Data private API."""
import httpx
from typeguard import typechecked
from ..client import Client
from .utils import nonce_data
from .utils import private_url
@typechecked
class DataRESTAPI:
| 64 | 64 | 141 | 9 | 54 | CryptoBerryBot/Okapi | src/okapi/api/user.py | Python | DataRESTAPI | DataRESTAPI | 23 | 42 | 23 | 24 | 78053f8fdde487c6d4a02dc1e3530d9ebbd2bf38 | bigcode/the-stack | train |
1fba0099c4708b4027659764 | train | function | def presign_s3(request):
"""
The files stored in the AWS S3 bucket are not public and requires authentication for security reasons as the
client might want to limit the access to only certain users. Only certain people should be able to edit the
database. As the user might leak the credentials through n... | def presign_s3(request):
| """
The files stored in the AWS S3 bucket are not public and requires authentication for security reasons as the
client might want to limit the access to only certain users. Only certain people should be able to edit the
database. As the user might leak the credentials through negligence or incompetence... | Error('Upload Option does not match any known type')
update_tag(request, paper)
return redirect('codestudy:index')
else:
context = get_base_context(request)
return render(request, 'codestudy/add-paper.html', context=context)
else:
raise Http404()
def p... | 69 | 69 | 230 | 7 | 62 | DE0CH/csia | codestudy/views.py | Python | presign_s3 | presign_s3 | 167 | 191 | 167 | 167 | dafa9605d172692bdf53328c9a58bf1c4d847895 | bigcode/the-stack | train |
86de808c5fd9b1b22504e219 | train | function | def get_base_context(request):
"""
:param request: The Django Request object
:return: A structured dictionary with the context that needs to be
displayed on all pages, including the User object all all Tag Classes for navigation
"""
return {
'user': get_user(request),
'tag_class... | def get_base_context(request):
| """
:param request: The Django Request object
:return: A structured dictionary with the context that needs to be
displayed on all pages, including the User object all all Tag Classes for navigation
"""
return {
'user': get_user(request),
'tag_classes': TagClass.objects.all()
... |
from threading import Thread
import json
import uuid
from django.conf import settings
from utils import s3_client
import google.oauth2.id_token
import google.auth.transport.requests
from .search_engine import search as s_search
import enum
from django.db import DataError
def get_base_context(request):
| 64 | 64 | 75 | 6 | 57 | DE0CH/csia | codestudy/views.py | Python | get_base_context | get_base_context | 21 | 31 | 21 | 21 | 7ad8d1a5f1dfd69fefbdca0b1829e9b3ed2fa778 | bigcode/the-stack | train |
f03c2da2e72df2fc71929319 | train | function | def edit_tags(request):
"""
This is a Django handler function for editing the tag and tag class in the database
:param request: The Django Request object
:return: The edit tags page
"""
if get_user(request) and get_user(request).can_edit:
if request.method == 'POST':
change_l... | def edit_tags(request):
| """
This is a Django handler function for editing the tag and tag class in the database
:param request: The Django Request object
:return: The edit tags page
"""
if get_user(request) and get_user(request).can_edit:
if request.method == 'POST':
change_log = json.loads(request.... | file_name = request.GET['file_name']
file_name = os.path.join(str(uuid.uuid4()), file_name)
presigned_post = s3_client.generate_presigned_post(
Bucket=settings.AWS_STORAGE_BUCKET_NAME,
Key=file_name,
Fields={"Content-Type": 'application/pdf'},
Con... | 107 | 107 | 359 | 5 | 102 | DE0CH/csia | codestudy/views.py | Python | edit_tags | edit_tags | 194 | 230 | 194 | 194 | 4089859471d97542fc47cbb035942e855aa129c4 | bigcode/the-stack | train |
89125afbc355139a2f7df83b | train | function | def login(request):
"""
This is a Django handler function that verifies the login details according to the token gained by signing in with
Google. Designed to be interacted programmatically
:param request: The Django Request object
:return: The login status in JSON format
"""
if request.meth... | def login(request):
| """
This is a Django handler function that verifies the login details according to the token gained by signing in with
Google. Designed to be interacted programmatically
:param request: The Django Request object
:return: The login status in JSON format
"""
if request.method == 'POST':
... | Paper
:return: None
"""
paper.tags.clear()
for tag_class in TagClass.objects.all():
tags = request.POST.getlist(str(tag_class.pk))
for tag_pk in tags:
tag = Tag.objects.get(pk=uuid.UUID(tag_pk))
paper.tags.add(tag)
paper.save()
def login(request):
| 71 | 71 | 238 | 4 | 67 | DE0CH/csia | codestudy/views.py | Python | login | login | 279 | 309 | 279 | 279 | 40d337124efee6b4627ff155b30d9a23b94c9a9f | bigcode/the-stack | train |
e372fc2701883f79f2a5f9d7 | train | function | def add_paper(request):
"""
This is a Django handler function for adding a paper into the database. This also handlers form submission through
HTTP POST.
:param request: The Django Request object
:return: Depending on the request method, it either returns the upload UI, or a redirect to the index pa... | def add_paper(request):
| """
This is a Django handler function for adding a paper into the database. This also handlers form submission through
HTTP POST.
:param request: The Django Request object
:return: Depending on the request method, it either returns the upload UI, or a redirect to the index page
"""
if get_us... | :param request: The Django Request object
:return: The results page
"""
context = get_base_context(request)
context.update({
'page_title': 'All Papers',
'papers': Paper.objects.all(),
'all_papers': True
})
return render(request, 'codestudy/results.html', context=context)... | 124 | 124 | 416 | 6 | 117 | DE0CH/csia | codestudy/views.py | Python | add_paper | add_paper | 115 | 164 | 115 | 115 | bb500742d3f4cbc54c7a427965509c06e1bf5145 | bigcode/the-stack | train |
67e3ad70de12fdae17aa6325 | train | function | def bookmark(request):
"""
This is a Django handler function for bookmarking a paper. This can be accessed either programmatically or directly
by the user
:param request: The Django Request object
:return: A redirection
"""
user = get_user(request)
if user:
paper = Paper.objects.... | def bookmark(request):
| """
This is a Django handler function for bookmarking a paper. This can be accessed either programmatically or directly
by the user
:param request: The Django Request object
:return: A redirection
"""
user = get_user(request)
if user:
paper = Paper.objects.get(pk=request.GET['pk'... | message': {
'title': '400 Bad Request',
'description': 'Your client has issued a malformed or illegal request.'
}
})
return render(request, 'codestudy/base.html', context=context, status=400)
def invoke_500(request):
raise Exception
def bookmark(request):
| 64 | 64 | 125 | 4 | 59 | DE0CH/csia | codestudy/views.py | Python | bookmark | bookmark | 428 | 444 | 428 | 428 | e27953d6b76669bfa4a91f7007a1231416845aea | bigcode/the-stack | train |
c9894b81ede81f0223d31829 | train | function | def handler400(request, exception):
"""
This is a Django handler function for 400 Bad Request error
:param request: The Django Request object
:param exception: The exception caught
:return: The 400 error page
"""
context = get_base_context(request)
context.update({
'message': {
... | def handler400(request, exception):
| """
This is a Django handler function for 400 Bad Request error
:param request: The Django Request object
:param exception: The exception caught
:return: The 400 error page
"""
context = get_base_context(request)
context.update({
'message': {
'title': '400 Bad Request... | 'message': {
'title': '403 Permission Denied',
'description': 'Looks like you don\'t have the permission to perform the action.'
}
})
return render(request, 'codestudy/base.html', context=context, status=403)
def handler400(request, exception):
| 64 | 64 | 118 | 7 | 57 | DE0CH/csia | codestudy/views.py | Python | handler400 | handler400 | 407 | 421 | 407 | 407 | 312524acdad4a54bc85417dc5c7a27d7a32336f1 | bigcode/the-stack | train |
334995a1a5e6d640c75e88ee | train | class | class UploadOption(enum.IntEnum):
"""
This Enum specifies all upload options and their associated integer value that is used in the front end as well
"""
FILE = 1
LINK = 2
| class UploadOption(enum.IntEnum):
| """
This Enum specifies all upload options and their associated integer value that is used in the front end as well
"""
FILE = 1
LINK = 2
|
"""
context = get_base_context(request)
context.update({
'page_title': 'All Papers',
'papers': Paper.objects.all(),
'all_papers': True
})
return render(request, 'codestudy/results.html', context=context)
class UploadOption(enum.IntEnum):
| 64 | 64 | 45 | 7 | 57 | DE0CH/csia | codestudy/views.py | Python | UploadOption | UploadOption | 107 | 112 | 107 | 107 | 74454263b3cf6027cdac21f7282b088469c8fea4 | bigcode/the-stack | train |
bd66cd716d25b1af79139886 | train | function | def invoke_500(request):
raise Exception
| def invoke_500(request):
| raise Exception
| (request)
context.update({
'message': {
'title': '400 Bad Request',
'description': 'Your client has issued a malformed or illegal request.'
}
})
return render(request, 'codestudy/base.html', context=context, status=400)
def invoke_500(request):
| 64 | 64 | 10 | 6 | 58 | DE0CH/csia | codestudy/views.py | Python | invoke_500 | invoke_500 | 424 | 425 | 424 | 424 | c0f1a5375f03863508cbfc1ac9a5ada47e984c78 | bigcode/the-stack | train |
4088911145ebdf8060a30300 | train | function | def handler500(request):
"""
This is a Django handler function for the 500 server error page. Because a server error can imply an serious issue
such as corrupted database, a nice render of the 500 page may be impossible. So the server first attemps to nicely
render the page with all the dynamic element,... | def handler500(request):
| """
This is a Django handler function for the 500 server error page. Because a server error can imply an serious issue
such as corrupted database, a nice render of the 500 page may be impossible. So the server first attemps to nicely
render the page with all the dynamic element, if it fails, it falls ba... | 'message': {
'title': '404 Not Found',
'description': 'This is no the web page you are looking for.',
}
})
return render(request, 'codestudy/base.html', context=context, status=404)
# noinspection PyBroadException
def handler500(request):
| 64 | 64 | 198 | 5 | 58 | DE0CH/csia | codestudy/views.py | Python | handler500 | handler500 | 367 | 386 | 367 | 367 | d5457ba0ab62242eb6b1056ef645969a0af8a003 | bigcode/the-stack | train |
177394d146b49d507998059a | train | function | def logout(request):
"""
This is a Django handler function that logs the current user out. Designed to be accessed programmatically.
:param request:
:return:
"""
try:
del request.session['sub']
success = True
except KeyError:
success = False
return JsonResponse({'... | def logout(request):
| """
This is a Django handler function that logs the current user out. Designed to be accessed programmatically.
:param request:
:return:
"""
try:
del request.session['sub']
success = True
except KeyError:
success = False
return JsonResponse({'success': success})
| .save()
return redirect('codestudy:admin')
else:
context = get_base_context(request)
context.update({
'users': User.objects.all()
})
return render(request, 'codestudy/admin.html', context=context)
else:
raise Http404()
def l... | 64 | 64 | 72 | 4 | 60 | DE0CH/csia | codestudy/views.py | Python | logout | logout | 334 | 345 | 334 | 334 | cdbc4ed3bf599211b26a6684d064078b890822cb | bigcode/the-stack | train |
978606bb0925208fd13aa596 | train | function | def edit_paper(request, pk):
"""
This is a Django handler function for editing the tags and names for existing papers.
:param request: The Django Request object
:param pk: The primary key of the paper
:return: The edit paper page
"""
if get_user(request) and get_user(request).can_edit:
... | def edit_paper(request, pk):
| """
This is a Django handler function for editing the tags and names for existing papers.
:param request: The Django Request object
:param pk: The primary key of the paper
:return: The edit paper page
"""
if get_user(request) and get_user(request).can_edit:
if request.method == 'POST... | :
logging.exception('Did not find tag class in database')
return redirect('codestudy:edit-tags')
else:
context = get_base_context(request)
return render(request, 'codestudy/edit-tags.html', context=context)
else:
raise Http404()
def edit_paper... | 67 | 67 | 224 | 8 | 59 | DE0CH/csia | codestudy/views.py | Python | edit_paper | edit_paper | 233 | 259 | 233 | 233 | dffafdadee92c1434b5c197c6ada11b9565e0d4b | bigcode/the-stack | train |
b83abba1805ae215a817905b | train | function | def all_papers(request):
"""
This is a Django handler function for browser all papers in the database
:param request: The Django Request object
:return: The results page
"""
context = get_base_context(request)
context.update({
'page_title': 'All Papers',
'papers': Paper.objec... | def all_papers(request):
| """
This is a Django handler function for browser all papers in the database
:param request: The Django Request object
:return: The results page
"""
context = get_base_context(request)
context.update({
'page_title': 'All Papers',
'papers': Paper.objects.all(),
'all_pa... | context = get_base_context(request)
context.update({
'page_title': tag,
'papers': Tag.objects.get(name=tag, tag_class__name=tag_class).paper_set.all(),
})
return render(request, 'codestudy/results.html', context=context)
def all_papers(request):
| 64 | 64 | 97 | 6 | 58 | DE0CH/csia | codestudy/views.py | Python | all_papers | all_papers | 92 | 104 | 92 | 92 | 772b201b3ab76bdcc0a3b6aad60bfb6787a68142 | bigcode/the-stack | train |
593eb1ff6244640b6bf7e5b7 | train | function | def handler404(request, exception):
"""
This is a Django handler function designed to override the default 404 page to provide a nicer formatting that is
consistent with the rest of the website
:param request: The Django Request object
:param exception: The Exception caught
:return: The 404 page... | def handler404(request, exception):
| """
This is a Django handler function designed to override the default 404 page to provide a nicer formatting that is
consistent with the rest of the website
:param request: The Django Request object
:param exception: The Exception caught
:return: The 404 page
"""
context = get_base_cont... | the current user out. Designed to be accessed programmatically.
:param request:
:return:
"""
try:
del request.session['sub']
success = True
except KeyError:
success = False
return JsonResponse({'success': success})
def handler404(request, exception):
| 64 | 64 | 136 | 7 | 57 | DE0CH/csia | codestudy/views.py | Python | handler404 | handler404 | 348 | 363 | 348 | 348 | 31164523eb1f61c52091c570ad120154d0b7894b | bigcode/the-stack | train |
f34067a54f765117e9c8bd80 | train | function | def bookmarked(request):
"""
This is a Django handler for viewing all bookmarked papers
:param request: The Django Request object
:return: The results page
"""
user = get_user(request)
if user:
context = get_base_context(request)
context.update({
'page_title': 'Bo... | def bookmarked(request):
| """
This is a Django handler for viewing all bookmarked papers
:param request: The Django Request object
:return: The results page
"""
user = get_user(request)
if user:
context = get_base_context(request)
context.update({
'page_title': 'Bookmarked',
'p... | paper = Paper.objects.get(pk=request.GET['pk'])
if user.bookmarks.filter(pk=paper.pk).exists():
user.bookmarks.remove(paper)
else:
user.bookmarks.add(paper)
return redirect('codestudy:index')
else:
raise Http404()
def bookmarked(request):
| 64 | 64 | 104 | 4 | 60 | DE0CH/csia | codestudy/views.py | Python | bookmarked | bookmarked | 447 | 462 | 447 | 447 | ea8824010951188fb5b8e74be8d50519730c21e7 | bigcode/the-stack | train |
d6933bda30e1da55a01e17aa | train | function | def admin(request):
"""
This is a Django handler function for the admin console
:param request: The Django Request object
:return: Rendered admin console page
"""
if get_user(request) and get_user(request).is_admin:
if request.method == 'POST':
for user in User.objects.all():... | def admin(request):
| """
This is a Django handler function for the admin console
:param request: The Django Request object
:return: Rendered admin console page
"""
if get_user(request) and get_user(request).is_admin:
if request.method == 'POST':
for user in User.objects.all():
use... | _info['family_name']
user.save()
request.session['sub'] = user.pk
success = True
except ValueError:
# Invalid token
success = False
else:
raise Http404()
return JsonResponse({
'success': success
})
def admin(request):
| 64 | 64 | 146 | 4 | 60 | DE0CH/csia | codestudy/views.py | Python | admin | admin | 312 | 331 | 312 | 312 | 95b7f3061d7df3d1ea5d05e1a3a5a0209056c585 | bigcode/the-stack | train |
185b2bd93c3b5915b6e70e39 | train | function | def browse(request, tag_class=None, tag=None):
"""
This is a Django handler function for browsing all papers tagged with a specific tag
:param request: The Django Request object
:param tag_class: The name of the Tag Class
:param tag: The name of the Tag
:return: The results g
"""
# Thou... | def browse(request, tag_class=None, tag=None):
| """
This is a Django handler function for browsing all papers tagged with a specific tag
:param request: The Django Request object
:param tag_class: The name of the Tag Class
:param tag: The name of the Tag
:return: The results g
"""
# Thought about using the pk of the tag, but used nam... | s_search(terms, tags, user)
context = get_base_context(request)
context.update({
'page_title': f'{terms}',
'papers': papers,
})
return render(request, 'codestudy/results.html', context=context)
def browse(request, tag_class=None, tag=None):
| 64 | 64 | 171 | 11 | 53 | DE0CH/csia | codestudy/views.py | Python | browse | browse | 71 | 89 | 71 | 71 | 058eabad6f86cd8ae57c1697f8d24cdd47a31cff | bigcode/the-stack | train |
2739b5703dfce1b7afa7c7cd | train | function | def index(request):
"""
This is a Django handler function for the index page
:param request: The Django Request object
:return: The index page
"""
if request.method == 'POST':
return redirect('codestudy:index')
else:
context = get_base_context(request)
return render(r... | def index(request):
| """
This is a Django handler function for the index page
:param request: The Django Request object
:return: The index page
"""
if request.method == 'POST':
return redirect('codestudy:index')
else:
context = get_base_context(request)
return render(request, 'codestudy/i... | Request object
:return: A structured dictionary with the context that needs to be
displayed on all pages, including the User object all all Tag Classes for navigation
"""
return {
'user': get_user(request),
'tag_classes': TagClass.objects.all()
}
def index(request):
| 64 | 64 | 81 | 4 | 60 | DE0CH/csia | codestudy/views.py | Python | index | index | 34 | 44 | 34 | 34 | f868f7f88b7587f6faf90c7183b05f4843bb5b2f | bigcode/the-stack | train |
2f9ee464bfd6c7c276907f13 | train | function | def update_tag(request, paper):
"""
This is a helper function that extract the tags in an HTTP POST form and update the tags for the paper object
:param request: The Django Request object
:param paper: the paper that needs to be updated
:type paper: Paper
:return: None
"""
paper.tags.cle... | def update_tag(request, paper):
| """
This is a helper function that extract the tags in an HTTP POST form and update the tags for the paper object
:param request: The Django Request object
:param paper: the paper that needs to be updated
:type paper: Paper
:return: None
"""
paper.tags.clear()
for tag_class in TagCla... | edit-paper', pk)
else:
context = get_base_context(request)
context.update({
'paper': Paper.objects.get(pk=pk),
})
return render(request, 'codestudy/edit-paper.html', context=context)
else:
raise Http404()
def update_tag(request, paper):... | 64 | 64 | 128 | 7 | 57 | DE0CH/csia | codestudy/views.py | Python | update_tag | update_tag | 262 | 276 | 262 | 262 | 60a216630fbe18d0f70350f37f1268b0664cfc2f | bigcode/the-stack | train |
a576ec2882e70a53abc30109 | train | function | def handler403(request, exception):
"""
This is a Django handler function for HTTP 403 permission error
:param request: The Django Request object
:param exception: The exception caught
:return: The 403 error page
"""
logging.exception(exception)
context = get_base_context(request)
co... | def handler403(request, exception):
| """
This is a Django handler function for HTTP 403 permission error
:param request: The Django Request object
:param exception: The exception caught
:return: The 403 error page
"""
logging.exception(exception)
context = get_base_context(request)
context.update({
'message': {
... | 'description': 'Something went wrong. Please try again later.'
}
})
return render(request, 'codestudy/base.html', context=context, status=500)
except:
return render(request, 'codestudy/500.html', status=500)
def handler403(request, exception):
| 64 | 64 | 128 | 7 | 57 | DE0CH/csia | codestudy/views.py | Python | handler403 | handler403 | 389 | 404 | 389 | 389 | 829ae435af46b531f260aff18831e8c25025b00e | bigcode/the-stack | train |
b1dc08e74efa806b7029422b | train | function | def search(request):
"""
This is a Django handler function for the search page. Client would pass information into this function through
HTTP GET parameters
:param request: The Django Request object
:return: The results g
"""
tags = []
for tag_class in TagClass.objects.all():
tag... | def search(request):
| """
This is a Django handler function for the search page. Client would pass information into this function through
HTTP GET parameters
:param request: The Django Request object
:return: The results g
"""
tags = []
for tag_class in TagClass.objects.all():
tag_names = request.GET.... | request: The Django Request object
:return: The index page
"""
if request.method == 'POST':
return redirect('codestudy:index')
else:
context = get_base_context(request)
return render(request, 'codestudy/index.html', context=context)
def search(request):
| 64 | 64 | 177 | 4 | 60 | DE0CH/csia | codestudy/views.py | Python | search | search | 47 | 68 | 47 | 47 | 0e92f7834fbd6614ca16e45bbe8c508c0bf30f09 | bigcode/the-stack | train |
0c8fa7e731575d9788b76333 | train | function | def create_the_image():
""" Create the image with the defined parameters
"""
#base_radius = int(RING_RADII[-1]) * GLOBAL_SCALE_FACTOR
annulus_count = 0
#annulus_radius = []
# Origin
org_x = RING_RADII[-1] * GLOBAL_SCALE_FACTOR
org_y = org_x
print("Scaled origin is {0},{1}".format(... | def create_the_image():
| """ Create the image with the defined parameters
"""
#base_radius = int(RING_RADII[-1]) * GLOBAL_SCALE_FACTOR
annulus_count = 0
#annulus_radius = []
# Origin
org_x = RING_RADII[-1] * GLOBAL_SCALE_FACTOR
org_y = org_x
print("Scaled origin is {0},{1}".format(org_x, org_y))
print... | , can be the same or different
# This number describes how many sectors each sector will be divided into
# If they're not multipes if the ones inside them, the segment lines won't
# meet neatly, but it will still draw just fine!
ANNULUS_SEGMENTS = [6, 30, 60]
# Ring radii
RING_RADII = [20, 40, 60]
# Ring Colours
R... | 157 | 157 | 525 | 5 | 151 | JohnTocher/ConcentricRingMaker | ringthing.py | Python | create_the_image | create_the_image | 44 | 104 | 44 | 44 | 1710459c5928c6db019acb968a02a8a2e3ff7e8e | bigcode/the-stack | train |
6b8f4565283c435ca621d442 | train | function | def progress(loc,
total,
prefix='',
suffix='',
decimals=1,
length=100,
fill='█'):
"""Create terminal progress bar.
@params:
loc - Required : current location (Int)
total - Required : total iterations (... | def progress(loc,
total,
prefix='',
suffix='',
decimals=1,
length=100,
fill='█'):
| """Create terminal progress bar.
@params:
loc - Required : current location (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : positive numb... | torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data
import utils
import data as datalib
import pdb
import maskrcnn
def progress(loc,
total,
prefix='',
suffix='',
decimals=1,
length=100,
fill='... | 71 | 71 | 238 | 30 | 40 | blyucs/MaskRCNN | model.py | Python | progress | progress | 28 | 53 | 28 | 34 | 2a7bcb195f8f24364e59ea0a570fc0b5cf006414 | bigcode/the-stack | train |
2c7b8902a485511ed0374c17 | train | class | class RPN(nn.Module):
"""Builds the model of Region Proposal Network.
anchors_per_location: number of anchors per pixel in the feature map
anchor_stride: Controls the density of anchors. Typically 1 (anchors for
every pixel in the feature map), or 2 (every other pixel).
Returns:
... | class RPN(nn.Module):
| """Builds the model of Region Proposal Network.
anchors_per_location: number of anchors per pixel in the feature map
anchor_stride: Controls the density of anchors. Typically 1 (anchors for
every pixel in the feature map), or 2 (every other pixel).
Returns:
rpn_logits: [batc... | , zeros], dim=0)
elif positive_count > 0:
rois = positive_rois
elif negative_count > 0:
rois = negative_rois
zeros = torch.zeros(negative_count)
if config.GPU_COUNT:
zeros = zeros.cuda()
roi_gt_class_ids = zeros
zeros = torch.zeros(negative_count, 4).i... | 256 | 256 | 1,520 | 6 | 249 | blyucs/MaskRCNN | model.py | Python | RPN | RPN | 590 | 726 | 590 | 590 | 59bbd121978b8a6a15ec827d888f49adb342acec | bigcode/the-stack | train |
6ed0da768dbc1bf1c7b30b5b | train | class | class Mask(nn.Module):
def __init__(self, depth, pool_size, image_shape, num_classes):
super(Mask, self).__init__()
self.depth = depth
self.pool_size = pool_size
self.image_shape = image_shape
self.num_classes = num_classes
self.padding = SamePad2d(kernel_size=3, stri... | class Mask(nn.Module):
| def __init__(self, depth, pool_size, image_shape, num_classes):
super(Mask, self).__init__()
self.depth = depth
self.pool_size = pool_size
self.image_shape = image_shape
self.num_classes = num_classes
self.padding = SamePad2d(kernel_size=3, stride=1)
self.conv... | # (Pdb) p target_bbox.size(), target_class_ids.size(), pred_bbox.size()
# (torch.Size([100, 4]), torch.Size([100]), torch.Size([100, 81, 4]))
if target_class_ids.size(0) > 0:
# Only positive ROIs contribute to the loss. And only
# the right class_id of each ROI. Get thei... | 256 | 256 | 1,175 | 5 | 250 | blyucs/MaskRCNN | model.py | Python | Mask | Mask | 856 | 961 | 856 | 856 | 629c413a5fd2dbd28986893c272ef2341dce46bf | bigcode/the-stack | train |
16c67f14cb924ce0d5c51a24 | train | class | class SamePad2d(nn.Module):
"""'SAME' padding."""
def __init__(self, kernel_size, stride):
"""Init."""
super(SamePad2d, self).__init__()
self.kernel_size = kernel_size
self.stride = stride
def forward(self, input):
"""Keep feature size not changing after CNN."""
... | class SamePad2d(nn.Module):
| """'SAME' padding."""
def __init__(self, kernel_size, stride):
"""Init."""
super(SamePad2d, self).__init__()
self.kernel_size = kernel_size
self.stride = stride
def forward(self, input):
"""Keep feature size not changing after CNN."""
in_width = input.size(2... | ='\n')
# Print New Line on Complete
if loc == total:
print()
def intersect1d(tensor1, tensor2):
"""Intersect 1D set."""
x = torch.LongTensor(list(set(tensor1.tolist()) & set(tensor2.tolist())))
if tensor1.is_cuda:
x = x.cuda()
return x
class SamePad2d(nn.Module):
| 84 | 84 | 280 | 8 | 75 | blyucs/MaskRCNN | model.py | Python | SamePad2d | SamePad2d | 64 | 91 | 64 | 64 | b4565df1dbe423b9f69d9de6ec300ae00839f60d | bigcode/the-stack | train |
a152e57e5d1a366b15427a0c | train | function | def roi_align(inputs, pool_size, image_shape):
"""Implements ROI Pooling on multiple levels of the feature pyramid.
Params:
- inputs = [boxes] + feature_map !!!
- pool_size: [height, width] of the output pooled regions. Usually [7, 7]
- image_shape: [height, width, channels]. Shape of input image i... | def roi_align(inputs, pool_size, image_shape):
| """Implements ROI Pooling on multiple levels of the feature pyramid.
Params:
- inputs = [boxes] + feature_map !!!
- pool_size: [height, width] of the output pooled regions. Usually [7, 7]
- image_shape: [height, width, channels]. Shape of input image in pixels
Inputs:
- boxes: [batch, num_... | 1(x)
x = self.C2(x)
x = self.C3(x)
x = self.C4(x)
if self.C5:
x = self.C5(x)
return x
def stages(self):
return [self.C1, self.C2, self.C3, self.C4, self.C5]
def make_layer(self, block, planes, blocks, stride=1):
downsample = None
if s... | 256 | 256 | 1,160 | 11 | 244 | blyucs/MaskRCNN | model.py | Python | roi_align | roi_align | 284 | 401 | 284 | 284 | 2769a88c7a038415a4734cbc9a52c1c710c89d56 | bigcode/the-stack | train |
7c1abaa8a81845a68da98165 | train | class | class MaskRCNN(nn.Module):
"""Encapsulates the Mask RCNN model functionality."""
def __init__(self, config, model_dir):
"""Global configuration."""
super(MaskRCNN, self).__init__()
self.config = config
self.model_dir = model_dir
self.set_log_dir()
self.build(conf... | class MaskRCNN(nn.Module):
| """Encapsulates the Mask RCNN model functionality."""
def __init__(self, config, model_dir):
"""Global configuration."""
super(MaskRCNN, self).__init__()
self.config = config
self.model_dir = model_dir
self.set_log_dir()
self.build(config=config)
self.ini... | _class_ids.size(), pred_masks.size()
# (torch.Size([100, 28, 28]), torch.Size([100]), torch.Size([100, 81, 28, 28]))
if target_class_ids.size(0) > 0:
# Only positive ROIs contribute to the loss. And only
# the class specific mask of each ROI.
positive_ix = torch.nonz... | 256 | 256 | 8,006 | 7 | 248 | blyucs/MaskRCNN | model.py | Python | MaskRCNN | MaskRCNN | 967 | 1,755 | 967 | 967 | 63f088b6ba1fb8c2e40f648c2aee2173c16a911c | bigcode/the-stack | train |
3d162f77d5e0ef0431879250 | train | class | class FPN(nn.Module):
"""See the paper "Feature Pyramid Networks for Object Detection" for more details."""
def __init__(self, C1, C2, C3, C4, C5, out_channels):
"""FPN Init."""
super(FPN, self).__init__()
self.out_channels = out_channels
self.C1 = C1
self.C2 = C2
... | class FPN(nn.Module):
| """See the paper "Feature Pyramid Networks for Object Detection" for more details."""
def __init__(self, C1, C2, C3, C4, C5, out_channels):
"""FPN Init."""
super(FPN, self).__init__()
self.out_channels = out_channels
self.C1 = C1
self.C2 = C2
self.C3 = C3
... | __()
self.kernel_size = kernel_size
self.stride = stride
def forward(self, input):
"""Keep feature size not changing after CNN."""
in_width = input.size(2)
in_height = input.size(3)
out_width = math.ceil(float(in_width) / float(self.stride))
out_height = math... | 256 | 256 | 1,033 | 6 | 249 | blyucs/MaskRCNN | model.py | Python | FPN | FPN | 97 | 176 | 97 | 97 | b67fa16b32a26395347fe033be312cd023eb0100 | bigcode/the-stack | train |
64518d9113fc3deaae5c23d7 | train | class | class Classifier(nn.Module):
def __init__(self, depth, pool_size, image_shape, num_classes):
super(Classifier, self).__init__()
self.depth = depth
self.pool_size = pool_size
self.image_shape = image_shape
self.num_classes = num_classes
self.conv1 = nn.Conv2d(self.dept... | class Classifier(nn.Module):
| def __init__(self, depth, pool_size, image_shape, num_classes):
super(Classifier, self).__init__()
self.depth = depth
self.pool_size = pool_size
self.image_shape = image_shape
self.num_classes = num_classes
self.conv1 = nn.Conv2d(self.depth, 1024, kernel_size=self.poo... | ), log(dw))]
"""
# pdb.set_trace()
# (Pdb) p target_bbox.size(), rpn_match.size(), rpn_bbox.size()
# (torch.Size([1, 128, 4]), torch.Size([1, 261888, 1]), torch.Size([1, 261888, 4]))
# Squeeze last dim to simplify
rpn_match = rpn_match.squeeze(2)
# Positive anc... | 256 | 256 | 1,506 | 6 | 249 | blyucs/MaskRCNN | model.py | Python | Classifier | Classifier | 732 | 853 | 732 | 732 | a793663c36bc6d59540a562f3a50633c53d65dec | bigcode/the-stack | train |
fa4ae1e87a5b5635b126e790 | train | function | def mold_image(images, config):
"""Takes RGB images with 0-255 values and subtraces
the mean pixel and converts it to float. Expects image
colors in RGB order."""
return images.astype(np.float32) - config.MEAN_PIXEL
| def mold_image(images, config):
| """Takes RGB images with 0-255 values and subtraces
the mean pixel and converts it to float. Expects image
colors in RGB order."""
return images.astype(np.float32) - config.MEAN_PIXEL
| break
step += 1
self.val_loss_history.append([
loss_sum, loss_rpn_class_sum, loss_rpn_bbox_sum, loss_mrn_class_sum,
loss_mrn_bbox_sum, loss_mrn_mask_sum
])
return loss_sum
def mold_image(images, config):
| 64 | 64 | 58 | 7 | 56 | blyucs/MaskRCNN | model.py | Python | mold_image | mold_image | 1,758 | 1,762 | 1,758 | 1,758 | 78787a05f9b750f86e074d541a7279b6e8b9f2dc | bigcode/the-stack | train |
545254bd07fd6ffa7c021c2c | train | function | def intersect1d(tensor1, tensor2):
"""Intersect 1D set."""
x = torch.LongTensor(list(set(tensor1.tolist()) & set(tensor2.tolist())))
if tensor1.is_cuda:
x = x.cuda()
return x
| def intersect1d(tensor1, tensor2):
| """Intersect 1D set."""
x = torch.LongTensor(list(set(tensor1.tolist()) & set(tensor2.tolist())))
if tensor1.is_cuda:
x = x.cuda()
return x
| * (length - filled_length)
print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end='\n')
# Print New Line on Complete
if loc == total:
print()
def intersect1d(tensor1, tensor2):
| 64 | 64 | 56 | 11 | 53 | blyucs/MaskRCNN | model.py | Python | intersect1d | intersect1d | 56 | 61 | 56 | 56 | 170fa9c0491bd7d0b01bb21d150c8830b98ea3aa | bigcode/the-stack | train |
cff6d796d5345a42489c4123 | train | function | def mrn_samples(rpn_rois, gt_class_ids, gt_boxes, gt_masks, config):
"""Subsample rpn_rois and generates target box deltas, class_ids, and masks for each.
Inputs:
rpn_rois: [batch, N, (y1, x1, y2, x2)] in normalized coordinates. Might
be zero padded if there are not enough rpn_rois.
gt_c... | def mrn_samples(rpn_rois, gt_class_ids, gt_boxes, gt_masks, config):
| """Subsample rpn_rois and generates target box deltas, class_ids, and masks for each.
Inputs:
rpn_rois: [batch, N, (y1, x1, y2, x2)] in normalized coordinates. Might
be zero padded if there are not enough rpn_rois.
gt_class_ids: [batch, MAX_GT_INSTANCES] Integer class IDs.
gt_boxes: ... | in tf.crop_and_resize()
# Result: [batch * num_boxes, pool_height, pool_width, channels]
ind = torch.zeros(level_boxes.size(0)).int()
if level_boxes.is_cuda:
ind = ind.cuda()
feature_maps[i] = feature_maps[i].unsqueeze(0)
pooled_features = maskrcnn.CropFunction(pool_... | 256 | 256 | 1,931 | 21 | 234 | blyucs/MaskRCNN | model.py | Python | mrn_samples | mrn_samples | 404 | 584 | 404 | 404 | cf1cc3e31616c1fb76184f29aa664351f08f3523 | bigcode/the-stack | train |
03dc4781307797991fbd4080 | train | class | class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride)
self.bn1 = nn.BatchNorm2d(planes, eps=0.001, momentum=0.01)
self.... | class Bottleneck(nn.Module):
| expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride)
self.bn1 = nn.BatchNorm2d(planes, eps=0.001, momentum=0.01)
self.padding2 = SamePad2d(kernel_s... | 256]), torch.Size([1, 256, 128, 128]), torch.Size([1, 256, 64, 64]),
# torch.Size([1, 256, 32, 32]), torch.Size([1, 256, 16, 16]))
return [p2_out, p3_out, p4_out, p5_out, p6_out]
############################################################
# Resnet Graph
############################################... | 102 | 102 | 342 | 6 | 95 | blyucs/MaskRCNN | model.py | Python | Bottleneck | Bottleneck | 182 | 219 | 182 | 182 | 7a0bddd3885ac05f4c0c1efcad9e39b8cb9fd97c | bigcode/the-stack | train |
044403034f48092e63c24057 | train | class | class ResNet(nn.Module):
def __init__(self, architecture, stage5=False):
super(ResNet, self).__init__()
assert architecture in ["resnet50", "resnet101"]
self.inplanes = 64
self.layers = [3, 4, {"resnet50": 6, "resnet101": 23}[architecture], 3]
self.block = Bottleneck
... | class ResNet(nn.Module):
| def __init__(self, architecture, stage5=False):
super(ResNet, self).__init__()
assert architecture in ["resnet50", "resnet101"]
self.inplanes = 64
self.layers = [3, 4, {"resnet50": 6, "resnet101": 23}[architecture], 3]
self.block = Bottleneck
self.stage5 = stage5
... | 4, eps=0.001, momentum=0.01)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.padding2(out)
out = ... | 161 | 161 | 539 | 6 | 154 | blyucs/MaskRCNN | model.py | Python | ResNet | ResNet | 222 | 278 | 222 | 222 | 9e1120b89cb85a9499893e809f682e5ddda654d9 | bigcode/the-stack | train |
d11c3e76b4e23c11e4a713a6 | train | class | class LinearLimitCycle(LimitCycleDynamicModel):
''' The Dynamic model is composed of two parts. A limit '''
def __init__(self, dim, device=None, dt = 0.001, requires_grad=True, T_to_stable=1., T_period= 1.):
super().__init__(dim, device, dt, requires_grad)
#### Deterministic Dynamics ####
... | class LinearLimitCycle(LimitCycleDynamicModel):
| ''' The Dynamic model is composed of two parts. A limit '''
def __init__(self, dim, device=None, dt = 0.001, requires_grad=True, T_to_stable=1., T_period= 1.):
super().__init__(dim, device, dt, requires_grad)
#### Deterministic Dynamics ####
self.N_to_stable = int(T_to_stable/dt)
... | import numpy as np
import torch
import torch.nn as nn
from iflow.model.dynamics.generic_dynamic import LimitCycleDynamicModel
from iflow.utils.math import block_diag
class LinearLimitCycle(LimitCycleDynamicModel):
| 47 | 241 | 804 | 10 | 36 | WeitaoZC/iflow | iflow/model/dynamics/linear_limit_cycle.py | Python | LinearLimitCycle | LinearLimitCycle | 10 | 86 | 10 | 10 | da1623e5970e36c1eea19c7d40dda21ca1ebfa88 | bigcode/the-stack | train |
4625bcffa484b447e148e55d | train | class | class Studio(object):
def __init__(self, ip, ignore_warnning=False):
super(Studio, self).__init__()
if not ignore_warnning:
warnings.warn("don't use it for now, just for debugging")
self.__ip = ip
self.__session = Session()
def __del__(self):
self.__session.c... | class Studio(object):
| def __init__(self, ip, ignore_warnning=False):
super(Studio, self).__init__()
if not ignore_warnning:
warnings.warn("don't use it for now, just for debugging")
self.__ip = ip
self.__session = Session()
def __del__(self):
self.__session.close()
def run_bl... | #!/usr/bin/env python3
# Software License Agreement (BSD License)
#
# Copyright (c) 2021, UFACTORY, Inc.
# All rights reserved.
#
# Author: Vinman <vinman.wen@ufactory.cc> <vinman.cub@gmail.com>
import json
import warnings
from ..core.utils.log import logger
from .code import APIState
try:
from requests import Se... | 219 | 231 | 773 | 4 | 214 | DanielWang123321/xArm-Python-SDK | xarm/x3/studio.py | Python | Studio | Studio | 40 | 131 | 40 | 40 | f9d3cb666e45a9ce7b8756109c9be92c758d05ff | bigcode/the-stack | train |
c7ea8442fe4ba823adac3145 | train | function | def test_missing_macro(ckr):
"""Verify correct functioning of MessageId.MISSING_MACRO."""
ckr.enabled([MessageId.MISSING_MACRO])
# This should have a missing macro warning
assert(ckr.check('with %s by' % PROTO).numDiagnostics() == 1)
# These 3 should not have a missing macro warning because of the... | def test_missing_macro(ckr):
| """Verify correct functioning of MessageId.MISSING_MACRO."""
ckr.enabled([MessageId.MISSING_MACRO])
# This should have a missing macro warning
assert(ckr.check('with %s by' % PROTO).numDiagnostics() == 1)
# These 3 should not have a missing macro warning because of their context
# (in a link)
... | join(file_checker.messages[which].message)
def allMessages(file_checker):
"""Return a list of strings, each being the combination of the message lines of a message from a file checker."""
return ['\n'.join(msg.message) for msg in file_checker.messages]
def test_missing_macro(ckr):
| 64 | 64 | 158 | 8 | 56 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | test_missing_macro | test_missing_macro | 95 | 108 | 95 | 95 | 8e92275cac38a8a397f0ca189502ae6d67cccffa | bigcode/the-stack | train |
37ee9545ad407de738314b9e | train | function | def test_REFPAGE_DUPLICATE(ckr):
"""Check the REFPAGE_DUPLICATE message."""
ckr.enabled([MessageId.REFPAGE_DUPLICATE])
# Should not error: no duplicate refpages.
assert(not ckr.check("[open,refpage='abc']").messages)
assert(not ckr.check("[open,refpage='123']").messages)
# Should error: repeate... | def test_REFPAGE_DUPLICATE(ckr):
| """Check the REFPAGE_DUPLICATE message."""
ckr.enabled([MessageId.REFPAGE_DUPLICATE])
# Should not error: no duplicate refpages.
assert(not ckr.check("[open,refpage='abc']").messages)
assert(not ckr.check("[open,refpage='123']").messages)
# Should error: repeated refpage
assert(ckr.check(
... | REFPAGE_WHITESPACE, MessageId.REFPAGE_SELF_XREF])
assert(msgReplacement(
ckr.check("[open,refpage='abc',xrefs=' abc 123 ']"), 1) == 'abc 123')
def test_REFPAGE_DUPLICATE(ckr):
| 64 | 64 | 172 | 12 | 52 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | test_REFPAGE_DUPLICATE | test_REFPAGE_DUPLICATE | 483 | 499 | 483 | 483 | 4f6cceeacdc9f4dd74088eba85bcd9e8dc7edc6e | bigcode/the-stack | train |
3364cd926e19ac69b5e7ea86 | train | function | def test_refpage_block(ckr):
"""Tests of the REFPAGE_BLOCK message."""
ckr.enabled([MessageId.REFPAGE_BLOCK])
# Should not error: have the tag, an open, and a close
assert(not ckr.check(
"""[open,]
--
bla
--""").messages)
assert(not ckr.check(
"""[open,refpage... | def test_refpage_block(ckr):
| """Tests of the REFPAGE_BLOCK message."""
ckr.enabled([MessageId.REFPAGE_BLOCK])
# Should not error: have the tag, an open, and a close
assert(not ckr.check(
"""[open,]
--
bla
--""").messages)
assert(not ckr.check(
"""[open,refpage='abc']
--
bl... | 'abc')
# All should correct to the same thing.
equivalent_tags_with_commas = [
"[open,refpage='',xrefs='abc, 123']",
"[open,refpage='',xrefs='abc,123']",
"[open,refpage='',xrefs='abc , 123']"]
for has_comma in equivalent_tags_with_commas:
assert(loneMsgReplacement(ckr.check... | 109 | 109 | 364 | 9 | 100 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | test_refpage_block | test_refpage_block | 296 | 346 | 296 | 296 | ec6418ac07492ca876e4927c31b63162757bad55 | bigcode/the-stack | train |
bd7c8f4723090369d1e719db | train | function | @pytest.fixture
def ckr(capsys):
"""Fixture - add an arg named ckr to your test function to automatically get one passed to you."""
return CheckerWrapper(capsys)
| @pytest.fixture
def ckr(capsys):
| """Fixture - add an arg named ckr to your test function to automatically get one passed to you."""
return CheckerWrapper(capsys)
| CheckerFile."""
# Flush the captured output.
_ = self.capsys.readouterr()
# Process
f = self.ckr.processString(string + '\n')
# Dump messages
ConsolePrinter().output(f)
return f
@pytest.fixture
def ckr(capsys):
| 64 | 64 | 40 | 10 | 53 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | ckr | ckr | 61 | 64 | 61 | 62 | 3ff0147a9fc633ca77c944c01b88c77f9d6298a1 | bigcode/the-stack | train |
5e263ea86974d81ae0486539 | train | function | def test_should_entity_be_text():
# These 5 are all examples of patterns that would merit usage of a ptext/etext/etc
# macro, for various reasons:
# has variable in subscript
assert(shouldEntityBeText('pBuffers[i]', '[i]'))
assert(shouldEntityBeText('API_ENUM_[X]', '[X]'))
# has asterisk
a... | def test_should_entity_be_text():
# These 5 are all examples of patterns that would merit usage of a ptext/etext/etc
# macro, for various reasons:
# has variable in subscript
| assert(shouldEntityBeText('pBuffers[i]', '[i]'))
assert(shouldEntityBeText('API_ENUM_[X]', '[X]'))
# has asterisk
assert(shouldEntityBeText('maxPerStage*', None))
# double-underscores make italicized placeholders
# (triple are double-underscores delimited by underscores...)
assert(shouldEn... | assert(ckr.check('code:uint32_t').numErrors() == 0)
def test_should_entity_be_text():
# These 5 are all examples of patterns that would merit usage of a ptext/etext/etc
# macro, for various reasons:
# has variable in subscript
| 64 | 64 | 197 | 46 | 18 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | test_should_entity_be_text | test_should_entity_be_text | 133 | 150 | 133 | 137 | d304dd139f32dd0a03d9ea9d5a026ef13737f76e | bigcode/the-stack | train |
09a6d522e431135b605484cc | train | function | def test_wrong_macro(ckr):
ckr.enabled([MessageId.WRONG_MACRO])
# Should error - this ought to be code:uint32_t
assert(ckr.check('basetype:uint32_t').numErrors() == 1)
# This shouldn't error
assert(ckr.check('code:uint32_t').numErrors() == 0)
| def test_wrong_macro(ckr):
| ckr.enabled([MessageId.WRONG_MACRO])
# Should error - this ought to be code:uint32_t
assert(ckr.check('basetype:uint32_t').numErrors() == 1)
# This shouldn't error
assert(ckr.check('code:uint32_t').numErrors() == 0)
| get picked up as
# an asterisk in the entity name (a placeholder).
ckr.enabled(
[MessageId.MISSING_TEXT, MessageId.BAD_ENTITY])
assert(ckr.check('*flink:abcd*').numErrors() == 1)
def test_wrong_macro(ckr):
| 64 | 64 | 79 | 8 | 56 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | test_wrong_macro | test_wrong_macro | 124 | 130 | 124 | 124 | 9e2f79dbf574790f276159bd2b486eb02a6f1e5d | bigcode/the-stack | train |
e5c76df06d26b00cc3aecb29 | train | function | def message(file_checker, which=0):
"""Return a string of the message lines associated with the message of a file checker."""
assert(len(file_checker.messages) > which)
return "\n".join(file_checker.messages[which].message)
| def message(file_checker, which=0):
| """Return a string of the message lines associated with the message of a file checker."""
assert(len(file_checker.messages) > which)
return "\n".join(file_checker.messages[which].message)
| (msg.fix)
return msg.replacement
def loneMsgReplacement(file_checker):
"""Assert there's only one message in a file checker, and return the replacement text associated with it."""
assert(len(file_checker.messages) == 1)
return msgReplacement(file_checker)
def message(file_checker, which=0):
| 64 | 64 | 51 | 9 | 55 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | message | message | 84 | 87 | 84 | 84 | 8712973c8b7e7d1f1244ac87d37a3bde11361f04 | bigcode/the-stack | train |
0ec719e61daeb773df19daae | train | function | def test_entity_detection(ckr):
ckr.enabled([MessageId.BAD_ENTITY])
# Should complain about BAD_ENTITY
assert(ckr.check('flink:abcd').numDiagnostics() == 1)
# Should just give BAD_ENTITY (an error), not MISSING_TEXT (a warning).
# Verifying that wrapping in asterisks (for formatting) doesn't get pi... | def test_entity_detection(ckr):
| ckr.enabled([MessageId.BAD_ENTITY])
# Should complain about BAD_ENTITY
assert(ckr.check('flink:abcd').numDiagnostics() == 1)
# Should just give BAD_ENTITY (an error), not MISSING_TEXT (a warning).
# Verifying that wrapping in asterisks (for formatting) doesn't get picked up as
# an asterisk in ... | PROTO).messages)
# These 2 are simulating links that broke over lines
assert(not ckr.check('%s>>' % PROTO).messages)
assert(not ckr.check(
'%s asdf>> table' % PROTO).messages)
def test_entity_detection(ckr):
| 64 | 64 | 136 | 8 | 56 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | test_entity_detection | test_entity_detection | 111 | 121 | 111 | 111 | 93aba12ef8fe417101acb8fdcfc7f1c1017f3c5b | bigcode/the-stack | train |
4e84e0e62bf6cd97355a4f11 | train | function | def msgReplacement(file_checker, which=0):
"""Return the replacement text associated with the specified message."""
assert(len(file_checker.messages) > which)
msg = file_checker.messages[which]
from pprint import pprint
pprint(msg.script_location)
pprint(msg.replacement)
pprint(msg.fix)
... | def msgReplacement(file_checker, which=0):
| """Return the replacement text associated with the specified message."""
assert(len(file_checker.messages) > which)
msg = file_checker.messages[which]
from pprint import pprint
pprint(msg.script_location)
pprint(msg.replacement)
pprint(msg.fix)
return msg.replacement
| Dump messages
ConsolePrinter().output(f)
return f
@pytest.fixture
def ckr(capsys):
"""Fixture - add an arg named ckr to your test function to automatically get one passed to you."""
return CheckerWrapper(capsys)
def msgReplacement(file_checker, which=0):
| 64 | 64 | 70 | 10 | 54 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | msgReplacement | msgReplacement | 67 | 75 | 67 | 67 | c4429a3866b8e71444a5b049c587e638c9b6ec12 | bigcode/the-stack | train |
6e31ef92bc63230f4542fbfc | train | function | def test_refpage_name(ckr):
ckr.enabled([MessageId.REFPAGE_NAME])
# Should not error: actually exists.
assert(ckr.check(
"[open,refpage='%s',desc='',type='']" % PROTO).numDiagnostics() == 0)
# Should error: does not exist.
assert(
ckr.check("[open,refpage='bogus',desc='',type='']").... | def test_refpage_name(ckr):
| ckr.enabled([MessageId.REFPAGE_NAME])
# Should not error: actually exists.
assert(ckr.check(
"[open,refpage='%s',desc='',type='']" % PROTO).numDiagnostics() == 0)
# Should error: does not exist.
assert(
ckr.check("[open,refpage='bogus',desc='',type='']").numDiagnostics() == 1)
| type='']").messages)
# Should error, due to missing refpage, but not crash due to message printing (note the unicode smart quote)
assert(ckr.check("[open,desc='',type='',xrefs=’']").numDiagnostics() == 1)
def test_refpage_name(ckr):
| 64 | 64 | 100 | 9 | 55 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | test_refpage_name | test_refpage_name | 228 | 236 | 228 | 228 | 6ac6bfab57454be2467a50d35ebf82cff272ba74 | bigcode/the-stack | train |
0bee5082f88f00a9c09d8411 | train | class | class CheckerWrapper(object):
"""Little wrapper object for a MacroChecker.
Intended for use in making test assertions shorter and easier to read."""
def __init__(self, capsys):
self.ckr = makeMacroChecker(set())
self.capsys = capsys
def enabled(self, enabled_messages):
"""Upda... | class CheckerWrapper(object):
| """Little wrapper object for a MacroChecker.
Intended for use in making test assertions shorter and easier to read."""
def __init__(self, capsys):
self.ckr = makeMacroChecker(set())
self.capsys = capsys
def enabled(self, enabled_messages):
"""Updates the checker's enable messa... | , makeMacroChecker
from spec_tools.console_printer import ConsolePrinter
from spec_tools.macro_checker_file import shouldEntityBeText
# API-specific constants
PROTO = 'xrCreateInstance'
STRUCT = 'XrInstanceCreateInfo'
EXT = 'XR_KHR_opengl_enable'
class CheckerWrapper(object):
| 64 | 64 | 181 | 5 | 59 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | CheckerWrapper | CheckerWrapper | 33 | 58 | 33 | 33 | 57d9d48a6dfa07aa49e40c170f98ec88828b076e | bigcode/the-stack | train |
e3b523b3c1f450210d9ab25a | train | function | def test_REFPAGE_WHITESPACE(ckr):
"""Check the REFPAGE_WHITESPACE message."""
ckr.enabled([MessageId.REFPAGE_WHITESPACE])
# Should not error: no extra whitespace
assert(not ckr.check("[open,xrefs='']").messages)
assert(not ckr.check("[open,xrefs='123']").messages)
assert(not ckr.check("[open,xre... | def test_REFPAGE_WHITESPACE(ckr):
| """Check the REFPAGE_WHITESPACE message."""
ckr.enabled([MessageId.REFPAGE_WHITESPACE])
# Should not error: no extra whitespace
assert(not ckr.check("[open,xrefs='']").messages)
assert(not ckr.check("[open,xrefs='123']").messages)
assert(not ckr.check("[open,xrefs='abc 123']").messages)
# S... | abc')
assert(loneMsgReplacement(
ckr.check("[open,xrefs='abc abc abc']")) == 'abc')
assert(loneMsgReplacement(
ckr.check("[open,xrefs='abc 123 abc']")) == 'abc 123')
assert(loneMsgReplacement(
ckr.check("[open,xrefs='123 abc abc']")) == '123 abc')
def test_REFPAGE_WHITESPACE(ckr):
| 93 | 93 | 312 | 12 | 81 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | test_REFPAGE_WHITESPACE | test_REFPAGE_WHITESPACE | 457 | 480 | 457 | 457 | 175d5996477339e452deaab0aa8a78be2bc814bd | bigcode/the-stack | train |
16db46fd8d732260767f61d6 | train | function | def test_refpage_missing_desc(ckr):
ckr.enabled([MessageId.REFPAGE_MISSING_DESC])
# Should not warn: non-empty description actually exists.
assert(ckr.check(
"[open,refpage='',desc='non-empty description',type='']").numDiagnostics() == 0)
# Should warn: desc field is empty.
assert(
... | def test_refpage_missing_desc(ckr):
| ckr.enabled([MessageId.REFPAGE_MISSING_DESC])
# Should not warn: non-empty description actually exists.
assert(ckr.check(
"[open,refpage='',desc='non-empty description',type='']").numDiagnostics() == 0)
# Should warn: desc field is empty.
assert(
ckr.check("[open,refpage='',desc='',... | desc='',type='']" % PROTO).numDiagnostics() == 0)
# Should error: does not exist.
assert(
ckr.check("[open,refpage='bogus',desc='',type='']").numDiagnostics() == 1)
def test_refpage_missing_desc(ckr):
| 64 | 64 | 101 | 10 | 54 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | test_refpage_missing_desc | test_refpage_missing_desc | 239 | 247 | 239 | 239 | d5d25f2d53ea92552c4917a1e37ca6f258fe4204 | bigcode/the-stack | train |
30c1b0f1af62eb25420fadd4 | train | function | def test_refpage_unknown_attrib(ckr):
"""Check the REFPAGE_UNKNOWN_ATTRIB message."""
ckr.enabled([MessageId.REFPAGE_UNKNOWN_ATTRIB])
# Should not error: these are known attribute names
assert(not ckr.check(
"[open,refpage='',desc='',type='',xrefs='']").messages)
# Should error: xref isn't ... | def test_refpage_unknown_attrib(ckr):
| """Check the REFPAGE_UNKNOWN_ATTRIB message."""
ckr.enabled([MessageId.REFPAGE_UNKNOWN_ATTRIB])
# Should not error: these are known attribute names
assert(not ckr.check(
"[open,refpage='',desc='',type='',xrefs='']").messages)
# Should error: xref isn't an attribute name.
assert(ckr.chec... | () == 1)
assert(ckr.check(
"""[open,refpage='%s']
--
include::../../generated/validity/structs/%s.txt[]""" % (PROTO, STRUCT)).numDiagnostics() == 1)
def test_refpage_unknown_attrib(ckr):
| 64 | 64 | 106 | 11 | 53 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | test_refpage_unknown_attrib | test_refpage_unknown_attrib | 406 | 415 | 406 | 406 | ae7c2c4bd45f53f7ddc167b78c477f2d10a1fd28 | bigcode/the-stack | train |
6d66b9477bdf2bd3c09e500d | train | function | def test_refpage_xrefs_comma(ckr):
ckr.enabled([MessageId.REFPAGE_XREFS_COMMA])
# Should not error: no commas in the xrefs field
assert(not ckr.check(
"[open,refpage='',xrefs='abc']").messages)
# Should error: commas shouldn't be there since it's space-delimited.
assert(loneMsgReplacement(
... | def test_refpage_xrefs_comma(ckr):
| ckr.enabled([MessageId.REFPAGE_XREFS_COMMA])
# Should not error: no commas in the xrefs field
assert(not ckr.check(
"[open,refpage='',xrefs='abc']").messages)
# Should error: commas shouldn't be there since it's space-delimited.
assert(loneMsgReplacement(
ckr.check("[open,refpage=''... | % STRUCT.lower()))
== STRUCT)
# Should error: not a valid entity.
assert(ckr.check(
"[open,refpage='',desc='',type='protos',xrefs='bogus']").numDiagnostics() == 1)
def test_refpage_xrefs_comma(ckr):
| 64 | 64 | 203 | 12 | 52 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | test_refpage_xrefs_comma | test_refpage_xrefs_comma | 277 | 293 | 277 | 277 | b27bc711b637d6fc1f046296917478fd3d9acb8b | bigcode/the-stack | train |
0084301a86b6f9be13e3482b | train | function | def test_refpage_type(ckr):
ckr.enabled([MessageId.REFPAGE_TYPE])
# Should not error: this is of type 'protos'.
assert(not ckr.check(
"[open,refpage='%s',desc='',type='protos']" % PROTO).messages)
# Should error: this is of type 'protos', not 'structs'.
assert(
ckr.check("[open,refp... | def test_refpage_type(ckr):
| ckr.enabled([MessageId.REFPAGE_TYPE])
# Should not error: this is of type 'protos'.
assert(not ckr.check(
"[open,refpage='%s',desc='',type='protos']" % PROTO).messages)
# Should error: this is of type 'protos', not 'structs'.
assert(
ckr.check("[open,refpage='%s',desc='',type='struc... | ,refpage='',desc='non-empty description',type='']").numDiagnostics() == 0)
# Should warn: desc field is empty.
assert(
ckr.check("[open,refpage='',desc='',type='']").numDiagnostics() == 1)
def test_refpage_type(ckr):
| 64 | 64 | 112 | 9 | 55 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | test_refpage_type | test_refpage_type | 250 | 258 | 250 | 250 | d06b30309ed3e5d1635adc36b45588717a8efe75 | bigcode/the-stack | train |
9440dcc3b7cada1ff48b6750 | train | function | def test_refpage_self_xref(ckr):
"""Check the REFPAGE_SELF_XREF message."""
ckr.enabled([MessageId.REFPAGE_SELF_XREF])
# Should not error: not self-referencing
assert(not ckr.check(
"[open,refpage='abc',xrefs='']").messages)
assert(not ckr.check(
"[open,refpage='abc',xrefs='123']").m... | def test_refpage_self_xref(ckr):
| """Check the REFPAGE_SELF_XREF message."""
ckr.enabled([MessageId.REFPAGE_SELF_XREF])
# Should not error: not self-referencing
assert(not ckr.check(
"[open,refpage='abc',xrefs='']").messages)
assert(not ckr.check(
"[open,refpage='abc',xrefs='123']").messages)
# Should error: sel... | kr.check(
"[open,refpage='',desc='',type='',xrefs='']").messages)
# Should error: xref isn't an attribute name.
assert(ckr.check(
"[open,xref='']").numDiagnostics() == 1)
def test_refpage_self_xref(ckr):
| 64 | 64 | 194 | 11 | 53 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | test_refpage_self_xref | test_refpage_self_xref | 418 | 433 | 418 | 418 | cf224c383b28531a2c83ad9f48a3e22cdd8e4a72 | bigcode/the-stack | train |
86518cbda4b48645adb205e6 | train | function | def test_refpage_tag(ckr):
ckr.enabled([MessageId.REFPAGE_TAG])
# Should error: missing refpage='' field
assert(ckr.check("[open,desc='',type='',xrefs='']").numErrors() == 1)
# Should error: missing desc='' field
assert(ckr.check("[open,refpage='',type='',xrefs='']").numErrors() == 1)
# Should ... | def test_refpage_tag(ckr):
| ckr.enabled([MessageId.REFPAGE_TAG])
# Should error: missing refpage='' field
assert(ckr.check("[open,desc='',type='',xrefs='']").numErrors() == 1)
# Should error: missing desc='' field
assert(ckr.check("[open,refpage='',type='',xrefs='']").numErrors() == 1)
# Should error: missing type='' fiel... | ' % EXT).messages)
# TODO can we auto-correct this to add the backticks?
# Doesn't error now, but would be nice if it did...
assert(not ckr.check('asdf <<%s>> asdf' % EXT).messages)
def test_refpage_tag(ckr):
| 64 | 64 | 208 | 9 | 55 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | test_refpage_tag | test_refpage_tag | 211 | 225 | 211 | 211 | ef55a0e885b2c26b4d1171f9c4de8e74df9994ee | bigcode/the-stack | train |
f22763403c4737dec937171a | train | function | def test_refpage_xrefs(ckr):
ckr.enabled([MessageId.REFPAGE_XREFS])
# Should not error: this is a valid entity to have an xref to.
assert(not ckr.check(
"[open,refpage='',desc='',type='protos',xrefs='%s']" % STRUCT).messages)
# case difference:
# should error but offer a replacement.
as... | def test_refpage_xrefs(ckr):
| ckr.enabled([MessageId.REFPAGE_XREFS])
# Should not error: this is a valid entity to have an xref to.
assert(not ckr.check(
"[open,refpage='',desc='',type='protos',xrefs='%s']" % STRUCT).messages)
# case difference:
# should error but offer a replacement.
assert(loneMsgReplacement(ckr.c... | " % PROTO).messages)
# Should error: this is of type 'protos', not 'structs'.
assert(
ckr.check("[open,refpage='%s',desc='',type='structs']" % PROTO).messages)
def test_refpage_xrefs(ckr):
| 64 | 64 | 162 | 10 | 54 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | test_refpage_xrefs | test_refpage_xrefs | 261 | 274 | 261 | 261 | b77622bb026ad520d13788f4fd453032672b8883 | bigcode/the-stack | train |
cee27615fc1ce8b08fb41db8 | train | function | def test_refpage_xref_dupe(ckr):
"""Check the REFPAGE_XREF_DUPE message."""
ckr.enabled([MessageId.REFPAGE_XREF_DUPE])
# Should not error: no dupes
assert(not ckr.check("[open,xrefs='']").messages)
assert(not ckr.check("[open,xrefs='123']").messages)
assert(not ckr.check("[open,xrefs='abc 123']"... | def test_refpage_xref_dupe(ckr):
| """Check the REFPAGE_XREF_DUPE message."""
ckr.enabled([MessageId.REFPAGE_XREF_DUPE])
# Should not error: no dupes
assert(not ckr.check("[open,xrefs='']").messages)
assert(not ckr.check("[open,xrefs='123']").messages)
assert(not ckr.check("[open,xrefs='abc 123']").messages)
# Should error: ... | oneMsgReplacement(
ckr.check("[open,refpage='abc',xrefs='abc 123']")) == '123')
assert(loneMsgReplacement(
ckr.check("[open,refpage='abc',xrefs='123 abc']")) == '123')
def test_refpage_xref_dupe(ckr):
| 70 | 70 | 235 | 12 | 58 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | test_refpage_xref_dupe | test_refpage_xref_dupe | 436 | 454 | 436 | 436 | 6c39e447d674c8f8eef4d9c8bc7eb782936895f2 | bigcode/the-stack | train |
29324b1af52172711d609101 | train | function | def test_refpage_mismatch(ckr):
"""Test the REFPAGE_MISMATCH message."""
ckr.enabled([MessageId.REFPAGE_MISMATCH])
# Should not error: have the tag, an open, and a matching include
assert(not ckr.check(
"""[open,refpage='%s']
--
include::../../generated/api/protos/%s.txt[]""" % (... | def test_refpage_mismatch(ckr):
| """Test the REFPAGE_MISMATCH message."""
ckr.enabled([MessageId.REFPAGE_MISMATCH])
# Should not error: have the tag, an open, and a matching include
assert(not ckr.check(
"""[open,refpage='%s']
--
include::../../generated/api/protos/%s.txt[]""" % (PROTO, PROTO)).messages)
ass... | --""" % (PROTO, PROTO)).numDiagnostics() == 1)
assert(ckr.check(
"""include::../../generated/validity/protos/%s.txt[]
[open,refpage='%s']
--""" % (PROTO, PROTO)).numDiagnostics() == 1)
def test_refpage_mismatch(ckr):
| 75 | 75 | 251 | 10 | 65 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | test_refpage_mismatch | test_refpage_mismatch | 382 | 403 | 382 | 382 | f77218ff153df13cc0c39ed7252502132efd53cf | bigcode/the-stack | train |
29ff537a480fa22b34d279a3 | train | function | def test_extension(ckr):
ckr.enabled(set(MessageId))
# Check formatting of extension names:
# the following is the canonical way to refer to an extension
# (link wrapped in backticks)
expected_replacement = '`<<%s>>`' % EXT
# Extension name mentioned without any markup, should be added
asse... | def test_extension(ckr):
| ckr.enabled(set(MessageId))
# Check formatting of extension names:
# the following is the canonical way to refer to an extension
# (link wrapped in backticks)
expected_replacement = '`<<%s>>`' % EXT
# Extension name mentioned without any markup, should be added
assert(loneMsgReplacement(ckr... | assert(ckr.check('etext:API_ENUM[i]').numDiagnostics() == 0)
assert(ckr.check('etext:API_ENUM[__x__]').numDiagnostics() == 0)
# Should be OK, since __i__ is a placeholder here
assert(ckr.check('etext:API_ENUM___i___EXT').numDiagnostics() == 0)
# This shouldn't be a *text: macro because it only has si... | 126 | 126 | 423 | 7 | 119 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | test_extension | test_extension | 170 | 208 | 170 | 170 | 2ea98796011e9427bf7a809b3d90feb1e169a053 | bigcode/the-stack | train |
033e33658b080d495ac1b2c0 | train | function | def test_UNCLOSED_BLOCK(ckr):
"""Check the UNCLOSED_BLOCK message."""
ckr.enabled([MessageId.UNCLOSED_BLOCK])
# These should all have 0 errors
assert(not ckr.check("== Heading").messages)
assert(not ckr.check(
"""****
== Heading
****""").messages)
assert(not ckr.check(
... | def test_UNCLOSED_BLOCK(ckr):
| """Check the UNCLOSED_BLOCK message."""
ckr.enabled([MessageId.UNCLOSED_BLOCK])
# These should all have 0 errors
assert(not ckr.check("== Heading").messages)
assert(not ckr.check(
"""****
== Heading
****""").messages)
assert(not ckr.check(
"""****
contents... | _XREF])
assert(msgReplacement(
ckr.check("[open,refpage='abc',xrefs=' abc 123 ']"), 1) == 'abc 123')
def test_REFPAGE_DUPLICATE(ckr):
"""Check the REFPAGE_DUPLICATE message."""
ckr.enabled([MessageId.REFPAGE_DUPLICATE])
# Should not error: no duplicate refpages.
assert(not ckr.check("[... | 222 | 222 | 740 | 10 | 212 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | test_UNCLOSED_BLOCK | test_UNCLOSED_BLOCK | 502 | 631 | 502 | 502 | 89b63832edfcf87938ca4c911887eff20a67bda1 | bigcode/the-stack | train |
4ab6e18be609c1457f92f77c | train | function | def allMessages(file_checker):
"""Return a list of strings, each being the combination of the message lines of a message from a file checker."""
return ['\n'.join(msg.message) for msg in file_checker.messages]
| def allMessages(file_checker):
| """Return a list of strings, each being the combination of the message lines of a message from a file checker."""
return ['\n'.join(msg.message) for msg in file_checker.messages]
| return msgReplacement(file_checker)
def message(file_checker, which=0):
"""Return a string of the message lines associated with the message of a file checker."""
assert(len(file_checker.messages) > which)
return "\n".join(file_checker.messages[which].message)
def allMessages(file_checker):
| 64 | 64 | 47 | 6 | 58 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | allMessages | allMessages | 90 | 92 | 90 | 90 | b5f3d866ccc82c0736834484f8db103b75cb2034 | bigcode/the-stack | train |
b5795ea4f482fe9520c0a5a9 | train | function | def loneMsgReplacement(file_checker):
"""Assert there's only one message in a file checker, and return the replacement text associated with it."""
assert(len(file_checker.messages) == 1)
return msgReplacement(file_checker)
| def loneMsgReplacement(file_checker):
| """Assert there's only one message in a file checker, and return the replacement text associated with it."""
assert(len(file_checker.messages) == 1)
return msgReplacement(file_checker)
| the replacement text associated with the specified message."""
assert(len(file_checker.messages) > which)
msg = file_checker.messages[which]
from pprint import pprint
pprint(msg.script_location)
pprint(msg.replacement)
pprint(msg.fix)
return msg.replacement
def loneMsgReplacement(file_check... | 64 | 64 | 46 | 7 | 56 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | loneMsgReplacement | loneMsgReplacement | 78 | 81 | 78 | 78 | 6effc7322a1b3154b1b255b44caba4866737840f | bigcode/the-stack | train |
b913f8204c01948647f96f9c | train | function | def test_code_block_tracking(ckr):
"""Check to make sure that no other messages get triggered in a code block."""
ckr.enabled([MessageId.BAD_ENTITY])
# Should have 1 error: not a valid entity
assert(ckr.check("slink:BogusStruct").numDiagnostics() == 1)
assert(ckr.check(
"""****
* sl... | def test_code_block_tracking(ckr):
| """Check to make sure that no other messages get triggered in a code block."""
ckr.enabled([MessageId.BAD_ENTITY])
# Should have 1 error: not a valid entity
assert(ckr.check("slink:BogusStruct").numDiagnostics() == 1)
assert(ckr.check(
"""****
* slink:BogusStruct
****""").nu... | open,]
== Heading
--""").messages)
# Should have 1 error: block left open at end of file
assert(ckr.check(
"""[open,]
--
bla""").numDiagnostics() == 1)
def test_code_block_tracking(ckr):
| 64 | 64 | 199 | 9 | 55 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | test_code_block_tracking | test_code_block_tracking | 634 | 653 | 634 | 634 | a588c8869627ec8d35d152c3e1f0dc124bfaef6c | bigcode/the-stack | train |
47118d62113c935fd884098a | train | function | def test_refpage_missing(ckr):
"""Test the REFPAGE_MISSING message."""
ckr.enabled([MessageId.REFPAGE_MISSING])
# Should not error: have the tag, an open, and the include
assert(not ckr.check(
"""[open,refpage='%s']
--
include::../../generated/api/protos/%s.txt[]""" % (PROTO, PRO... | def test_refpage_missing(ckr):
| """Test the REFPAGE_MISSING message."""
ckr.enabled([MessageId.REFPAGE_MISSING])
# Should not error: have the tag, an open, and the include
assert(not ckr.check(
"""[open,refpage='%s']
--
include::../../generated/api/protos/%s.txt[]""" % (PROTO, PROTO)).messages)
assert(not c... |
this is in a code block
----
--""").numDiagnostics() == 1)
# Should have 1 error: tag inside refpage.
tag_inside = """[open,]
--
bla
[open,]
--"""
assert(ckr.check(tag_inside).numDiagnostics() == 1)
assert("already in a refpage block" in
... | 104 | 105 | 351 | 9 | 95 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | test_refpage_missing | test_refpage_missing | 349 | 379 | 349 | 349 | b696577c5ada9ab128399b4043bedbf102a48f7b | bigcode/the-stack | train |
2893a68e09e557489e98758e | train | function | def test_misused_text(ckr):
# Tests the same patterns as test_should_entity_be_text(),
# but in a whole checker
ckr.enabled([MessageId.MISUSED_TEXT])
assert(ckr.check('etext:API_ENUM_').numDiagnostics() == 0)
assert(ckr.check('etext:API_ENUM_[X]').numDiagnostics() == 0)
assert(ckr.check('etext:... | def test_misused_text(ckr):
# Tests the same patterns as test_should_entity_be_text(),
# but in a whole checker
| ckr.enabled([MessageId.MISUSED_TEXT])
assert(ckr.check('etext:API_ENUM_').numDiagnostics() == 0)
assert(ckr.check('etext:API_ENUM_[X]').numDiagnostics() == 0)
assert(ckr.check('etext:API_ENUM[i]').numDiagnostics() == 0)
assert(ckr.check('etext:API_ENUM[__x__]').numDiagnostics() == 0)
# Should ... | # This shouldn't be a *text: macro because it only has single underscores
assert(False == shouldEntityBeText('API_ENUM_i_EXT', None))
def test_misused_text(ckr):
# Tests the same patterns as test_should_entity_be_text(),
# but in a whole checker
| 64 | 64 | 206 | 31 | 33 | emersion/OpenXR-SDK-Source | specification/scripts/test_check_spec_links.py | Python | test_misused_text | test_misused_text | 153 | 167 | 153 | 155 | f3b917db5c4da8421ffb0504bce347d524805c73 | bigcode/the-stack | train |
f7515cc9883f44307f28345d | train | class | class TestSimple(unittest.TestCase):
def setUp(self):
self.inputdocs = glob.glob(os.path.join(stubdata_dir, 'parsed/*.json'))
# sys.stderr.write("test cases are: {}\n".format(self.inputdocs))
def test_simple_schema(self):
validator = validators.ads.SimpleValidator()
for file in ... | class TestSimple(unittest.TestCase):
| def setUp(self):
self.inputdocs = glob.glob(os.path.join(stubdata_dir, 'parsed/*.json'))
# sys.stderr.write("test cases are: {}\n".format(self.inputdocs))
def test_simple_schema(self):
validator = validators.ads.SimpleValidator()
for file in self.inputdocs:
# this wil... | """
Test parsers
"""
import unittest
import sys, os
import glob
import json
import validators.ads
stubdata_dir = os.path.join(os.path.dirname(__file__), 'stubdata')
class TestSimple(unittest.TestCase):
| 48 | 64 | 126 | 7 | 41 | aaccomazzi/adsabs-pyingest | test/test_validators.py | Python | TestSimple | TestSimple | 13 | 26 | 13 | 14 | 996c2e11a1914cef50c8d191bda157a95978be63 | bigcode/the-stack | train |
951605d008f2b7786502dc3d | train | function | def __gather_tex_coord(blender_shader_sockets_or_texture_slots, export_settings):
if __is_socket(blender_shader_sockets_or_texture_slots):
blender_shader_node = __get_tex_from_socket(blender_shader_sockets_or_texture_slots[0]).shader_node
if len(blender_shader_node.inputs['Vector'].links) == 0:
... | def __gather_tex_coord(blender_shader_sockets_or_texture_slots, export_settings):
| if __is_socket(blender_shader_sockets_or_texture_slots):
blender_shader_node = __get_tex_from_socket(blender_shader_sockets_or_texture_slots[0]).shader_node
if len(blender_shader_node.inputs['Vector'].links) == 0:
return 0
input_node = blender_shader_node.inputs['Vector'].links[... | _slots, export_settings):
return None
def __gather_index(blender_shader_sockets_or_texture_slots, export_settings):
# We just put the actual shader into the 'index' member
return gltf2_blender_gather_texture.gather_texture(blender_shader_sockets_or_texture_slots, export_settings)
def __gather_tex_coord(bl... | 84 | 84 | 280 | 18 | 66 | Cyp/glTF-Blender-IO | addons/io_scene_gltf2/blender/exp/gltf2_blender_gather_material_normal_texture_info_class.py | Python | __gather_tex_coord | __gather_tex_coord | 88 | 120 | 88 | 88 | 108a78861f83cf3f9408709752835fbdc406674e | bigcode/the-stack | train |
020f8d085008f833b6098fd1 | train | function | def __gather_index(blender_shader_sockets_or_texture_slots, export_settings):
# We just put the actual shader into the 'index' member
return gltf2_blender_gather_texture.gather_texture(blender_shader_sockets_or_texture_slots, export_settings)
| def __gather_index(blender_shader_sockets_or_texture_slots, export_settings):
# We just put the actual shader into the 'index' member
| return gltf2_blender_gather_texture.gather_texture(blender_shader_sockets_or_texture_slots, export_settings)
| _or_texture_slots, export_settings):
return None
def __gather_scale(blender_shader_sockets_or_texture_slots, export_settings):
return None
def __gather_index(blender_shader_sockets_or_texture_slots, export_settings):
# We just put the actual shader into the 'index' member
| 64 | 64 | 57 | 32 | 31 | Cyp/glTF-Blender-IO | addons/io_scene_gltf2/blender/exp/gltf2_blender_gather_material_normal_texture_info_class.py | Python | __gather_index | __gather_index | 83 | 85 | 83 | 84 | 9020391711a7cdc952fb298892a23e485a590220 | bigcode/the-stack | train |
d04b3180ea1ab67dbf9e85d8 | train | function | def __gather_extras(blender_shader_sockets_or_texture_slots, export_settings):
return None
| def __gather_extras(blender_shader_sockets_or_texture_slots, export_settings):
| return None
| [0].from_node
texture_transform = gltf2_blender_get.get_texture_transform_from_texture_node(texture_node)
extension = Extension("KHR_texture_transform", texture_transform)
return {"KHR_texture_transform": extension}
def __gather_extras(blender_shader_sockets_or_texture_slots, export_settings):
| 64 | 64 | 22 | 18 | 46 | Cyp/glTF-Blender-IO | addons/io_scene_gltf2/blender/exp/gltf2_blender_gather_material_normal_texture_info_class.py | Python | __gather_extras | __gather_extras | 75 | 76 | 75 | 75 | b53f75af9cb31618230b3502ceac7de0770d3ce7 | bigcode/the-stack | train |
1b4626f863b09efc232bf365 | train | function | def __get_tex_from_socket(socket):
result = gltf2_blender_search_node_tree.from_socket(
socket,
gltf2_blender_search_node_tree.FilterByType(bpy.types.ShaderNodeTexImage))
if not result:
return None
return result[0]
| def __get_tex_from_socket(socket):
| result = gltf2_blender_search_node_tree.from_socket(
socket,
gltf2_blender_search_node_tree.FilterByType(bpy.types.ShaderNodeTexImage))
if not result:
return None
return result[0]
| uv_map)
if texCoordIndex >= 0:
return texCoordIndex
return 0
else:
raise NotImplementedError()
def __is_socket(sockets_or_slots):
return isinstance(sockets_or_slots[0], bpy.types.NodeSocket)
def __get_tex_from_socket(socket):
| 64 | 64 | 61 | 8 | 56 | Cyp/glTF-Blender-IO | addons/io_scene_gltf2/blender/exp/gltf2_blender_gather_material_normal_texture_info_class.py | Python | __get_tex_from_socket | __get_tex_from_socket | 127 | 133 | 127 | 127 | 6faec33daaf668dbcf2d8c2e853595c6bcf7342c | bigcode/the-stack | train |
8bdedb6310903a01dfbc6d83 | train | function | def __filter_texture_info(blender_shader_sockets_or_texture_slots, export_settings):
if not blender_shader_sockets_or_texture_slots:
return False
if not all([elem is not None for elem in blender_shader_sockets_or_texture_slots]):
return False
if isinstance(blender_shader_sockets_or_texture_s... | def __filter_texture_info(blender_shader_sockets_or_texture_slots, export_settings):
| if not blender_shader_sockets_or_texture_slots:
return False
if not all([elem is not None for elem in blender_shader_sockets_or_texture_slots]):
return False
if isinstance(blender_shader_sockets_or_texture_slots[0], bpy.types.NodeSocket):
if any([__get_tex_from_socket(socket) is None... | index=__gather_index(blender_shader_sockets_or_texture_slots, export_settings),
tex_coord=__gather_tex_coord(blender_shader_sockets_or_texture_slots, export_settings)
)
return texture_info
def __filter_texture_info(blender_shader_sockets_or_texture_slots, export_settings):
| 64 | 64 | 119 | 17 | 46 | Cyp/glTF-Blender-IO | addons/io_scene_gltf2/blender/exp/gltf2_blender_gather_material_normal_texture_info_class.py | Python | __filter_texture_info | __filter_texture_info | 44 | 53 | 44 | 44 | f57138803936a922329e079458ffb7b7bcf31d4b | bigcode/the-stack | train |
c38fb3dcf58605269366d9b3 | train | function | @cached
def gather_material_normal_texture_info_class(blender_shader_sockets_or_texture_slots: typing.Union[
typing.Tuple[bpy.types.NodeSocket], typing.Tuple[bpy.types.Texture]],
export_settings):
if not __filter_texture_info(blender_shader_sockets_or_texture_slots, export_settings):
return None... | @cached
def gather_material_normal_texture_info_class(blender_shader_sockets_or_texture_slots: typing.Union[
typing.Tuple[bpy.types.NodeSocket], typing.Tuple[bpy.types.Texture]],
export_settings):
| if not __filter_texture_info(blender_shader_sockets_or_texture_slots, export_settings):
return None
texture_info = gltf2_io.MaterialNormalTextureInfoClass(
extensions=__gather_extensions(blender_shader_sockets_or_texture_slots, export_settings),
extras=__gather_extras(blender_shader_soc... | 2_blender_get
from io_scene_gltf2.io.com.gltf2_io_extensions import Extension
@cached
def gather_material_normal_texture_info_class(blender_shader_sockets_or_texture_slots: typing.Union[
typing.Tuple[bpy.types.NodeSocket], typing.Tuple[bpy.types.Texture]],
export_settings):
| 64 | 64 | 185 | 43 | 20 | Cyp/glTF-Blender-IO | addons/io_scene_gltf2/blender/exp/gltf2_blender_gather_material_normal_texture_info_class.py | Python | gather_material_normal_texture_info_class | gather_material_normal_texture_info_class | 26 | 41 | 26 | 29 | 97b7f360b1600938969e760cbb0a1b12c9b172ad | bigcode/the-stack | train |
e7f679cc231ac09c0f4ccc31 | train | function | def __gather_extensions(blender_shader_sockets_or_texture_slots, export_settings):
if not export_settings[gltf2_blender_export_keys.TEXTURE_TRANSFORM]:
return None
normal_map_node = blender_shader_sockets_or_texture_slots[0].links[0].from_node
if not isinstance(normal_map_node, bpy.types.ShaderNode... | def __gather_extensions(blender_shader_sockets_or_texture_slots, export_settings):
| if not export_settings[gltf2_blender_export_keys.TEXTURE_TRANSFORM]:
return None
normal_map_node = blender_shader_sockets_or_texture_slots[0].links[0].from_node
if not isinstance(normal_map_node, bpy.types.ShaderNodeNormalMap):
return None
texture_socket = normal_map_node.inputs["Color... | .NodeSocket):
if any([__get_tex_from_socket(socket) is None for socket in blender_shader_sockets_or_texture_slots]):
# sockets do not lead to a texture --> discard
return False
return True
def __gather_extensions(blender_shader_sockets_or_texture_slots, export_settings):
| 64 | 64 | 159 | 17 | 46 | Cyp/glTF-Blender-IO | addons/io_scene_gltf2/blender/exp/gltf2_blender_gather_material_normal_texture_info_class.py | Python | __gather_extensions | __gather_extensions | 56 | 72 | 56 | 56 | 1566705ab390b05dd4b1d443c1c85c0f9dc44852 | bigcode/the-stack | train |
0e098d3b32d6c5df82d9f6d9 | train | function | def __gather_scale(blender_shader_sockets_or_texture_slots, export_settings):
return None
| def __gather_scale(blender_shader_sockets_or_texture_slots, export_settings):
| return None
| _node(texture_node)
extension = Extension("KHR_texture_transform", texture_transform)
return {"KHR_texture_transform": extension}
def __gather_extras(blender_shader_sockets_or_texture_slots, export_settings):
return None
def __gather_scale(blender_shader_sockets_or_texture_slots, export_settings):
| 64 | 64 | 21 | 17 | 46 | Cyp/glTF-Blender-IO | addons/io_scene_gltf2/blender/exp/gltf2_blender_gather_material_normal_texture_info_class.py | Python | __gather_scale | __gather_scale | 79 | 80 | 79 | 79 | e84869fdec8d8578be8d8033a34c2b07c2f9ea39 | bigcode/the-stack | train |
d109424686986635bbe82ae4 | train | function | def __is_socket(sockets_or_slots):
return isinstance(sockets_or_slots[0], bpy.types.NodeSocket)
| def __is_socket(sockets_or_slots):
| return isinstance(sockets_or_slots[0], bpy.types.NodeSocket)
| (input_node.uv_map)
else:
texCoordIndex = blender_mesh.uv_layers.find(input_node.uv_map)
if texCoordIndex >= 0:
return texCoordIndex
return 0
else:
raise NotImplementedError()
def __is_socket(sockets_or_slots):
| 64 | 64 | 24 | 9 | 55 | Cyp/glTF-Blender-IO | addons/io_scene_gltf2/blender/exp/gltf2_blender_gather_material_normal_texture_info_class.py | Python | __is_socket | __is_socket | 123 | 124 | 123 | 123 | d2d9ebd62f350b378056f201ae9a127a1a211557 | bigcode/the-stack | train |
e2492957833060da73c8be04 | train | class | class UpdateVersion:
def main(self):
self.version_major = VERSION_MAJOR
self.version_minor = VERSION_MINOR
self.version_maintenance = VERSION_MAINTENANCE
self.version_build = VERSION_BUILD
# ----------------------- MAIN -------------------------
if len(sys.argv... | class UpdateVersion:
| def main(self):
self.version_major = VERSION_MAJOR
self.version_minor = VERSION_MINOR
self.version_maintenance = VERSION_MAINTENANCE
self.version_build = VERSION_BUILD
# ----------------------- MAIN -------------------------
if len(sys.argv) == 5:
s... | * OpenNI 1.x Alpha *
#* Copyright (C) 2012 PrimeSense Ltd. *
#* *
#* This file is part of OpenNI. *
#... | 256 | 256 | 1,956 | 4 | 251 | Dianpeng-Wang/kinect-1 | Platform/Win32/CreateRedist/UpdateVersion.py | Python | UpdateVersion | UpdateVersion | 32 | 168 | 32 | 32 | a297fc9bbb9717ff94e65839848457815523498b | bigcode/the-stack | train |
5daa8897f03c1225a81df70a | train | function | def get_context():
bloggers = webnotes.conn.sql("""select * from `tabBlogger`
where ifnull(posts,0) > 0 and ifnull(disabled,0)=0
order by posts desc""", as_dict=1)
args = {
"bloggers": bloggers,
"texts": {
"all_posts_by": "All posts by"
},
"categories": webnotes.conn.sql_list("select name from `t... | def get_context():
| bloggers = webnotes.conn.sql("""select * from `tabBlogger`
where ifnull(posts,0) > 0 and ifnull(disabled,0)=0
order by posts desc""", as_dict=1)
args = {
"bloggers": bloggers,
"texts": {
"all_posts_by": "All posts by"
},
"categories": webnotes.conn.sql_list("select name from `tabBlog Category` or... | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import webnotes
def get_context():
| 43 | 64 | 131 | 4 | 38 | hafeez3000/wnframework | website/doctype/blogger/templates/pages/writers.py | Python | get_context | get_context | 7 | 21 | 7 | 7 | da3a29f81ee9da98ff6fb0491decd56892032a7e | bigcode/the-stack | train |
23cf0d34b5bef1e09386fc7d | train | function | def simData(n=1200):
"""
Function to simulate the test dataset
the simulated dataset in the format of Pandas's Data Frame,
columns: ['x1','x2','x3','x4','x5','x6','x7','x8','y']
(xi is the covariate and 'y' is the target variable)
The simulated dataset generated according to th... | def simData(n=1200):
| """
Function to simulate the test dataset
the simulated dataset in the format of Pandas's Data Frame,
columns: ['x1','x2','x3','x4','x5','x6','x7','x8','y']
(xi is the covariate and 'y' is the target variable)
The simulated dataset generated according to the following formula:
... | import numpy as np
import numpy.random as nr
import pandas as pd
def simData(n=1200):
| 24 | 156 | 522 | 8 | 15 | lspatial/baggingrnet | baggingrnet/data/simulatedata.py | Python | simData | simData | 5 | 39 | 5 | 5 | b378bac0279d0db1412764d7309d7bffdbeb74b3 | bigcode/the-stack | train |
38302e4364eafcd0b3a19339 | train | function | def _multiclass_train_input_fn():
features = {
"x": constant_op.constant([[2.], [1.], [1.], [5.], [3.5], [4.6], [3.5]])
}
label = constant_op.constant([[1], [0], [0], [2], [2], [0], [1]],
dtype=dtypes.int32)
return features, label
| def _multiclass_train_input_fn():
| features = {
"x": constant_op.constant([[2.], [1.], [1.], [5.], [3.5], [4.6], [3.5]])
}
label = constant_op.constant([[1], [0], [0], [2], [2], [0], [1]],
dtype=dtypes.int32)
return features, label
| def _train_input_fn():
features = {"x": constant_op.constant([[2.], [1.], [1.]])}
label = constant_op.constant([[1], [0], [0]], dtype=dtypes.int32)
return features, label
def _multiclass_train_input_fn():
| 64 | 64 | 93 | 9 | 54 | lenny93/tensorflow | tensorflow/contrib/boosted_trees/estimator_batch/estimator_test.py | Python | _multiclass_train_input_fn | _multiclass_train_input_fn | 49 | 55 | 49 | 49 | 3379c8459c700965185ff5a2e34e5f62bbe4e2b9 | bigcode/the-stack | train |
1451fb39910c17afc51e6e90 | train | class | class CoreGradientBoostedDecisionTreeEstimators(test_util.TensorFlowTestCase):
def testTrainEvaluateInferDoesNotThrowError(self):
head_fn = head_lib._binary_logistic_head_with_sigmoid_cross_entropy_loss(
loss_reduction=losses.Reduction.SUM_OVER_NONZERO_WEIGHTS)
learner_config = learner_pb2.LearnerCo... | class CoreGradientBoostedDecisionTreeEstimators(test_util.TensorFlowTestCase):
| def testTrainEvaluateInferDoesNotThrowError(self):
head_fn = head_lib._binary_logistic_head_with_sigmoid_cross_entropy_loss(
loss_reduction=losses.Reduction.SUM_OVER_NONZERO_WEIGHTS)
learner_config = learner_pb2.LearnerConfig()
learner_config.num_classes = 2
learner_config.constraints.max_tre... | leaf {
vector {
value: 0.0
}
}
}
nodes {
leaf {
vector {
value: 0.0
}
}
}
nodes {
leaf {
vector {
value: 0.0
}
}
}
... | 256 | 256 | 1,930 | 16 | 240 | lenny93/tensorflow | tensorflow/contrib/boosted_trees/estimator_batch/estimator_test.py | Python | CoreGradientBoostedDecisionTreeEstimators | CoreGradientBoostedDecisionTreeEstimators | 815 | 1,032 | 815 | 816 | 377973c7ad2e8f5c282eae331191b64928889a7f | bigcode/the-stack | train |
3b25b541c3d5187ec3274e8a | train | class | class BoostedTreeEstimatorTest(test_util.TensorFlowTestCase):
def setUp(self):
self._export_dir_base = tempfile.mkdtemp() + "export/"
gfile.MkDir(self._export_dir_base)
def _assert_checkpoint_and_return_model(self, model_dir, global_step):
reader = checkpoint_utils.load_checkpoint(model_dir)
self.... | class BoostedTreeEstimatorTest(test_util.TensorFlowTestCase):
| def setUp(self):
self._export_dir_base = tempfile.mkdtemp() + "export/"
gfile.MkDir(self._export_dir_base)
def _assert_checkpoint_and_return_model(self, model_dir, global_step):
reader = checkpoint_utils.load_checkpoint(model_dir)
self.assertEqual(global_step, reader.get_tensor(ops.GraphKeys.GLOBAL... | QUANTILE_REGRESSION_SIZE)).T
x = x.astype(np.float32)
# Labels.
if not two_dimension:
y = f(x).ravel()
else:
y = np.column_stack((f(x).ravel(), g(x).ravel()))
# Add random noise.
dy = 1.5 + 1.0 * np.random.random(y.shape)
noise = np.random.normal(0, dy)
y += noise
y_original = y.astype(np.fl... | 256 | 256 | 4,749 | 13 | 242 | lenny93/tensorflow | tensorflow/contrib/boosted_trees/estimator_batch/estimator_test.py | Python | BoostedTreeEstimatorTest | BoostedTreeEstimatorTest | 136 | 812 | 136 | 137 | 33637ff385d36e20c86c178ff7cb34af5c4b029a | bigcode/the-stack | train |
1f19611be457970e12e32127 | train | function | def _infer_ranking_train_input_fn():
features = {
"f1": constant_op.constant([[3.], [2], [1.]]),
"f2": constant_op.constant([[0.1], [3.], [1.]])
}
return features, None
| def _infer_ranking_train_input_fn():
| features = {
"f1": constant_op.constant([[3.], [2], [1.]]),
"f2": constant_op.constant([[0.1], [3.], [1.]])
}
return features, None
| def _eval_input_fn():
features = {"x": constant_op.constant([[1.], [2.], [2.]])}
label = constant_op.constant([[0], [1], [1]], dtype=dtypes.int32)
return features, label
def _infer_ranking_train_input_fn():
| 64 | 64 | 62 | 9 | 54 | lenny93/tensorflow | tensorflow/contrib/boosted_trees/estimator_batch/estimator_test.py | Python | _infer_ranking_train_input_fn | _infer_ranking_train_input_fn | 75 | 80 | 75 | 75 | a99702e3739e6a61c21d5f3e573df27bddd49668 | bigcode/the-stack | train |
cb8260f4f13b25f69cc0576a | train | function | def _eval_input_fn():
features = {"x": constant_op.constant([[1.], [2.], [2.]])}
label = constant_op.constant([[0], [1], [1]], dtype=dtypes.int32)
return features, label
| def _eval_input_fn():
| features = {"x": constant_op.constant([[1.], [2.], [2.]])}
label = constant_op.constant([[0], [1], [1]], dtype=dtypes.int32)
return features, label
| ], [5.]]),
"b.f2": constant_op.constant([[1.], [3.], [0.01]]),
}
label = constant_op.constant([[0], [0], [1]], dtype=dtypes.int32)
return features, label
def _eval_input_fn():
| 64 | 64 | 55 | 6 | 57 | lenny93/tensorflow | tensorflow/contrib/boosted_trees/estimator_batch/estimator_test.py | Python | _eval_input_fn | _eval_input_fn | 69 | 72 | 69 | 69 | 90ba9e82e24a98dfd7c6540f21507718c50be804 | bigcode/the-stack | train |
f019641d32966e4a40e23119 | train | function | def _train_input_fn():
features = {"x": constant_op.constant([[2.], [1.], [1.]])}
label = constant_op.constant([[1], [0], [0]], dtype=dtypes.int32)
return features, label
| def _train_input_fn():
| features = {"x": constant_op.constant([[2.], [1.], [1.]])}
label = constant_op.constant([[1], [0], [0]], dtype=dtypes.int32)
return features, label
|
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import test_util
from tensorflow.python.ops.losses import losses
from tensorflow.python.platform import gfile
from tensorflow.python.platform import googletest
from tensorflow.python.train... | 64 | 64 | 55 | 6 | 57 | lenny93/tensorflow | tensorflow/contrib/boosted_trees/estimator_batch/estimator_test.py | Python | _train_input_fn | _train_input_fn | 43 | 46 | 43 | 43 | a1b9e266d091645fba09671592807387af9d9aa1 | bigcode/the-stack | train |
60b861a4f38ffae946156209 | train | function | def _quantile_regression_input_fns(two_dimension=False):
# The data generation is taken from
# http://scikit-learn.org/stable/auto_examples/ensemble/plot_gradient_boosting_quantile.html
np.random.seed(1)
def f(x):
"""The function to predict."""
return x * np.sin(x)
def g(x):
"""The function to p... | def _quantile_regression_input_fns(two_dimension=False):
# The data generation is taken from
# http://scikit-learn.org/stable/auto_examples/ensemble/plot_gradient_boosting_quantile.html
| np.random.seed(1)
def f(x):
"""The function to predict."""
return x * np.sin(x)
def g(x):
"""The function to predict."""
return x * np.cos(x)
# Training data.
x = np.atleast_2d(np.random.uniform(0, 10.0,
size=_QUANTILE_REGRESSION_SIZE)).T
x = x.astyp... | {
"f1": constant_op.constant([[3.], [2], [1.]]),
"f2": constant_op.constant([[0.1], [3.], [1.]])
}
return features, None
_QUANTILE_REGRESSION_SIZE = 1000
def _quantile_regression_input_fns(two_dimension=False):
# The data generation is taken from
# http://scikit-learn.org/stable/auto_examples/ens... | 110 | 110 | 367 | 48 | 61 | lenny93/tensorflow | tensorflow/contrib/boosted_trees/estimator_batch/estimator_test.py | Python | _quantile_regression_input_fns | _quantile_regression_input_fns | 86 | 133 | 86 | 88 | 783547da19e0c2807d8656f6d4fa8281fe6b30f2 | bigcode/the-stack | train |
fca8b6766c6514c80dd0fe71 | train | function | def _ranking_train_input_fn():
features = {
"a.f1": constant_op.constant([[3.], [0.3], [1.]]),
"a.f2": constant_op.constant([[0.1], [3.], [1.]]),
"b.f1": constant_op.constant([[13.], [0.4], [5.]]),
"b.f2": constant_op.constant([[1.], [3.], [0.01]]),
}
label = constant_op.constant([[0], [0]... | def _ranking_train_input_fn():
| features = {
"a.f1": constant_op.constant([[3.], [0.3], [1.]]),
"a.f2": constant_op.constant([[0.1], [3.], [1.]]),
"b.f1": constant_op.constant([[13.], [0.4], [5.]]),
"b.f2": constant_op.constant([[1.], [3.], [0.01]]),
}
label = constant_op.constant([[0], [0], [1]], dtype=dtypes.int32)
r... | [3.5], [4.6], [3.5]])
}
label = constant_op.constant([[1], [0], [0], [2], [2], [0], [1]],
dtype=dtypes.int32)
return features, label
def _ranking_train_input_fn():
| 64 | 64 | 132 | 7 | 56 | lenny93/tensorflow | tensorflow/contrib/boosted_trees/estimator_batch/estimator_test.py | Python | _ranking_train_input_fn | _ranking_train_input_fn | 58 | 66 | 58 | 58 | 99412f250e87ff4debe4892490f156317fd3b4c0 | bigcode/the-stack | train |
a1cef221ca98af500601de55 | train | function | def make_sync_batch_optimizer(workers, config):
return SyncBatchReplayOptimizer(
workers,
learning_starts=config["learning_starts"],
buffer_size=config["buffer_size"],
train_batch_size=config["train_batch_size"])
| def make_sync_batch_optimizer(workers, config):
| return SyncBatchReplayOptimizer(
workers,
learning_starts=config["learning_starts"],
buffer_size=config["buffer_size"],
train_batch_size=config["train_batch_size"])
| _iter_time_s": 1,
# === Model ===
"model": {
"lstm_cell_size": 64,
"max_seq_len": 999999,
},
})
# __sphinx_doc_end__
# yapf: enable
def make_sync_batch_optimizer(workers, config):
| 64 | 64 | 48 | 10 | 53 | brechtmann/ray | rllib/agents/qmix/qmix.py | Python | make_sync_batch_optimizer | make_sync_batch_optimizer | 90 | 95 | 90 | 90 | ee39fca4e7676ff6a860417ac4ab3afcb313d33f | bigcode/the-stack | train |
2cc2120fa5d22b4b1756bea5 | train | class | class authenticationvserver_authenticationwebauthpolicy_binding(base_resource) :
""" Binding class showing the authenticationwebauthpolicy that can be bound to authenticationvserver.
"""
def __init__(self) :
self._policy = ""
self._priority = 0
self._acttype = 0
self._secondary = False
self._name = ""
se... | class authenticationvserver_authenticationwebauthpolicy_binding(base_resource) :
| """ Binding class showing the authenticationwebauthpolicy that can be bound to authenticationvserver.
"""
def __init__(self) :
self._policy = ""
self._priority = 0
self._acttype = 0
self._secondary = False
self._name = ""
self._groupextraction = False
self._nextfactor = ""
self._gotopriorityexpressio... | .
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distri... | 256 | 256 | 2,919 | 15 | 240 | mahabs/nitro | nssrc/com/citrix/netscaler/nitro/resource/config/authentication/authenticationvserver_authenticationwebauthpolicy_binding.py | Python | authenticationvserver_authenticationwebauthpolicy_binding | authenticationvserver_authenticationwebauthpolicy_binding | 24 | 335 | 24 | 24 | 53e3eac8653c22d2db89e182cc50d8bbf17b671c | bigcode/the-stack | train |
68fd620de0b59e8fdbb8bb93 | train | class | class authenticationvserver_authenticationwebauthpolicy_binding_response(base_response) :
def __init__(self, length=1) :
self.authenticationvserver_authenticationwebauthpolicy_binding = []
self.errorcode = 0
self.message = ""
self.severity = ""
self.sessionid = ""
self.authenticationvserver_authenticationw... | class authenticationvserver_authenticationwebauthpolicy_binding_response(base_response) :
| def __init__(self, length=1) :
self.authenticationvserver_authenticationwebauthpolicy_binding = []
self.errorcode = 0
self.message = ""
self.severity = ""
self.sessionid = ""
self.authenticationvserver_authenticationwebauthpolicy_binding = [authenticationvserver_authenticationwebauthpolicy_binding() for _ ... | option_.filter = filter_
response = obj.getfiltered(service, option_)
if response :
return response[0].__dict__['___count']
return 0
except Exception as e:
raise e
class authenticationvserver_authenticationwebauthpolicy_binding_response(base_response) :
| 64 | 64 | 97 | 16 | 47 | mahabs/nitro | nssrc/com/citrix/netscaler/nitro/resource/config/authentication/authenticationvserver_authenticationwebauthpolicy_binding.py | Python | authenticationvserver_authenticationwebauthpolicy_binding_response | authenticationvserver_authenticationwebauthpolicy_binding_response | 337 | 344 | 337 | 337 | 201c5549d06d68e4456226826831dd13469692fd | bigcode/the-stack | train |
b671979ff982f7fe7a0f2cd8 | train | class | class AutomateBase(entity.Entity):
"""Base representation of an Automate roller."""
def __init__(self, roller: aiopulse2.Roller) -> None:
"""Initialize the roller."""
self.roller = roller
@property
def available(self) -> bool:
"""Return True if roller and hub is available."""
... | class AutomateBase(entity.Entity):
| """Base representation of an Automate roller."""
def __init__(self, roller: aiopulse2.Roller) -> None:
"""Initialize the roller."""
self.roller = roller
@property
def available(self) -> bool:
"""Return True if roller and hub is available."""
return self.roller.online an... | """Base class for Automate Roller Blinds."""
import logging
import aiopulse2
from homeassistant.core import callback
from homeassistant.helpers import entity
from homeassistant.helpers.device_registry import async_get_registry as get_dev_reg
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from h... | 102 | 153 | 511 | 7 | 95 | Andrew55529/core | homeassistant/components/automate/base.py | Python | AutomateBase | AutomateBase | 17 | 93 | 17 | 17 | 80bb82a5ed2815bab852aed1b6e5b48d16a5cd42 | bigcode/the-stack | train |
4905a82760f108e83e11e81d | train | function | def filter_func(s):
if s.isspace() == True or len(s) < 1:
return False
else:
return True
| def filter_func(s):
| if s.isspace() == True or len(s) < 1:
return False
else:
return True
| '''
This module returns an array of tags pertaining to a single problem.
'''
import requests
from bs4 import BeautifulSoup
#A filter function to remove some unnecessary tags.
def filter_func(s):
| 40 | 64 | 31 | 5 | 35 | anirudnits/Spojy | spojy/single_problem_info.py | Python | filter_func | filter_func | 10 | 14 | 10 | 10 | 86c80e8612d439257b261ebe01dcd8f66a3b6ae8 | bigcode/the-stack | train |
479eb07f717b90460e8e0f94 | train | function | def get_single_problem_tags(problem):
'''
Main function which takes the problem name as input and returns an array of tags pertaining to that problem.
'''
problem = str(problem)
problem_url = "https://www.spoj.com/problems/" + problem + "/"
problem_tags = get_tags(problem_url)
return problem_tags
| def get_single_problem_tags(problem):
| '''
Main function which takes the problem name as input and returns an array of tags pertaining to that problem.
'''
problem = str(problem)
problem_url = "https://www.spoj.com/problems/" + problem + "/"
problem_tags = get_tags(problem_url)
return problem_tags
| id" : "problem-tags"})
try:
links = problem_tag_div.find_all("a")
except:
print ("No problem by this name")
exit(0)
problem_tags = list(filter(filter_func, problem_tag_div.text.split()))
return problem_tags
def get_single_problem_tags(problem):
| 64 | 64 | 68 | 7 | 56 | anirudnits/Spojy | spojy/single_problem_info.py | Python | get_single_problem_tags | get_single_problem_tags | 39 | 50 | 39 | 39 | c553cf1a3df49c771ed9e5e5bb34e89c6d0c3721 | bigcode/the-stack | train |
0b30a69bc1b0e68f76ce3f98 | train | function | def get_tags(problem_url):
'''
utility function to fetch all the problem tags from the response page
'''
response = requests.get(problem_url)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
problem_tag_div = soup.find("div", attrs= {"id" : "problem-tags"})
try:
links = probl... | def get_tags(problem_url):
| '''
utility function to fetch all the problem tags from the response page
'''
response = requests.get(problem_url)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
problem_tag_div = soup.find("div", attrs= {"id" : "problem-tags"})
try:
links = problem_tag_div.find_all("a")
e... | pertaining to a single problem.
'''
import requests
from bs4 import BeautifulSoup
#A filter function to remove some unnecessary tags.
def filter_func(s):
if s.isspace() == True or len(s) < 1:
return False
else:
return True
def get_tags(problem_url):
| 64 | 64 | 118 | 6 | 57 | anirudnits/Spojy | spojy/single_problem_info.py | Python | get_tags | get_tags | 17 | 36 | 17 | 17 | b9a3af1d6dbf6afd3e593e27a6a842e9e238eb11 | bigcode/the-stack | train |
7a13c2b71ec1ef8072c76e6b | train | function | def remat(fn: Callable[..., Any],
variables: CollectionFilter = True,
rngs: PRNGSequenceFilter = True) -> Callable[..., Any]:
"""Lifted version of jax.remat."""
def inner(scope_fn, repack_fn, variable_groups, rng_groups, *args):
@jax.remat
@functools.wraps(fn)
def rematted(variable_g... | def remat(fn: Callable[..., Any],
variables: CollectionFilter = True,
rngs: PRNGSequenceFilter = True) -> Callable[..., Any]:
| """Lifted version of jax.remat."""
def inner(scope_fn, repack_fn, variable_groups, rng_groups, *args):
@jax.remat
@functools.wraps(fn)
def rematted(variable_groups, rng_groups, *args):
scope = scope_fn(variable_groups, rng_groups)
y = fn(scope, *args)
return y, repack_fn(scope)
re... | rng_groups = (True,)
return pack(
inner, variable_in_groups, variable_out_groups, rng_groups,
name='custom_vjp')
def remat(fn: Callable[..., Any],
variables: CollectionFilter = True,
rngs: PRNGSequenceFilter = True) -> Callable[..., Any]:
| 64 | 64 | 153 | 33 | 31 | joelgarde/flax | flax/core/lift.py | Python | remat | remat | 589 | 602 | 589 | 591 | 222bac68bf99cb76bb95f95d874cead59379d9a8 | bigcode/the-stack | train |
4f98d3c56e896cd04853d7d3 | train | class | @dataclass(frozen=True)
class Out(Generic[T]):
"""Specifies a variable collection should only be lifted as output."""
axis: Any # pytype does not support generic variable annotation
| @dataclass(frozen=True)
class Out(Generic[T]):
| """Specifies a variable collection should only be lifted as output."""
axis: Any # pytype does not support generic variable annotation
| col_a, col_b), swap, swap, mutable=True)
@dataclass(frozen=True)
class In(Generic[T]):
"""Specifies a variable collection should only be lifted as input."""
axis: Any # pytype does not support generic variable annotation
@dataclass(frozen=True)
class Out(Generic[T]):
| 64 | 64 | 40 | 11 | 52 | joelgarde/flax | flax/core/lift.py | Python | Out | Out | 293 | 296 | 293 | 294 | 62e53973d87c008d99e48c75c1301f7e22b783ba | bigcode/the-stack | train |
1ada027f97db305b883d64b2 | train | function | def transform(
fn: Callable[..., Any],
target: CollectionFilter,
trans_in_fn: Callable[..., Any] = id_fn,
trans_out_fn: Callable[..., Any] = id_fn,
init: bool = False, mutable: bool = False,
rngs: PRNGSequenceFilter = True, variables: CollectionFilter = True):
"""Locally transform Variables in... | def transform(
fn: Callable[..., Any],
target: CollectionFilter,
trans_in_fn: Callable[..., Any] = id_fn,
trans_out_fn: Callable[..., Any] = id_fn,
init: bool = False, mutable: bool = False,
rngs: PRNGSequenceFilter = True, variables: CollectionFilter = True):
| """Locally transform Variables inside a scope.
Args:
fn: the function to be transformed.
target: the collection(s) to be transformed.
trans_in_fn: creates a view of the target variables.
trans_out_fn: transforms the updated variables in the view after mutation.
init: If True, variables are init... | _xs_t)
for scope, out_variable_groups in zip(scopes, out_variable_groups_xs):
for out_variable_group in out_variable_groups:
for col_name, collection in out_variable_group.items():
for var_name, value in collection.items():
scope.put_variable(col_name, var_name, value)
return... | 155 | 155 | 517 | 73 | 81 | joelgarde/flax | flax/core/lift.py | Python | transform | transform | 197 | 245 | 197 | 203 | 880af2be9976af194aa4526d7f1b6af4c8e86f17 | bigcode/the-stack | train |
81359587275d2518e70b1e87 | train | function | def _unzip2(xs):
ys = tuple(zip(*xs))
return ys if ys else ((), ())
| def _unzip2(xs):
| ys = tuple(zip(*xs))
return ys if ys else ((), ())
| jax.named_call(named, name=name)
return named(variable_groups, rng_groups)
lifted = pack(inner, (True,), (True,), (True,))
def wrapper(scope, *args, **kwargs):
return lifted(scope, args, kwargs)
return wrapper
def _unzip2(xs):
| 64 | 64 | 24 | 7 | 56 | joelgarde/flax | flax/core/lift.py | Python | _unzip2 | _unzip2 | 686 | 688 | 686 | 686 | 6a7b6bc4597232073c872f02a9567c3f9daebf8a | bigcode/the-stack | train |
451f40f66f8398429bd9fb5d | train | class | @dataclass(frozen=True)
class In(Generic[T]):
"""Specifies a variable collection should only be lifted as input."""
axis: Any # pytype does not support generic variable annotation
| @dataclass(frozen=True)
class In(Generic[T]):
| """Specifies a variable collection should only be lifted as input."""
axis: Any # pytype does not support generic variable annotation
| else {}
b = target[col_b] if col_b in target else {}
target[col_b], target[col_a] = a, b
return target
return transform(fn, (col_a, col_b), swap, swap, mutable=True)
@dataclass(frozen=True)
class In(Generic[T]):
| 64 | 64 | 40 | 11 | 53 | joelgarde/flax | flax/core/lift.py | Python | In | In | 288 | 291 | 288 | 289 | 2996b0fb7417d2820661b40e08b2df00eeca60e2 | bigcode/the-stack | train |
7d2c4e7a6e8417edc8fa921f | train | function | def pack(fn: Callable[..., Any],
in_variable_filters: Sequence[CollectionFilter],
out_variable_filters: Sequence[CollectionFilter],
rng_filters: Sequence[PRNGSequenceFilter],
name=None) -> Callable[..., Any]:
"""Pack variables and rngs for functional transformations.
The pack fu... | def pack(fn: Callable[..., Any],
in_variable_filters: Sequence[CollectionFilter],
out_variable_filters: Sequence[CollectionFilter],
rng_filters: Sequence[PRNGSequenceFilter],
name=None) -> Callable[..., Any]:
| """Pack variables and rngs for functional transformations.
The pack function is the building block for all other lifted transformations.
"""
@functools.wraps(fn)
def wrapper(scope_tree: Scope, *args):
# pylint: disable=protected-access
scopes, treedef = jax.tree_flatten(scope_tree)
scopes, paths ... | _set = collections.OrderedDict((s, ()) for s in scopes)
for leaf in scopes:
scope = leaf.parent
max_parent = leaf
max_parent_path = ()
path = [leaf.name]
while scope is not None:
if scope in minimal_set:
max_parent = scope
max_parent_path = tuple(reversed(path))
path.ap... | 256 | 256 | 1,135 | 48 | 208 | joelgarde/flax | flax/core/lift.py | Python | pack | pack | 73 | 191 | 73 | 77 | a54eb6c1d006d7f5b872084ff829cdcdbf5bb1fd | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.