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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ec358ecfd2824be69fbc561b | train | class | class IsRelatedFeedOwnerOrChris(permissions.BasePermission):
"""
Custom permission to only allow owners of an object or superuser
'chris' to access a feed-related object (eg. a plugin instance).
"""
def has_object_permission(self, request, view, obj):
# Access is only allowed to related fee... | class IsRelatedFeedOwnerOrChris(permissions.BasePermission):
| """
Custom permission to only allow owners of an object or superuser
'chris' to access a feed-related object (eg. a plugin instance).
"""
def has_object_permission(self, request, view, obj):
# Access is only allowed to related feed owners and superuser 'chris'.
#import pdb; pdb.set_... | from rest_framework import permissions
class IsRelatedFeedOwnerOrChris(permissions.BasePermission):
| 18 | 64 | 147 | 12 | 5 | rudolphpienaar/ChRIS_ultron_backEnd | chris_backend/plugininstances/permissions.py | Python | IsRelatedFeedOwnerOrChris | IsRelatedFeedOwnerOrChris | 4 | 21 | 4 | 4 | 78f4ee4ceeb93cd9488626822ea8b7b24cee84d6 | bigcode/the-stack | train |
6424f3132c8e477334682629 | train | class | class BasicValidator(object):
single_schema = None
collection_schema = None
@classmethod
def validate_json(cls, data):
if data:
try:
res = jsonutils.loads(data)
except Exception:
raise errors.InvalidData(
"Invalid json... | class BasicValidator(object):
| single_schema = None
collection_schema = None
@classmethod
def validate_json(cls, data):
if data:
try:
res = jsonutils.loads(data)
except Exception:
raise errors.InvalidData(
"Invalid json received",
... | a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# ... | 126 | 126 | 422 | 5 | 120 | Zipfer/fuel-web | nailgun/nailgun/api/v1/validators/base.py | Python | BasicValidator | BasicValidator | 23 | 91 | 23 | 24 | 20cbb6698945e786f6efce6b66322ef13c4de90b | bigcode/the-stack | train |
fe4864989e02105951e872fc | train | function | def main():
# parse input arguments
parser = argparse.ArgumentParser()
parser.add_argument("--node-name", type=str, default="env_node")
parser.add_argument(
"--task-config", type=str, default="configs/pointnav_d_orignal.yaml"
)
parser.add_argument("--enable-physics-sim", default=False, a... | def main():
# parse input arguments
| parser = argparse.ArgumentParser()
parser.add_argument("--node-name", type=str, default="env_node")
parser.add_argument(
"--task-config", type=str, default="configs/pointnav_d_orignal.yaml"
)
parser.add_argument("--enable-physics-sim", default=False, action="store_true")
parser.add_argum... | _dir=self.config.VIDEO_DIR,
images=self.observations_per_episode,
episode_id="fake_episode_id",
scene_id="fake_scene_id",
agent_seed=0,
checkpoint_idx=0,
metrics={},
tb_writer=None,
)
def main():
... | 64 | 64 | 202 | 9 | 55 | ericchen321/ros_x_habitat | src/nodes/habitat_env_node.py | Python | main | main | 679 | 705 | 679 | 680 | 0ea02fd344f9d50911853701dd67d5e8f0ec1787 | bigcode/the-stack | train |
dad3e4fc6f47453ab22ef4d2 | train | class | class HabitatEnvNode:
r"""
A class to represent a ROS node with a Habitat simulator inside.
The node subscribes to agent command topics, and publishes sensor
readings to sensor topics.
"""
def __init__(
self,
node_name: str,
config_paths: str = None,
enable_physi... | class HabitatEnvNode:
| r"""
A class to represent a ROS node with a Habitat simulator inside.
The node subscribes to agent command topics, and publishes sensor
readings to sensor topics.
"""
def __init__(
self,
node_name: str,
config_paths: str = None,
enable_physics_sim: bool = False,
... | #!/usr/bin/env python
import argparse
from threading import Condition, Lock
import numpy as np
import rospy
from cv_bridge import CvBridge
from geometry_msgs.msg import Twist
from habitat.config.default import get_config
from habitat.core.simulator import Observations
from ros_x_habitat.msg import PointGoalWithGPSComp... | 237 | 256 | 5,130 | 5 | 232 | ericchen321/ros_x_habitat | src/nodes/habitat_env_node.py | Python | HabitatEnvNode | HabitatEnvNode | 32 | 676 | 32 | 32 | 488aad3bef231a57c78846360d1ff3978a7b0923 | bigcode/the-stack | train |
a479495986269368c69c9778 | train | class | class Customer(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=100, null=True)
email = models.EmailField(null=True, unique=True)
address = models.CharField(max_length=100, null=True)
phone = PhoneNumberField(n... | class Customer(models.Model):
| owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=100, null=True)
email = models.EmailField(null=True, unique=True)
address = models.CharField(max_length=100, null=True)
phone = PhoneNumberField(null=False, blank=False, unique... | from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
# Create your models here.
class Customer(models.Model):
| 43 | 64 | 171 | 5 | 38 | RFNshare/StraightIntLtd | customer/models.py | Python | Customer | Customer | 9 | 23 | 9 | 9 | 9d668c7da721f9415f981ab57e5e28c14294c796 | bigcode/the-stack | train |
e18654fabf6461e917158233 | train | function | @api_key_only_webhook_view('SolanoLabs')
@has_request_variables
def api_solano_webhook(request: HttpRequest, user_profile: UserProfile,
payload: Dict[str, Any]=REQ(argument_type='body')) -> HttpResponse:
event = payload.get('event')
topic = 'build update'
if event == 'test':
r... | @api_key_only_webhook_view('SolanoLabs')
@has_request_variables
def api_solano_webhook(request: HttpRequest, user_profile: UserProfile,
payload: Dict[str, Any]=REQ(argument_type='body')) -> HttpResponse:
| event = payload.get('event')
topic = 'build update'
if event == 'test':
return handle_test_event(request, user_profile, topic)
try:
author = payload['committers'][0]
except KeyError:
author = 'Unknown'
status = payload['status']
build_log = payload['url']
reposito... | _message
from zerver.models import UserProfile
MESSAGE_TEMPLATE = """
Build update (see [build log]({build_log_url})):
* **Author**: {author}
* **Commit**: [{commit_id}]({commit_url})
* **Status**: {status} {emoji}
""".strip()
@api_key_only_webhook_view('SolanoLabs')
@has_request_variables
def api_solano_webhook(reque... | 116 | 116 | 387 | 52 | 64 | kaustubh-nair/zulip | zerver/webhooks/solano/view.py | Python | api_solano_webhook | api_solano_webhook | 19 | 64 | 19 | 22 | f3796b24f769a2323e8f94f7fb63aa74076a3715 | bigcode/the-stack | train |
750f7df17e3e0e89b095d33c | train | function | def handle_test_event(request: HttpRequest, user_profile: UserProfile,
topic: str) -> HttpResponse:
body = 'Solano webhook set up correctly.'
check_send_webhook_message(request, user_profile, topic, body)
return json_success()
| def handle_test_event(request: HttpRequest, user_profile: UserProfile,
topic: str) -> HttpResponse:
| body = 'Solano webhook set up correctly.'
check_send_webhook_message(request, user_profile, topic, body)
return json_success()
| _id[:7], commit_url=commit_url,
status=status, emoji=emoji,
)
check_send_webhook_message(request, user_profile, topic, body)
return json_success()
def handle_test_event(request: HttpRequest, user_profile: UserProfile,
topic: str) -> HttpResponse:
| 64 | 64 | 55 | 24 | 40 | kaustubh-nair/zulip | zerver/webhooks/solano/view.py | Python | handle_test_event | handle_test_event | 66 | 70 | 66 | 67 | e30531e262804c6d6f99e1031100017ae62f7a22 | bigcode/the-stack | train |
275eacaaa812536fbf7c65c3 | train | class | class StringsTest(unittest.TestCase):
def test_contains_with_matching_patterns(self):
# Positive test cases (examples) with matching patterns
assert contains('abc', '') is True # all strings contain empty string
assert contains('abc', 'a') is True # single letters are easy
assert ... | class StringsTest(unittest.TestCase):
| def test_contains_with_matching_patterns(self):
# Positive test cases (examples) with matching patterns
assert contains('abc', '') is True # all strings contain empty string
assert contains('abc', 'a') is True # single letters are easy
assert contains('abc', 'b') is True
as... | #!python
from strings import contains, find_index, find_all_indexes
import unittest
class StringsTest(unittest.TestCase):
| 25 | 256 | 1,576 | 7 | 17 | ablades/CS-1.3-Core-Data-Structures | Code/strings_test.py | Python | StringsTest | StringsTest | 7 | 111 | 7 | 8 | 2db5918f412d5fed8443ebf335e0fcbe1cffe2b0 | bigcode/the-stack | train |
9ab73a63f00ca9008b1a299a | train | function | @router.get("/self", response_model=GroupInDB)
async def get_current_user_group(
current_user: UserInDB = Depends(get_current_user),
session: Session = Depends(generate_session),
):
""" Returns the Group Data for the Current User """
current_user: UserInDB
return db.groups.get(session, current_user... | @router.get("/self", response_model=GroupInDB)
async def get_current_user_group(
current_user: UserInDB = Depends(get_current_user),
session: Session = Depends(generate_session),
):
| """ Returns the Group Data for the Current User """
current_user: UserInDB
return db.groups.get(session, current_user.group, "name")
| ):
""" Returns a list of all groups in the database """
return db.groups.get_all(session)
@router.get("/self", response_model=GroupInDB)
async def get_current_user_group(
current_user: UserInDB = Depends(get_current_user),
session: Session = Depends(generate_session),
):
| 64 | 64 | 76 | 43 | 21 | sephrat/mealie | mealie/routes/groups/crud.py | Python | get_current_user_group | get_current_user_group | 22 | 30 | 22 | 26 | 957d256410865c3d7534bb925bddea04ffb05df5 | bigcode/the-stack | train |
133f099a1145c38e24adf83a | train | function | @router.post("")
async def create_group(
group_data: GroupBase,
current_user=Depends(get_current_user),
session: Session = Depends(generate_session),
):
""" Creates a Group in the Database """
try:
db.groups.create(session, group_data.dict())
return SnackResponse.success("User Group... | @router.post("")
async def create_group(
group_data: GroupBase,
current_user=Depends(get_current_user),
session: Session = Depends(generate_session),
):
| """ Creates a Group in the Database """
try:
db.groups.create(session, group_data.dict())
return SnackResponse.success("User Group Created", {"created": True})
except:
return SnackResponse.error("User Group Creation Failed")
| Group Data for the Current User """
current_user: UserInDB
return db.groups.get(session, current_user.group, "name")
@router.post("")
async def create_group(
group_data: GroupBase,
current_user=Depends(get_current_user),
session: Session = Depends(generate_session),
):
| 64 | 64 | 86 | 35 | 29 | sephrat/mealie | mealie/routes/groups/crud.py | Python | create_group | create_group | 33 | 45 | 33 | 38 | c4c4cf0615bb1ea993d5e3621a6954e894dc1806 | bigcode/the-stack | train |
93111b74c44487afa8351ce1 | train | function | @router.put("/{id}")
async def update_group_data(
id: int,
group_data: UpdateGroup,
current_user=Depends(get_current_user),
session: Session = Depends(generate_session),
):
""" Updates a User Group """
db.groups.update(session, id, group_data.dict())
return SnackResponse.success("Group Sett... | @router.put("/{id}")
async def update_group_data(
id: int,
group_data: UpdateGroup,
current_user=Depends(get_current_user),
session: Session = Depends(generate_session),
):
| """ Updates a User Group """
db.groups.update(session, id, group_data.dict())
return SnackResponse.success("Group Settings Updated")
| Created", {"created": True})
except:
return SnackResponse.error("User Group Creation Failed")
@router.put("/{id}")
async def update_group_data(
id: int,
group_data: UpdateGroup,
current_user=Depends(get_current_user),
session: Session = Depends(generate_session),
):
| 64 | 64 | 72 | 43 | 21 | sephrat/mealie | mealie/routes/groups/crud.py | Python | update_group_data | update_group_data | 48 | 58 | 48 | 54 | 8cde22c998102f7263c1edf7f95130aaee8b7ad3 | bigcode/the-stack | train |
a0ee3288faa66cde35ee4ccf | train | function | @router.delete("/{id}")
async def delete_user_group(
id: int, current_user=Depends(get_current_user), session: Session = Depends(generate_session)
):
""" Removes a user group from the database """
if id == 1:
return SnackResponse.error("Cannot delete default group")
group: GroupInDB = db.group... | @router.delete("/{id}")
async def delete_user_group(
id: int, current_user=Depends(get_current_user), session: Session = Depends(generate_session)
):
| """ Removes a user group from the database """
if id == 1:
return SnackResponse.error("Cannot delete default group")
group: GroupInDB = db.groups.get(session, id)
if not group:
return SnackResponse.error("Group not found")
if not group.users == []:
return SnackResponse.er... | ):
""" Updates a User Group """
db.groups.update(session, id, group_data.dict())
return SnackResponse.success("Group Settings Updated")
@router.delete("/{id}")
async def delete_user_group(
id: int, current_user=Depends(get_current_user), session: Session = Depends(generate_session)
):
| 64 | 64 | 122 | 34 | 30 | sephrat/mealie | mealie/routes/groups/crud.py | Python | delete_user_group | delete_user_group | 61 | 80 | 61 | 64 | 5faecae128dadd5083c471ee15c7ada1778aed53 | bigcode/the-stack | train |
6160b8befe2db4018bd32e0f | train | function | @router.get("", response_model=list[GroupInDB])
async def get_all_groups(
current_user=Depends(get_current_user),
session: Session = Depends(generate_session),
):
""" Returns a list of all groups in the database """
return db.groups.get_all(session)
| @router.get("", response_model=list[GroupInDB])
async def get_all_groups(
current_user=Depends(get_current_user),
session: Session = Depends(generate_session),
):
| """ Returns a list of all groups in the database """
return db.groups.get_all(session)
| , UserInDB
from sqlalchemy.orm.session import Session
router = APIRouter(prefix="/api/groups", tags=["Groups"])
@router.get("", response_model=list[GroupInDB])
async def get_all_groups(
current_user=Depends(get_current_user),
session: Session = Depends(generate_session),
):
| 63 | 64 | 57 | 37 | 26 | sephrat/mealie | mealie/routes/groups/crud.py | Python | get_all_groups | get_all_groups | 12 | 19 | 12 | 16 | 64182d31c6df6c71bc1e02e8ed92525deeeba05a | bigcode/the-stack | train |
9e1ee68c21b9de1ef5570d83 | train | class | class UserAccount(collections.Mapping):
VALID_KEYS = [
"github",
"name",
"slack",
"github_avatar",
"avatar",
]
def __init__(self, name, github=None, slack=None):
self.__github = github
self.__slack = slack
self.name = name
@property
... | class UserAccount(collections.Mapping):
| VALID_KEYS = [
"github",
"name",
"slack",
"github_avatar",
"avatar",
]
def __init__(self, name, github=None, slack=None):
self.__github = github
self.__slack = slack
self.name = name
@property
def github(self):
if self.__gith... | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import collections
class UserAccount(collections.Mapping):
| 24 | 91 | 305 | 7 | 16 | Saevon/github-slack-bot | user_mapping.py | Python | UserAccount | UserAccount | 6 | 69 | 6 | 7 | 3e317da56f29d977b9e6bad68623da30b72d1ae8 | bigcode/the-stack | train |
93844ef34ff993887d5d1fb2 | train | class | class UserMapping(object):
def __init__(self, default=None):
self.users = {}
self.slacks = {}
self.githubs = {}
if default is not None:
for user in default:
self.add_user(**user)
def add_user(self, name, github=None, slack=None):
user = User... | class UserMapping(object):
| def __init__(self, default=None):
self.users = {}
self.slacks = {}
self.githubs = {}
if default is not None:
for user in default:
self.add_user(**user)
def add_user(self, name, github=None, slack=None):
user = UserAccount(
name=na... |
def __iter__(self):
for key in self.VALID_KEYS:
yield key
def __len__(self):
return len(list(iter(self)))
def __unicode__(self):
return self.name
def __repr__(self):
return unicode(self)
############################
# Comparison
def __eq__(s... | 90 | 90 | 300 | 5 | 84 | Saevon/github-slack-bot | user_mapping.py | Python | UserMapping | UserMapping | 72 | 123 | 72 | 73 | f8b80392752837e1d543a96b3d7063653444f520 | bigcode/the-stack | train |
f65afc07652fcdc5844dd632 | train | class | class PlayerShip(Sprite):
"""
Animated space ship
"""
asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png", Frame(227-65,0,65,125), 4, 'vertical')
def __init__(self, position):
super().__init__(PlayerShip.asset, position, CircleAsset(32.5))
self.vx = 0
self... | class PlayerShip(Sprite):
| """
Animated space ship
"""
asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png", Frame(227-65,0,65,125), 4, 'vertical')
def __init__(self, position):
super().__init__(PlayerShip.asset, position, CircleAsset(32.5))
self.vx = 0
self.vy = 0
self.vr = ... | -2.5 * speed_limit * math.cos(direction)
self.vr = 0
self.fxcenter = self.fycenter = 0.5
self.bulletphase = 0
self.collisions = []
def collision(self):
[self.collisions.append(x) for x in self.collidingWithSprites(PlayerShip)]
[self.collisions.append(x) for ... | 210 | 210 | 703 | 5 | 204 | sth23/Space-Shooter | spaceshooter.py | Python | PlayerShip | PlayerShip | 67 | 149 | 67 | 67 | e2e10686eacf265669fc68b30a395fc0c110f49f | bigcode/the-stack | train |
7819c75479a5bdce8d396e0b | train | class | class SpaceGame(App):
"""
Tutorial4 space game example.
"""
def __init__(self):
super().__init__()
# Background
black = Color(0, 1)
noline = LineStyle(0, black)
#bg_asset = RectangleAsset(self.width, self.height, noline, black)
#bg = Sprite(bg_asset, (0,0)... | class SpaceGame(App):
| """
Tutorial4 space game example.
"""
def __init__(self):
super().__init__()
# Background
black = Color(0, 1)
noline = LineStyle(0, black)
#bg_asset = RectangleAsset(self.width, self.height, noline, black)
#bg = Sprite(bg_asset, (0,0))
starfield_as... | & shoot
if self.count%self.difficulty == 0:
if random.randint(0,1) == 1:
self.thrustOn()
if random.randint(0,1) == 1:
self.thrustOff()
# Make random turns
"""if random.randint(0,1) == 1:
self.rotateRightOn()
... | 240 | 241 | 804 | 5 | 235 | sth23/Space-Shooter | spaceshooter.py | Python | SpaceGame | SpaceGame | 262 | 348 | 262 | 262 | a31cc1ca555a610e83eb2bda7849c11619940293 | bigcode/the-stack | train |
d9997d74de0e4fe4e89e7162 | train | class | class Bullet(Sprite):
asset = ImageAsset("images/blast.png", Frame(0,0,8,8), 8, 'horizontal')
def __init__(self, position, direction):
super().__init__(Bullet.asset, [position[0] - 50 * math.sin(direction), position[1] - 50 * math.cos(direction)])
self.vx = -2.5 * speed_limit * math.sin(dir... | class Bullet(Sprite):
| asset = ImageAsset("images/blast.png", Frame(0,0,8,8), 8, 'horizontal')
def __init__(self, position, direction):
super().__init__(Bullet.asset, [position[0] - 50 * math.sin(direction), position[1] - 50 * math.cos(direction)])
self.vx = -2.5 * speed_limit * math.sin(direction)
self.v... | up = 0
self.countdown = 10
def step(self):
# Manage explosion animation
if self.countup < 10:
self.setImage(self.countup%10)
self.countup += 1
else:
self.setImage(self.countdown%10)
self.countdown -= 1
if self.count... | 89 | 89 | 297 | 4 | 85 | sth23/Space-Shooter | spaceshooter.py | Python | Bullet | Bullet | 37 | 64 | 37 | 37 | 0d0af0cd1fb5623835ab2bd33009f2a5483a3984 | bigcode/the-stack | train |
69eac36278cb70f80d472bff | train | class | class Explosion(Sprite):
asset = ImageAsset("images/explosion1.png", Frame(0,0,128,128), 10, 'horizontal')
def __init__(self, position):
super().__init__(Explosion.asset, position)
self.fxcenter = self.fycenter = 0.5
self.countup = 0
self.countdown = 10
def step... | class Explosion(Sprite):
| asset = ImageAsset("images/explosion1.png", Frame(0,0,128,128), 10, 'horizontal')
def __init__(self, position):
super().__init__(Explosion.asset, position)
self.fxcenter = self.fycenter = 0.5
self.countup = 0
self.countdown = 10
def step(self):
# Manage ... | submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, RectangleAsset, CircleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
import math
import random
speed_limit = 10
class Explosion(Sprite):
| 64 | 64 | 155 | 4 | 59 | sth23/Space-Shooter | spaceshooter.py | Python | Explosion | Explosion | 17 | 35 | 17 | 17 | e2c6d1a5989549619f29e9df81a3d39afb0a893e | bigcode/the-stack | train |
50a98d17c039b8cb2c3f1fc6 | train | class | class EnemyShip(Sprite):
"""
Animated space ship
"""
asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png", Frame(227,0,65,125), 4, 'vertical')
def __init__(self, position, challenge):
super().__init__(EnemyShip.asset, position, CircleAsset(32.5))
self.vx = 0
... | class EnemyShip(Sprite):
| """
Animated space ship
"""
asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png", Frame(227,0,65,125), 4, 'vertical')
def __init__(self, position, challenge):
super().__init__(EnemyShip.asset, position, CircleAsset(32.5))
self.vx = 0
self.vy = 0
sel... | 0
def shoot(self, event):
Bullet((self.x, self.y), self.rotation)
def collision(self):
[self.collisions.append(x) for x in self.collidingWithSprites(PlayerShip)]
[self.collisions.append(x) for x in self.collidingWithSprites(EnemyShip)]
[self.collisions.append(x... | 256 | 256 | 862 | 5 | 250 | sth23/Space-Shooter | spaceshooter.py | Python | EnemyShip | EnemyShip | 152 | 260 | 152 | 152 | 85faddc3914e2302eba79a783aaf2877161eb4ab | bigcode/the-stack | train |
14490e28e09d27c308906d13 | train | function | def squeezeCoeffIdx(coeff_ptrs_layer, array_w, numBases, layerIdx, pathName, dynamicChunk=False, precompChunk=False, addChunk=0):
if (not dynamicChunk) or layerIdx == 12:
return squeezeCoeffIdxOLD(coeff_ptrs_layer, array_w, numBases, layerIdx, pathName)
# IDEA: move fold and other precalculations out o... | def squeezeCoeffIdx(coeff_ptrs_layer, array_w, numBases, layerIdx, pathName, dynamicChunk=False, precompChunk=False, addChunk=0):
| if (not dynamicChunk) or layerIdx == 12:
return squeezeCoeffIdxOLD(coeff_ptrs_layer, array_w, numBases, layerIdx, pathName)
# IDEA: move fold and other precalculations out of wrapped function
# make wrapped function simply squeeze chunks based on dynamic sizes of 'array_w'
data = torch.load(pat... | assert max(chunks) >= len(coeff_ptrs_layer)
# keep track of pruning performance
tot_pruned = 0
tot_rounds = 0
sq_ptrs = []
for chunk_idx in range(len(chunks) - 1):
assert array_w >= (chunks[chunk_idx + 1] - chunks[chunk_idx]), "Issue: {} vs {}".format(chunks[chunk_idx + 1], chunks[chun... | 256 | 256 | 1,066 | 35 | 220 | Rudedaisy/SCALE-Sim | OLDloadData.py | Python | squeezeCoeffIdx | squeezeCoeffIdx | 119 | 217 | 119 | 119 | 507deedd71df0af02805c10570c913f1ea3e8ad1 | bigcode/the-stack | train |
1c6d1b93e2469399c71f1603 | train | function | def squeezeCoeffIdxOnce(coeff_ptrs_layer, chunks, array_w, in_len):
# chunks: [out_channel_start, out_chanel_end+1]
assert max(chunks) >= len(coeff_ptrs_layer)
# keep track of pruning performance
tot_pruned = 0
tot_rounds = 0
sq_ptrs = []
for chunk_idx in range(len(chunks) - 1):
as... | def squeezeCoeffIdxOnce(coeff_ptrs_layer, chunks, array_w, in_len):
# chunks: [out_channel_start, out_chanel_end+1]
| assert max(chunks) >= len(coeff_ptrs_layer)
# keep track of pruning performance
tot_pruned = 0
tot_rounds = 0
sq_ptrs = []
for chunk_idx in range(len(chunks) - 1):
assert array_w >= (chunks[chunk_idx + 1] - chunks[chunk_idx]), "Issue: {} vs {}".format(chunks[chunk_idx + 1], chunks[chun... | Score for layer {}: {}".format(layerIdx, tot_pruned / (max_len*num_fold)))
return sq_ptrs
# return squeezed list of array_w-wide array for a single layer
def squeezeCoeffIdxOnce(coeff_ptrs_layer, chunks, array_w, in_len):
# chunks: [out_channel_start, out_chanel_end+1]
| 74 | 74 | 247 | 34 | 39 | Rudedaisy/SCALE-Sim | OLDloadData.py | Python | squeezeCoeffIdxOnce | squeezeCoeffIdxOnce | 93 | 116 | 93 | 94 | c65482ff8cccac980fbb7ff0610d337c5713511f | bigcode/the-stack | train |
914309724274bd998871263b | train | function | def loadCoeffIdx(pathName):
# Intermediate feature map for layer 'l' format expected: [h][w][bases][input_channel]
# [layer][output_channel] = [basis*num_input_channels + input_channel]
data = torch.load(pathName)
widths = [3] # first input channel width in VGG16
widths.extend(data['width'])
coe... | def loadCoeffIdx(pathName):
# Intermediate feature map for layer 'l' format expected: [h][w][bases][input_channel]
# [layer][output_channel] = [basis*num_input_channels + input_channel]
| data = torch.load(pathName)
widths = [3] # first input channel width in VGG16
widths.extend(data['width'])
coeff_ptrs = []
for layer_idx, layer in enumerate(data['indices']):
coeff_ptrs.append([])
coeff_ptrs[layer_idx] = [[] for _ in range(widths[layer_idx + 1])]
for c in lay... | File: loadData.py
# Author: Edward Hanson (eth20@duke.edu)
import torch
import numpy as np
import math
from tqdm import tqdm
from copy import deepcopy
CHECK = 4
def loadCoeffIdx(pathName):
# Intermediate feature map for layer 'l' format expected: [h][w][bases][input_channel]
# [layer][output_channel] = [... | 95 | 95 | 319 | 48 | 46 | Rudedaisy/SCALE-Sim | OLDloadData.py | Python | loadCoeffIdx | loadCoeffIdx | 12 | 39 | 12 | 14 | a77ae086ae13658872626ba1638eacae2586d6ba | bigcode/the-stack | train |
4c7090354a45aa760f1a2f7b | train | function | def squeezeCoeffIdxOLD(coeff_ptrs_layer, array_w, numBases, layerIdx, pathName):
data = torch.load(pathName)
widths = [3] # first input channel width in VGG16
widths.extend(data['width'])
sq_ptrs = []
num_fold = math.ceil(len(coeff_ptrs_layer) / array_w)
max_len = numBases * widths[layerIdx... | def squeezeCoeffIdxOLD(coeff_ptrs_layer, array_w, numBases, layerIdx, pathName):
| data = torch.load(pathName)
widths = [3] # first input channel width in VGG16
widths.extend(data['width'])
sq_ptrs = []
num_fold = math.ceil(len(coeff_ptrs_layer) / array_w)
max_len = numBases * widths[layerIdx]
# internal counter just for information
tot_pruned = 0
nonzero_row... | check = 5
numBases = 5
for idx, layer in enumerate(coeff_ptrs):
tot_in = widths[idx] * numBases
taken = [0 for _ in range(tot_in)]
for out_channel in layer:
for c in out_channel:
taken[c] += 1
print("Layer {} -- {} % of in_channels*B are used great... | 156 | 156 | 522 | 22 | 133 | Rudedaisy/SCALE-Sim | OLDloadData.py | Python | squeezeCoeffIdxOLD | squeezeCoeffIdxOLD | 42 | 90 | 42 | 42 | 2fdfd351ab5ed051cd6282a15f52a6ca842e69ff | bigcode/the-stack | train |
1baa1bbe657edf22ea66e21b | train | class | class Subtype(object):
"""Subtype information about tokens.
Gleaned from parsing the code. Helps determine the best formatting.
"""
NONE = 0
UNARY_OPERATOR = 1
BINARY_OPERATOR = 2
SUBSCRIPT_COLON = 3
SUBSCRIPT_BRACKET = 4
DEFAULT_OR_NAMED_ASSIGN = 5
DEFAULT_OR_NAMED_ASSIGN_ARG_LIST = 6
VARARGS_LI... | class Subtype(object):
| """Subtype information about tokens.
Gleaned from parsing the code. Helps determine the best formatting.
"""
NONE = 0
UNARY_OPERATOR = 1
BINARY_OPERATOR = 2
SUBSCRIPT_COLON = 3
SUBSCRIPT_BRACKET = 4
DEFAULT_OR_NAMED_ASSIGN = 5
DEFAULT_OR_NAMED_ASSIGN_ARG_LIST = 6
VARARGS_LIST = 7
VARARGS_STAR =... | .pgen2 import token
from yapf.yapflib import py3compat
from yapf.yapflib import pytree_utils
from yapf.yapflib import style
CONTINUATION = token.N_TOKENS
token.N_TOKENS += 1
class Subtype(object):
| 64 | 64 | 193 | 5 | 58 | bouweandela/yapf | yapf/yapflib/format_token.py | Python | Subtype | Subtype | 32 | 55 | 32 | 32 | 739e6bab2d6ba7acb205b2e26541c236a8c94dfc | bigcode/the-stack | train |
1c499b4380bc06e71be4d626 | train | class | class FormatToken(object):
"""A wrapper around pytree Leaf nodes.
This represents the token plus additional information useful for reformatting
the code.
Attributes:
next_token: The token in the unwrapped line after this token or None if this
is the last token in the unwrapped line.
previous_tok... | class FormatToken(object):
| """A wrapper around pytree Leaf nodes.
This represents the token plus additional information useful for reformatting
the code.
Attributes:
next_token: The token in the unwrapped line after this token or None if this
is the last token in the unwrapped line.
previous_token: The token in the unwrap... | gen2 import token
from yapf.yapflib import py3compat
from yapf.yapflib import pytree_utils
from yapf.yapflib import style
CONTINUATION = token.N_TOKENS
token.N_TOKENS += 1
class Subtype(object):
"""Subtype information about tokens.
Gleaned from parsing the code. Helps determine the best formatting.
"""
NON... | 256 | 256 | 1,806 | 5 | 250 | bouweandela/yapf | yapf/yapflib/format_token.py | Python | FormatToken | FormatToken | 58 | 283 | 58 | 58 | 062ff36d4d2f318ec6c4b891d8af9bce63741b31 | bigcode/the-stack | train |
e8781c8de7ffc393faa2d13f | train | class | class ConfigObject(object):
"""
An object that holds various configuration settings that
are used throughout crestdsl.
"""
approx: int = 100
"""precision for when we have to round z3's fractions to actual numbers"""
use_integer_and_real:bool = True
"""Should we replace Python's int... | class ConfigObject(object):
| """
An object that holds various configuration settings that
are used throughout crestdsl.
"""
approx: int = 100
"""precision for when we have to round z3's fractions to actual numbers"""
use_integer_and_real:bool = True
"""Should we replace Python's int and float with Z3's Integer... | import logging # basic loggingconfig
logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger(__name__)
# only export config, by default
__all__ = ['config']
class ConfigObject(object):
| 43 | 153 | 510 | 5 | 38 | stklik/CREST | crestdsl/config.py | Python | ConfigObject | ConfigObject | 8 | 75 | 8 | 8 | e10f27f25d01dfde77087f62970ce61ef53e363b | bigcode/the-stack | train |
6e1b854bd3ed3f32cc1b1259 | train | function | def to_python(some_number):
if isinstance(some_number, numbers.Number):
return some_number
some_number = z3.simplify(some_number)
if z3.is_algebraic_value(some_number):
some_number = some_number.approx(config.approx)
if z3.is_int_value(some_number):
return some_number.as_long()... | def to_python(some_number):
| if isinstance(some_number, numbers.Number):
return some_number
some_number = z3.simplify(some_number)
if z3.is_algebraic_value(some_number):
some_number = some_number.approx(config.approx)
if z3.is_int_value(some_number):
return some_number.as_long()
else:
try:
... | access the properties.
.. seealso:: :class:`crestdsl.config.ConfigObject`
"""
import numbers
try:
import z3
except ModuleNotFoundError:
logger.warning("There was a problem when importing z3. Please make sure it is correctly installed")
def to_python(some_number):
| 64 | 64 | 125 | 7 | 57 | stklik/CREST | crestdsl/config.py | Python | to_python | to_python | 95 | 109 | 95 | 95 | fe91b9ff5112c67054e8096a9c6ca94a4bcc1b39 | bigcode/the-stack | train |
6d18055b0b2176306ab2d378 | train | class | class CarscenesDataset(Dataset):
def __init__(self, padded_voxel_points_example, label_one_hot_example, reg_target_example, reg_loss_mask_example,
anchors_map_example, \
motion_one_hot_example, motion_mask_example, vis_maps_example, dataset_root=None, config=None,
... | class CarscenesDataset(Dataset):
| def __init__(self, padded_voxel_points_example, label_one_hot_example, reg_target_example, reg_loss_mask_example,
anchors_map_example, \
motion_one_hot_example, motion_mask_example, vis_maps_example, dataset_root=None, config=None,
config_global=None, agent_list =... | = np.swapaxes(vis_maps,2,3)
vis_maps = np.transpose(vis_maps,(0,2,3,1))
for v_id in range(vis_maps.shape[0]):
vis_maps[v_id] = np.rot90(vis_maps[v_id],3)
vis_maps = vis_maps[-1]
else:
vis_maps = np.zeros(0)
padded_voxel_points = ... | 256 | 256 | 5,231 | 7 | 248 | Chezacar/CollaborationWithLatency | pairwise_fast/pairwise_fusion_kd/data/Dataset_com.py | Python | CarscenesDataset | CarscenesDataset | 206 | 584 | 206 | 206 | dd0228f873eeb8e4191a22ab015fc93938edefc2 | bigcode/the-stack | train |
fd40671aca20bbeede4d155e | train | class | class NuscenesDataset(Dataset):
def __init__(self, dataset_root=None, config=None,split=None,cache_size=10000,val=False):
"""
This dataloader loads single sequence for a keyframe, and is not designed for computing the
spatio-temporal consistency losses. It supports train, val and test split... | class NuscenesDataset(Dataset):
| def __init__(self, dataset_root=None, config=None,split=None,cache_size=10000,val=False):
"""
This dataloader loads single sequence for a keyframe, and is not designed for computing the
spatio-temporal consistency losses. It supports train, val and test splits.
dataset_root: Data p... | from data.obj_util import *
from torch.utils.data import Dataset
import numpy as np
import os
import warnings
import torch
import torch.multiprocessing
from multiprocessing import Manager
from data.config_com import Config, ConfigGlobal
from matplotlib import pyplot as plt
import cv2
class NuscenesDataset(Dataset):
| 66 | 256 | 2,272 | 7 | 58 | Chezacar/CollaborationWithLatency | pairwise_fast/pairwise_fusion_kd/data/Dataset_com.py | Python | NuscenesDataset | NuscenesDataset | 13 | 204 | 13 | 13 | 4d81cf77ab1d0fdcead298b8fe9fea0110282fe6 | bigcode/the-stack | train |
40c9448891a9edd5a7aedf05 | train | function | def parse_args():
parser = argparse.ArgumentParser(description="WebSocket Simple Dump Tool")
parser.add_argument("url", metavar="ws_url",
help="websocket url. ex. ws://echo.websocket.org/")
parser.add_argument("-p", "--proxy",
help="proxy url. ex. http://127.0... | def parse_args():
| parser = argparse.ArgumentParser(description="WebSocket Simple Dump Tool")
parser.add_argument("url", metavar="ws_url",
help="websocket url. ex. ws://echo.websocket.org/")
parser.add_argument("-p", "--proxy",
help="proxy url. ex. http://127.0.0.1:8080")
pa... | websocket.ABNF.OPCODE_BINARY)
ENCODING = get_encoding()
class VAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
if values==None:
values = "1"
try:
values = int(values)
except ValueError:
values = values.count("v")+1... | 88 | 88 | 294 | 4 | 84 | thormodsen/starter-python-bot | bin/wsdump.py | Python | parse_args | parse_args | 39 | 64 | 39 | 39 | b2975bed4a9d32f50d7a8e670529f434f00afb25 | bigcode/the-stack | train |
ac4b24e8e59623c4a454c177 | train | class | class VAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
if values==None:
values = "1"
try:
values = int(values)
except ValueError:
values = values.count("v")+1
setattr(args, self.dest, values)
| class VAction(argparse.Action):
| def __call__(self, parser, args, values, option_string=None):
if values==None:
values = "1"
try:
values = int(values)
except ValueError:
values = values.count("v")+1
setattr(args, self.dest, values)
| getattr(sys.stdin, "encoding", "")
if not encoding:
return "utf-8"
else:
return encoding.lower()
OPCODE_DATA = (websocket.ABNF.OPCODE_TEXT, websocket.ABNF.OPCODE_BINARY)
ENCODING = get_encoding()
class VAction(argparse.Action):
| 64 | 64 | 69 | 7 | 57 | thormodsen/starter-python-bot | bin/wsdump.py | Python | VAction | VAction | 29 | 37 | 29 | 29 | f3f98b5a632cc244dde7dfd0a592e1fe9249f92e | bigcode/the-stack | train |
72a88dd21226f416ee8b176a | train | class | class RawInput():
def raw_input(self, prompt):
if six.PY3:
line = input(prompt)
else:
line = raw_input(prompt)
if ENCODING and ENCODING != "utf-8" and not isinstance(line, six.text_type):
line = line.decode(ENCODING).encode("utf-8")
elif isinstanc... | class RawInput():
| def raw_input(self, prompt):
if six.PY3:
line = input(prompt)
else:
line = raw_input(prompt)
if ENCODING and ENCODING != "utf-8" and not isinstance(line, six.text_type):
line = line.decode(ENCODING).encode("utf-8")
elif isinstance(line, six.text_t... | type=int,
help="wait time(second) after 'EOF' received.")
parser.add_argument("-t", "--text",
help="Send initial text")
parser.add_argument("--timings", action="store_true",
help="Print timings in seconds")
return parser.parse_args()
... | 64 | 64 | 98 | 4 | 60 | thormodsen/starter-python-bot | bin/wsdump.py | Python | RawInput | RawInput | 66 | 78 | 66 | 66 | a50a59c8b34b0c29b19b3cbc06bb5b0b096a63b7 | bigcode/the-stack | train |
798b67f583d1ce3714326625 | train | function | def get_encoding():
encoding = getattr(sys.stdin, "encoding", "")
if not encoding:
return "utf-8"
else:
return encoding.lower()
| def get_encoding():
| encoding = getattr(sys.stdin, "encoding", "")
if not encoding:
return "utf-8"
else:
return encoding.lower()
| /pedrothormodsen/dev/bots/starter-python-bot/bin/python
import argparse
import code
import six
import sys
import threading
import time
import websocket
from six.moves.urllib.parse import urlparse
try:
import readline
except:
pass
def get_encoding():
| 64 | 64 | 35 | 4 | 59 | thormodsen/starter-python-bot | bin/wsdump.py | Python | get_encoding | get_encoding | 17 | 22 | 17 | 17 | ea05e69649ea14f7dfc9d848f7be280ba88049e2 | bigcode/the-stack | train |
189b34c09ed86e27e83a0c00 | train | class | class InteractiveConsole(RawInput, code.InteractiveConsole):
def write(self, data):
sys.stdout.write("\033[2K\033[E")
# sys.stdout.write("\n")
sys.stdout.write("\033[34m< " + data + "\033[39m")
sys.stdout.write("\n> ")
sys.stdout.flush()
def read(self):
return se... | class InteractiveConsole(RawInput, code.InteractiveConsole):
| def write(self, data):
sys.stdout.write("\033[2K\033[E")
# sys.stdout.write("\n")
sys.stdout.write("\033[34m< " + data + "\033[39m")
sys.stdout.write("\n> ")
sys.stdout.flush()
def read(self):
return self.raw_input("> ")
| utf-8" and not isinstance(line, six.text_type):
line = line.decode(ENCODING).encode("utf-8")
elif isinstance(line, six.text_type):
line = line.encode("utf-8")
return line
class InteractiveConsole(RawInput, code.InteractiveConsole):
| 64 | 64 | 85 | 12 | 51 | thormodsen/starter-python-bot | bin/wsdump.py | Python | InteractiveConsole | InteractiveConsole | 80 | 89 | 80 | 80 | 5f8138a884dc4371c9a210f0a0b92aca411f3c21 | bigcode/the-stack | train |
2cbe7906919a67bb08e7b37f | train | class | class NonInteractive(RawInput):
def write(self, data):
sys.stdout.write(data)
sys.stdout.write("\n")
sys.stdout.flush()
def read(self):
return self.raw_input("")
| class NonInteractive(RawInput):
| def write(self, data):
sys.stdout.write(data)
sys.stdout.write("\n")
sys.stdout.flush()
def read(self):
return self.raw_input("")
| \033[E")
# sys.stdout.write("\n")
sys.stdout.write("\033[34m< " + data + "\033[39m")
sys.stdout.write("\n> ")
sys.stdout.flush()
def read(self):
return self.raw_input("> ")
class NonInteractive(RawInput):
| 64 | 64 | 43 | 7 | 57 | thormodsen/starter-python-bot | bin/wsdump.py | Python | NonInteractive | NonInteractive | 91 | 98 | 91 | 91 | 09a0f300209a52aba9e839e9621a566734bb8f2f | bigcode/the-stack | train |
1c5b8742d9a8e0acd593b39a | train | function | def main():
start_time = time.time()
args = parse_args()
if args.verbose > 1:
websocket.enableTrace(True)
options = {}
if (args.proxy):
p = urlparse(args.proxy)
options["http_proxy_host"] = p.hostname
options["http_proxy_port"] = p.port
if (args.origin):
o... | def main():
| start_time = time.time()
args = parse_args()
if args.verbose > 1:
websocket.enableTrace(True)
options = {}
if (args.proxy):
p = urlparse(args.proxy)
options["http_proxy_host"] = p.hostname
options["http_proxy_port"] = p.port
if (args.origin):
options["orig... | .decode(ENCODING).encode("utf-8")
elif isinstance(line, six.text_type):
line = line.encode("utf-8")
return line
class InteractiveConsole(RawInput, code.InteractiveConsole):
def write(self, data):
sys.stdout.write("\033[2K\033[E")
# sys.stdout.write("\n")
sys.std... | 166 | 167 | 559 | 3 | 163 | thormodsen/starter-python-bot | bin/wsdump.py | Python | main | main | 100 | 178 | 100 | 100 | 3f75abaa1f53486354d0c1d9fbe13b3f8d84d32f | bigcode/the-stack | train |
56078c729fc23011cfa99203 | train | class | class CardUpdateForm(forms.ModelForm):
class Meta:
model = Nav_cards
fields = ['heading','Summary']
| class CardUpdateForm(forms.ModelForm):
| class Meta:
model = Nav_cards
fields = ['heading','Summary']
| from django import forms
from django.contrib.auth.models import User
from .models import Nav_cards
class CardUpdateForm(forms.ModelForm):
| 28 | 64 | 26 | 8 | 19 | foo290/My-protfolio-website | landing_page/forms.py | Python | CardUpdateForm | CardUpdateForm | 7 | 12 | 7 | 8 | f22ef288f0aa7ae8da32c8aae40efc611008ae58 | bigcode/the-stack | train |
318989408337d1c8bbc836df | train | function | def logger(method: F) -> F:
"""For non-memoized functions that we want to be logged.
(In practice this is only non-leader left-recursive functions.)
"""
method_name = method.__name__
def logger_wrapper(self: P, *args: object) -> T:
if not self._verbose:
return method(self, *arg... | def logger(method: F) -> F:
| """For non-memoized functions that we want to be logged.
(In practice this is only non-leader left-recursive functions.)
"""
method_name = method.__name__
def logger_wrapper(self: P, *args: object) -> T:
if not self._verbose:
return method(self, *args)
argsr = ",".join(... | typing import Any, Callable, cast, ClassVar, Dict, Optional, Set, Tuple, Type, TypeVar
T = TypeVar("T")
P = TypeVar("P", bound="Parser")
F = TypeVar("F", bound=Callable[..., Any])
def logger(method: F) -> F:
| 64 | 64 | 205 | 9 | 55 | zeaphoo/markpy | packages/pegparser/pegparser/parser.py | Python | logger | logger | 14 | 34 | 14 | 14 | 0082f533f08cbe30df1abad564284b42ab66ccf4 | bigcode/the-stack | train |
cc6777c621de36c8fbef7f38 | train | class | class PegParser:
def __init__(self, tokenizer):
self.tokenizer = tokenizer
self.memos = {}
def mark(self):
return self.tokenizer.mark()
def reset(self, pos):
self.tokenizer.reset(pos)
def show_rule(self, name, alts):
# alts is a list of lists of strings
... | class PegParser:
| def __init__(self, tokenizer):
self.tokenizer = tokenizer
self.memos = {}
def mark(self):
return self.tokenizer.mark()
def reset(self, pos):
self.tokenizer.reset(pos)
def show_rule(self, name, alts):
# alts is a list of lists of strings
vis = self.token... | , reach
else:
tree, endmark, reach = self._cache[key]
if verbose:
print(f"{fill}{method_name}() -> {tree!s:.200} [fresh]")
if tree:
self.reset(endmark)
return tree
memoize_left_rec_wrapper.__wrapped__ = method # type: ignore
r... | 87 | 87 | 290 | 4 | 82 | zeaphoo/markpy | packages/pegparser/pegparser/parser.py | Python | PegParser | PegParser | 162 | 206 | 162 | 162 | f31cae65f76360a6361a2fc7d3809b31ebcafc10 | bigcode/the-stack | train |
193e353b13898e094c2bf325 | train | function | def memoize(method: F) -> F:
"""Memoize a symbol method."""
method_name = method.__name__
def memoize_wrapper(self: P, *args: object) -> T:
mark = self.mark()
key = mark, method_name, args
# Fast path: cache hit, and not verbose.
if key in self._cache and not self._verbose:
... | def memoize(method: F) -> F:
| """Memoize a symbol method."""
method_name = method.__name__
def memoize_wrapper(self: P, *args: object) -> T:
mark = self.mark()
key = mark, method_name, args
# Fast path: cache hit, and not verbose.
if key in self._cache and not self._verbose:
tree, endmark, re... | " * self._level
print(f"{fill}{method_name}({argsr}) .... (looking at {self.showpeek()})")
self._level += 1
tree = method(self, *args)
self._level -= 1
print(f"{fill}... {method_name}({argsr}) --> {tree!s:.200}")
return tree
logger_wrapper.__wrapped__ = method # t... | 115 | 115 | 385 | 10 | 105 | zeaphoo/markpy | packages/pegparser/pegparser/parser.py | Python | memoize | memoize | 37 | 76 | 37 | 37 | 41d51dd57105371343137f15b0b1a0e56963cd48 | bigcode/the-stack | train |
5fad92db4cda4be531b2de04 | train | function | def memoize_left_rec(method: Callable[[P], Optional[T]]) -> Callable[[P], Optional[T]]:
"""Memoize a left-recursive symbol method."""
method_name = method.__name__
def memoize_left_rec_wrapper(self: P) -> Optional[T]:
mark = self.mark()
key = mark, method_name, ()
# Fast path: cache... | def memoize_left_rec(method: Callable[[P], Optional[T]]) -> Callable[[P], Optional[T]]:
| """Memoize a left-recursive symbol method."""
method_name = method.__name__
def memoize_left_rec_wrapper(self: P) -> Optional[T]:
mark = self.mark()
key = mark, method_name, ()
# Fast path: cache hit, and not verbose.
if key in self._cache and not self._verbose:
... | r}) ... (looking at {self.showpeek()})")
self._level += 1
prior_reach = self.reset_reach(mark)
tree = method(self, *args)
reach = self.reset_reach(prior_reach)
self.update_reach(reach)
self._level -= 1
if verbose:
print(... | 222 | 222 | 742 | 22 | 200 | zeaphoo/markpy | packages/pegparser/pegparser/parser.py | Python | memoize_left_rec | memoize_left_rec | 79 | 159 | 79 | 79 | 38966e721c63f5a1db4094bd07b769aa553bc78a | bigcode/the-stack | train |
8e022f18b88202dba7f5ec17 | train | class | class AuthorDelete(LoginRequiredMixin, DeleteView):
model = Author
success_url = reverse_lazy('authors')
| class AuthorDelete(LoginRequiredMixin, DeleteView):
| model = Author
success_url = reverse_lazy('authors')
| _death']
initial = {'date_of_death': '11/06/2020'}
class AuthorUpdate(LoginRequiredMixin, UpdateView):
model = Author
fields = '__all__' # Not recommended (potential security issue if more fields added)
class AuthorDelete(LoginRequiredMixin, DeleteView):
| 64 | 64 | 24 | 10 | 54 | tindi-plus/Local_Library | locallibrary/catalog/views.py | Python | AuthorDelete | AuthorDelete | 230 | 232 | 230 | 230 | b87d72e2184b8f3ff5f36834e79cf4b469124edd | bigcode/the-stack | train |
e67c2a53a857ac732b8d5437 | train | class | class AuthorDetailView(LoginRequiredMixin, DetailView):
"""
Generates a detail view of authors in the database. It extends Django's generic view DetailView
which does most of the work of retrieving the data and displaying using the appropriate
templates.
Args:
DetailView (Generic View): D... | class AuthorDetailView(LoginRequiredMixin, DetailView):
| """
Generates a detail view of authors in the database. It extends Django's generic view DetailView
which does most of the work of retrieving the data and displaying using the appropriate
templates.
Args:
DetailView (Generic View): Django's generic view for displaying the details of model... |
model = Author
# paginate enables the list view to fetch a certain number of records per page. This is
# useful when the records are plenty and it is not possible to display all in one page.
paginate_by = 4
class AuthorDetailView(LoginRequiredMixin, DetailView):
| 64 | 64 | 112 | 11 | 52 | tindi-plus/Local_Library | locallibrary/catalog/views.py | Python | AuthorDetailView | AuthorDetailView | 114 | 128 | 114 | 114 | 5f8aa3097a50756524ddb8e9281cbcb5c2cfeb5d | bigcode/the-stack | train |
b67d24ae4d908dabf24b4d7d | train | function | @login_required
@permission_required('catalog.can_mark_returned', raise_exception=True)
def renew_book_librarian(request, pk):
"""
A function for renewing the due_date of a book.
"""
book_instance = get_object_or_404(BookInstance, pk=pk)
# if this is a post request, then process the re... | @login_required
@permission_required('catalog.can_mark_returned', raise_exception=True)
def renew_book_librarian(request, pk):
| """
A function for renewing the due_date of a book.
"""
book_instance = get_object_or_404(BookInstance, pk=pk)
# if this is a post request, then process the request
if request.method == 'POST':
# create a form instance and populate it with data from the request
for... |
def get_queryset(self):
"""Gets a list all books instances that have been borrowed with the borrower
field not null or empty.
"""
return BookInstance.objects.exclude(borrower__isnull=True).order_by('borrower')
@login_required
@permission_required('catalog.can_mark_returned', ra... | 79 | 79 | 266 | 27 | 52 | tindi-plus/Local_Library | locallibrary/catalog/views.py | Python | renew_book_librarian | renew_book_librarian | 185 | 215 | 185 | 187 | 1a298c9dd154be365c4f62dbe7ac12d9d1bb7118 | bigcode/the-stack | train |
aee31d338a57fef49867419c | train | class | class BookListView(LoginRequiredMixin, ListView):
"""
Generates a list all books in the database. It extends Django's generic view ListView
which does most of the work of retrieving the data and displaying using the appropriate
templates.
Args:
ListView (Generic View): Django's generic vi... | class BookListView(LoginRequiredMixin, ListView):
| """
Generates a list all books in the database. It extends Django's generic view ListView
which does most of the work of retrieving the data and displaying using the appropriate
templates.
Args:
ListView (Generic View): Django's generic view for displaying a list of model
objects.... | _books,
'num_genre': num_genre,
'num_visits': num_visits
}
# Render the HTML template index.html with the data in the context variable
return render(request, 'catalog/index.html', context=context)
class BookListView(LoginRequiredMixin, ListView):
| 64 | 64 | 158 | 11 | 53 | tindi-plus/Local_Library | locallibrary/catalog/views.py | Python | BookListView | BookListView | 57 | 75 | 57 | 57 | 5b40793be95c97adfcf49d6453cfc31da8eda8f6 | bigcode/the-stack | train |
f40e9c816fc12d6f4ad5234b | train | class | class BookDetailView(LoginRequiredMixin, DetailView):
"""
Generates a detail view of books in the database. It extends Django's generic view DetailView
which does most of the work of retrieving the data and displaying using the appropriate
templates.
Args:
DetailView (Generic View): Djang... | class BookDetailView(LoginRequiredMixin, DetailView):
| """
Generates a detail view of books in the database. It extends Django's generic view DetailView
which does most of the work of retrieving the data and displaying using the appropriate
templates.
Args:
DetailView (Generic View): Django's generic view for displaying the details of model
... |
model = Book
# paginate enables the list view to fetch a certain number of records per page. This is
# useful when the records are plenty and it is not possible to display all in one page.
paginate_by = 3
class BookDetailView(LoginRequiredMixin, DetailView):
| 64 | 64 | 112 | 11 | 52 | tindi-plus/Local_Library | locallibrary/catalog/views.py | Python | BookDetailView | BookDetailView | 78 | 92 | 78 | 78 | e3546fa2b21f7d81d266e869d285c4cd23c66771 | bigcode/the-stack | train |
170a8aeb87e2af9a36d0e24d | train | class | class BookDelete(LoginRequiredMixin, DeleteView):
model = Book
success_url = reverse_lazy('books')
| class BookDelete(LoginRequiredMixin, DeleteView):
| model = Book
success_url = reverse_lazy('books')
| success_url = reverse_lazy('authors')
class BookCreate(LoginRequiredMixin, CreateView):
model = Book
fields = '__all__'
class BookUpdate(LoginRequiredMixin, UpdateView):
model = Book
fields = '__all__'
class BookDelete(LoginRequiredMixin, DeleteView):
| 63 | 64 | 24 | 10 | 53 | tindi-plus/Local_Library | locallibrary/catalog/views.py | Python | BookDelete | BookDelete | 242 | 244 | 242 | 242 | 666f96e4787a862c841595a26ccc1bd76d926834 | bigcode/the-stack | train |
e6f81f9dc2f1febb4d81c7ca | train | class | class AuthorListView(LoginRequiredMixin, ListView):
"""
Generates a list all authors in the database. It extends Django's generic view ListView
which does most of the work of retrieving the data and displaying using the appropriate
templates.
Args:
ListView (Generic View): Django's generi... | class AuthorListView(LoginRequiredMixin, ListView):
| """
Generates a list all authors in the database. It extends Django's generic view ListView
which does most of the work of retrieving the data and displaying using the appropriate
templates.
Args:
ListView (Generic View): Django's generic view for displaying a list of model
object... | (Generic View): Django's generic view for displaying the details of model
objects.
Returns:
Returns the details of an object of the specified model. The list is rendered in
a HTML view.
"""
model = Book
class AuthorListView(LoginRequiredMixin, ListView):
| 64 | 64 | 158 | 11 | 52 | tindi-plus/Local_Library | locallibrary/catalog/views.py | Python | AuthorListView | AuthorListView | 94 | 112 | 94 | 94 | 8dc82d7907787084e0c55da65e18ad8a503f16d4 | bigcode/the-stack | train |
3525c3b4b80452b023bd6c43 | train | function | @login_required(login_url='/accounts/login')
def index(request):
"""
This is a view for the home page of the catalog app. It renders all the information
that is displayed on the home page.
Args:
request (HTTP):
Returns:
html that is displayed to the end-user.
"""
# get... | @login_required(login_url='/accounts/login')
def index(request):
| """
This is a view for the home page of the catalog app. It renders all the information
that is displayed on the home page.
Args:
request (HTTP):
Returns:
html that is displayed to the end-user.
"""
# get the count of most of the items
num_books = Book.objects.all(... | from django.shortcuts import render, get_object_or_404
from .models import Book, Author, BookInstance, Language, Genre
from django.views.generic import ListView, DetailView
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
from django.contrib.auth.decorators import login_required, permi... | 102 | 102 | 341 | 12 | 89 | tindi-plus/Local_Library | locallibrary/catalog/views.py | Python | index | index | 13 | 55 | 13 | 14 | 248c16f2b9fbafdd6c50ee7b46dcbe6be6fda553 | bigcode/the-stack | train |
995520f0dd0aca6e92af5d02 | train | class | class BookCreate(LoginRequiredMixin, CreateView):
model = Book
fields = '__all__'
| class BookCreate(LoginRequiredMixin, CreateView):
| model = Book
fields = '__all__'
| RequiredMixin, UpdateView):
model = Author
fields = '__all__' # Not recommended (potential security issue if more fields added)
class AuthorDelete(LoginRequiredMixin, DeleteView):
model = Author
success_url = reverse_lazy('authors')
class BookCreate(LoginRequiredMixin, CreateView):
| 64 | 64 | 22 | 10 | 54 | tindi-plus/Local_Library | locallibrary/catalog/views.py | Python | BookCreate | BookCreate | 234 | 236 | 234 | 234 | 4de62f06b31fa75cd359e0ffaeb872ed73df643c | bigcode/the-stack | train |
83fbc899b20ae65fd1931981 | train | class | class AuthorCreate(LoginRequiredMixin, CreateView):
model = Author
fields = ['first_name', 'last_name', 'date_of_birth', 'date_of_death']
initial = {'date_of_death': '11/06/2020'}
| class AuthorCreate(LoginRequiredMixin, CreateView):
| model = Author
fields = ['first_name', 'last_name', 'date_of_birth', 'date_of_death']
initial = {'date_of_death': '11/06/2020'}
| form': form,
'book_instance': book_instance
}
return render(request, 'catalog/book_renew_librarian.html', context=context)
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
class AuthorCreate(LoginRequiredMixin, CreateView):... | 64 | 64 | 54 | 10 | 53 | tindi-plus/Local_Library | locallibrary/catalog/views.py | Python | AuthorCreate | AuthorCreate | 221 | 224 | 221 | 221 | e3360262b95a76b1f88bcb0544bfd60f067572c0 | bigcode/the-stack | train |
0e1550d05922b9cfc0b1b24b | train | class | class AllBorrowedBooks(PermissionRequiredMixin, ListView):
"""
Generates a list of all books instances borrowed by all users. It extends Django's generic view ListView
which does most of the work of retrieving the data and displaying using the appropriate
templates.
Args:
ListView (Generi... | class AllBorrowedBooks(PermissionRequiredMixin, ListView):
| """
Generates a list of all books instances borrowed by all users. It extends Django's generic view ListView
which does most of the work of retrieving the data and displaying using the appropriate
templates.
Args:
ListView (Generic View): Django's generic view for displaying a list of mod... | = 10
def get_queryset(self):
"""
Get list of books on loan to user
"""
return BookInstance.objects.filter(borrower=self.request.user).filter(status__exact='o').order_by('due_back')
class AllBorrowedBooks(PermissionRequiredMixin, ListView):
| 63 | 65 | 219 | 13 | 50 | tindi-plus/Local_Library | locallibrary/catalog/views.py | Python | AllBorrowedBooks | AllBorrowedBooks | 157 | 182 | 157 | 157 | 89c28a516f5fdd25d6ad0b14559e4a141c04fd75 | bigcode/the-stack | train |
7f83fe6f0ae079f0a8845785 | train | class | class AuthorUpdate(LoginRequiredMixin, UpdateView):
model = Author
fields = '__all__' # Not recommended (potential security issue if more fields added)
| class AuthorUpdate(LoginRequiredMixin, UpdateView):
| model = Author
fields = '__all__' # Not recommended (potential security issue if more fields added)
| class AuthorCreate(LoginRequiredMixin, CreateView):
model = Author
fields = ['first_name', 'last_name', 'date_of_birth', 'date_of_death']
initial = {'date_of_death': '11/06/2020'}
class AuthorUpdate(LoginRequiredMixin, UpdateView):
| 64 | 64 | 34 | 10 | 54 | tindi-plus/Local_Library | locallibrary/catalog/views.py | Python | AuthorUpdate | AuthorUpdate | 226 | 228 | 226 | 226 | 6df3ef93ddf9b0a44c827239d442061efeb1dc16 | bigcode/the-stack | train |
9b93ce5c09b906e1dd47064f | train | class | class LoanedBooksByUserListView(LoginRequiredMixin, ListView):
"""
Generates a list of all books instances borrowed by the user. It extends Django's generic view ListView
which does most of the work of retrieving the data and displaying using the appropriate
templates.
Args:
ListView (Gen... | class LoanedBooksByUserListView(LoginRequiredMixin, ListView):
| """
Generates a list of all books instances borrowed by the user. It extends Django's generic view ListView
which does most of the work of retrieving the data and displaying using the appropriate
templates.
Args:
ListView (Generic View): Django's generic view for displaying a list of mode... | Django's generic view for displaying the details of model
objects.
Returns:
Returns the details of an object of the specified model. The list is rendered in
a HTML view.
"""
model = Author
class LoanedBooksByUserListView(LoginRequiredMixin, ListView):
| 64 | 64 | 207 | 15 | 48 | tindi-plus/Local_Library | locallibrary/catalog/views.py | Python | LoanedBooksByUserListView | LoanedBooksByUserListView | 130 | 154 | 130 | 130 | cb45effdce8cec902d00b3117dbbd05b4b1b4f9e | bigcode/the-stack | train |
89acc856db289e721f6fb89a | train | class | class BookUpdate(LoginRequiredMixin, UpdateView):
model = Book
fields = '__all__'
| class BookUpdate(LoginRequiredMixin, UpdateView):
| model = Book
fields = '__all__'
| potential security issue if more fields added)
class AuthorDelete(LoginRequiredMixin, DeleteView):
model = Author
success_url = reverse_lazy('authors')
class BookCreate(LoginRequiredMixin, CreateView):
model = Book
fields = '__all__'
class BookUpdate(LoginRequiredMixin, UpdateView):
| 64 | 64 | 22 | 10 | 54 | tindi-plus/Local_Library | locallibrary/catalog/views.py | Python | BookUpdate | BookUpdate | 238 | 240 | 238 | 238 | 33f3f981d7efb9a89981dddfcce222a2640716dc | bigcode/the-stack | train |
85e3c9892f7ab2e5daeb2636 | train | function | def test_gpu_construction(gpu):
assert 5 == len(gpu.remaining_memory.values())
| def test_gpu_construction(gpu):
| assert 5 == len(gpu.remaining_memory.values())
| import pytest
def test_gpu_construction(gpu):
| 11 | 64 | 20 | 8 | 2 | hankyul2/PostImageClassification | tests/test_gpu/test_gpu.py | Python | test_gpu_construction | test_gpu_construction | 4 | 5 | 4 | 4 | f7c3df06ef84b055bfe97590d60910dff304348c | bigcode/the-stack | train |
baa320c1fa1b7095b6aec973 | train | function | @pytest.mark.skip(reason="not implemented yet")
def test_gpu_give_me_maximum_gpu(gpu):
assert False
| @pytest.mark.skip(reason="not implemented yet")
def test_gpu_give_me_maximum_gpu(gpu):
| assert False
| test_gpu_used_memory(gpu):
for gpu_id in range(5):
assert gpu.remaining_memory[gpu_id] + gpu.used_memory[gpu_id] == \
gpu.total_memory[gpu_id]
@pytest.mark.skip(reason="not implemented yet")
def test_gpu_give_me_maximum_gpu(gpu):
| 64 | 64 | 25 | 21 | 43 | hankyul2/PostImageClassification | tests/test_gpu/test_gpu.py | Python | test_gpu_give_me_maximum_gpu | test_gpu_give_me_maximum_gpu | 32 | 34 | 32 | 33 | 1df6c6fcd182ef0997794a422ed3e0c88d34e79a | bigcode/the-stack | train |
be27dc5a7dc06739bf6eb8a0 | train | function | def test_gpu_check_memory(gpu):
for gpu_id in range(5):
if gpu.remaining_memory[gpu_id] > 10 * 1000:
assert gpu.can_use_it(gpu_id, 10)
| def test_gpu_check_memory(gpu):
| for gpu_id in range(5):
if gpu.remaining_memory[gpu_id] > 10 * 1000:
assert gpu.can_use_it(gpu_id, 10)
| 24' == str(exc.value)
def test_gpu_check_minimum(gpu):
with pytest.raises(AssertionError) as exc:
gpu.can_use_it(0, 0)
assert 'memory should be between 1 and 24' == str(exc.value)
def test_gpu_check_memory(gpu):
| 64 | 64 | 47 | 8 | 56 | hankyul2/PostImageClassification | tests/test_gpu/test_gpu.py | Python | test_gpu_check_memory | test_gpu_check_memory | 20 | 23 | 20 | 20 | 8f47fe1fae9b7216b3869762c959674e871c3c63 | bigcode/the-stack | train |
cd3d7ad7c608b2ebd53ffb13 | train | function | def test_gpu_used_memory(gpu):
for gpu_id in range(5):
assert gpu.remaining_memory[gpu_id] + gpu.used_memory[gpu_id] == \
gpu.total_memory[gpu_id]
| def test_gpu_used_memory(gpu):
| for gpu_id in range(5):
assert gpu.remaining_memory[gpu_id] + gpu.used_memory[gpu_id] == \
gpu.total_memory[gpu_id]
| and 24' == str(exc.value)
def test_gpu_check_memory(gpu):
for gpu_id in range(5):
if gpu.remaining_memory[gpu_id] > 10 * 1000:
assert gpu.can_use_it(gpu_id, 10)
def test_gpu_used_memory(gpu):
| 64 | 64 | 44 | 8 | 56 | hankyul2/PostImageClassification | tests/test_gpu/test_gpu.py | Python | test_gpu_used_memory | test_gpu_used_memory | 26 | 29 | 26 | 26 | 61555c948183c8c2fa46ca2a5acf2a9e023f3679 | bigcode/the-stack | train |
a8a22b8972f53856d073a945 | train | function | def test_gpu_check_minimum(gpu):
with pytest.raises(AssertionError) as exc:
gpu.can_use_it(0, 0)
assert 'memory should be between 1 and 24' == str(exc.value)
| def test_gpu_check_minimum(gpu):
| with pytest.raises(AssertionError) as exc:
gpu.can_use_it(0, 0)
assert 'memory should be between 1 and 24' == str(exc.value)
| (gpu.remaining_memory.values())
def test_gpu_check_maximum(gpu):
with pytest.raises(AssertionError) as exc:
gpu.can_use_it(0, 25)
assert 'memory should be between 1 and 24' == str(exc.value)
def test_gpu_check_minimum(gpu):
| 64 | 64 | 49 | 9 | 55 | hankyul2/PostImageClassification | tests/test_gpu/test_gpu.py | Python | test_gpu_check_minimum | test_gpu_check_minimum | 14 | 17 | 14 | 14 | c0e69c0fcd2e1972cb364802a9a28693f37c95f0 | bigcode/the-stack | train |
aac1172bbdc06ece27abd4f0 | train | function | def test_gpu_check_maximum(gpu):
with pytest.raises(AssertionError) as exc:
gpu.can_use_it(0, 25)
assert 'memory should be between 1 and 24' == str(exc.value)
| def test_gpu_check_maximum(gpu):
| with pytest.raises(AssertionError) as exc:
gpu.can_use_it(0, 25)
assert 'memory should be between 1 and 24' == str(exc.value)
| import pytest
def test_gpu_construction(gpu):
assert 5 == len(gpu.remaining_memory.values())
def test_gpu_check_maximum(gpu):
| 32 | 64 | 49 | 9 | 23 | hankyul2/PostImageClassification | tests/test_gpu/test_gpu.py | Python | test_gpu_check_maximum | test_gpu_check_maximum | 8 | 11 | 8 | 8 | 47c497e218273089504c62cdeee6de79f26017be | bigcode/the-stack | train |
d74eece241a54d70f0b40eb1 | train | class | class ECPIX545Platform(_ECPIX5Platform):
device = "LFE5UM5G-45F"
resources = [
*_ECPIX5Platform.resources,
# The IT6613E HDMI transmitter has access to 8 bits per color channel.
Resource("it6613e", 0,
Subsignal("rst", PinsN("N6", dir="o")),
Subsignal("s... | class ECPIX545Platform(_ECPIX5Platform):
| device = "LFE5UM5G-45F"
resources = [
*_ECPIX5Platform.resources,
# The IT6613E HDMI transmitter has access to 8 bits per color channel.
Resource("it6613e", 0,
Subsignal("rst", PinsN("N6", dir="o")),
Subsignal("scl", Pins("C17", dir="io")),
... | """
}
def toolchain_program(self, products, name):
openocd = os.environ.get("OPENOCD", "openocd")
with products.extract("{}-openocd.cfg".format(name), "{}.svf".format(name)) \
as (config_filename, vector_filename):
subprocess.check_call([openocd,
... | 117 | 118 | 394 | 11 | 106 | tdaede/nmigen-boards | nmigen_boards/ecpix5.py | Python | ECPIX545Platform | ECPIX545Platform | 155 | 182 | 155 | 155 | 64e88ac7d73700fa12d89b0a53ef7465cf7b3957 | bigcode/the-stack | train |
39b0a657e2e45d798a10e32a | train | class | class ECPIX585Platform(_ECPIX5Platform):
device = "LFE5UM5G-85F"
resources = [
*_ECPIX5Platform.resources,
# The IT6613E HDMI transmitter has access to 12 bits per color channel. The LFE5UM5G-85F
# has an additional I/O bank which is used to provide the lower 4 bits of each chan... | class ECPIX585Platform(_ECPIX5Platform):
| device = "LFE5UM5G-85F"
resources = [
*_ECPIX5Platform.resources,
# The IT6613E HDMI transmitter has access to 12 bits per color channel. The LFE5UM5G-85F
# has an additional I/O bank which is used to provide the lower 4 bits of each channel.
Resource("it6613e", 0,
... | 10 D9 E8 H5 J4", dir="o")),
),
Subsignal("mclk", Pins("E19", dir="o")),
Subsignal("sck", Pins("D6", dir="o")),
Subsignal("ws", Pins("C6", dir="o")),
Subsignal("i2s", Pins("A6 B6 A5 C5", dir="o")),
Subsignal("int", PinsN("C4", dir="i")),... | 134 | 135 | 453 | 11 | 123 | tdaede/nmigen-boards | nmigen_boards/ecpix5.py | Python | ECPIX585Platform | ECPIX585Platform | 185 | 213 | 185 | 185 | 21cc6877d7fa101c4e05be3bf68704c3f84a0c9c | bigcode/the-stack | train |
d1dc01d0773089863cba1b64 | train | class | class _ECPIX5Platform(LatticeECP5Platform):
package = "BG554"
speed = "8"
default_clk = "clk100"
default_rst = "rst"
resources = [
Resource("rst", 0, PinsN("AB1", dir="i"), Attrs(IO_TYPE="LVCMOS33")),
Resource("clk100", 0, Pins("K23", dir="i"), Clock(100e6), Attrs(IO_TYP... | class _ECPIX5Platform(LatticeECP5Platform):
| package = "BG554"
speed = "8"
default_clk = "clk100"
default_rst = "rst"
resources = [
Resource("rst", 0, PinsN("AB1", dir="i"), Attrs(IO_TYPE="LVCMOS33")),
Resource("clk100", 0, Pins("K23", dir="i"), Clock(100e6), Attrs(IO_TYPE="LVCMOS33")),
RGBLEDResource(0,
... | import os
import subprocess
from nmigen.build import *
from nmigen.vendor.lattice_ecp5 import *
from .resources import *
__all__ = ["ECPIX585Platform", "ECPIX545Platform"]
class _ECPIX5Platform(LatticeECP5Platform):
| 57 | 256 | 1,963 | 13 | 44 | tdaede/nmigen-boards | nmigen_boards/ecpix5.py | Python | _ECPIX5Platform | _ECPIX5Platform | 12 | 152 | 12 | 12 | 2e95ab03091a3f40c220a98051fd8bdbd688dc60 | bigcode/the-stack | train |
c3aabae9e3a2afa96ec8f782 | train | function | @register.filter(name='cuti')
def cuti(value,arg):
return value.replace(arg,'')
| @register.filter(name='cuti')
def cuti(value,arg):
| return value.replace(arg,'')
| from django import template
register = template.Library()
@register.filter(name='cuti')
def cuti(value,arg):
| 24 | 64 | 20 | 14 | 10 | ashishpm/django-repository--example | learning_templates/basic_app/templatetags/my_extras.py | Python | cuti | cuti | 5 | 8 | 5 | 7 | c6e696bf6213b9463edc445cf2f2a62b352b096a | bigcode/the-stack | train |
e0803bc1501d5ccc38b8c317 | train | function | def midi_note_to_hertz(midi_note):
return 440 * 2 ** ((midi_note - 69) / 12)
| def midi_note_to_hertz(midi_note):
| return 440 * 2 ** ((midi_note - 69) / 12)
| import pathlib
BASE_DIR = pathlib.Path(__file__).resolve().parent
def midi_note_to_hertz(midi_note):
| 25 | 64 | 30 | 10 | 14 | oddvoices/oddvoices | python/oddvoices/utils.py | Python | midi_note_to_hertz | midi_note_to_hertz | 6 | 7 | 6 | 6 | c6e7d2dccee1623aa74d2314c7d30891c9660f87 | bigcode/the-stack | train |
331b4aef6083263120cc0cb6 | train | class | class eventsAPI(object):
def __init__(self, username, authstring, token = False):
self.requester = username
self.authstring = authstring
self.istoken = token
def get_feed(self, entity, isorg):
if not isorg:
return build_call("get", "users/" + entity + "/received_eve... | class eventsAPI(object):
| def __init__(self, username, authstring, token = False):
self.requester = username
self.authstring = authstring
self.istoken = token
def get_feed(self, entity, isorg):
if not isorg:
return build_call("get", "users/" + entity + "/received_events", self.requester, self... | from endpoints import build_call
class eventsAPI(object):
| 11 | 64 | 126 | 5 | 5 | mbad0la/octopy | octopy/events.py | Python | eventsAPI | eventsAPI | 3 | 14 | 3 | 4 | 2cdb9a9e3823cbed1bd9d2fcd71bbfb692ab78b3 | bigcode/the-stack | train |
f9cffa2cfd54ab96fd3f6c59 | train | class | class MybankMarketingCampaignPrizeListConsultResponse(AlipayResponse):
def __init__(self):
super(MybankMarketingCampaignPrizeListConsultResponse, self).__init__()
self._prize_list = None
@property
def prize_list(self):
return self._prize_list
@prize_list.setter
def prize_l... | class MybankMarketingCampaignPrizeListConsultResponse(AlipayResponse):
| def __init__(self):
super(MybankMarketingCampaignPrizeListConsultResponse, self).__init__()
self._prize_list = None
@property
def prize_list(self):
return self._prize_list
@prize_list.setter
def prize_list(self, value):
if isinstance(value, list):
self._... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.PrizeModel import PrizeModel
class MybankMarketingCampaignPrizeListConsultResponse(AlipayResponse):
| 60 | 64 | 189 | 14 | 45 | snowxmas/alipay-sdk-python-all | alipay/aop/api/response/MybankMarketingCampaignPrizeListConsultResponse.py | Python | MybankMarketingCampaignPrizeListConsultResponse | MybankMarketingCampaignPrizeListConsultResponse | 9 | 32 | 9 | 10 | ad1438a12c5cd0c9806b916b2712a8804298f31a | bigcode/the-stack | train |
284dab6e99e2c073aaca6911 | train | function | @pytest.mark.disabled
@pytest.mark.host_reservation
@pytest.mark.kea_only
def test_v6_host_reservation_cql_conflicts_reconfigure_server_with_reservation_of_used_address_renew_after_expire():
misc.test_setup()
srv_control.set_time('renew-timer', '5')
srv_control.set_time('rebind-timer', '6')
srv_control.... | @pytest.mark.disabled
@pytest.mark.host_reservation
@pytest.mark.kea_only
def test_v6_host_reservation_cql_conflicts_reconfigure_server_with_reservation_of_used_address_renew_after_expire():
| misc.test_setup()
srv_control.set_time('renew-timer', '5')
srv_control.set_time('rebind-timer', '6')
srv_control.set_time('preferred-lifetime', '7')
srv_control.set_time('valid-lifetime', '8')
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::2')
srv_control.build_and_send_config_fil... | , 'IA-NA')
srv_msg.client_send_msg('SOLICIT')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', None, 'ADVERTISE')
misc.test_procedure()
srv_msg.client_copy_option('server-id')
srv_msg.client_copy_option('IA_NA')
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:f6:f5:f4:f3... | 256 | 256 | 1,621 | 42 | 214 | shawnmullaney/forge | tests/dhcpv6/kea_only/host_reservation/test_host_reservation_address_conflicts_cql.py | Python | test_v6_host_reservation_cql_conflicts_reconfigure_server_with_reservation_of_used_address_renew_after_expire | test_v6_host_reservation_cql_conflicts_reconfigure_server_with_reservation_of_used_address_renew_after_expire | 430 | 555 | 430 | 433 | b69f8c13bfe2eccfb8bf718783a33652c5ca1f84 | bigcode/the-stack | train |
b888e27f43fa480d73bd2bed | train | function | @pytest.mark.disabled
@pytest.mark.host_reservation
@pytest.mark.kea_only
def test_v6_host_reservation_cql_conflicts_reconfigure_server_with_reservation_of_used_address():
misc.test_setup()
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::2')
srv_control.build_and_send_config_files('SSH', 'config-f... | @pytest.mark.disabled
@pytest.mark.host_reservation
@pytest.mark.kea_only
def test_v6_host_reservation_cql_conflicts_reconfigure_server_with_reservation_of_used_address():
| misc.test_setup()
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::2')
srv_control.build_and_send_config_files('SSH', 'config-file')
srv_control.start_srv('DHCP', 'started')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:66:55:44:33:22:11')
srv_msg.c... | None, 'ADVERTISE')
srv_msg.response_check_include_option('Response', None, '3')
srv_msg.response_check_option_content('Response', '3', None, 'sub-option', '5')
misc.test_procedure()
srv_msg.client_copy_option('IA_NA')
srv_msg.client_copy_option('server-id')
srv_msg.client_sets_value('Client', ... | 256 | 256 | 968 | 37 | 219 | shawnmullaney/forge | tests/dhcpv6/kea_only/host_reservation/test_host_reservation_address_conflicts_cql.py | Python | test_v6_host_reservation_cql_conflicts_reconfigure_server_with_reservation_of_used_address | test_v6_host_reservation_cql_conflicts_reconfigure_server_with_reservation_of_used_address | 130 | 210 | 130 | 133 | de7482ba917cfbc91dd0e1a6ad8b1eb794ff2445 | bigcode/the-stack | train |
a73aa1797ca41bac0235c35d | train | function | @pytest.mark.disabled
@pytest.mark.host_reservation
@pytest.mark.kea_only
def test_v6_host_reservation_cql_conflicts_two_entries_for_one_host_different_subnets():
misc.test_setup()
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::10')
srv_control.enable_db_backend_reservation('Cassandra')
srv_... | @pytest.mark.disabled
@pytest.mark.host_reservation
@pytest.mark.kea_only
def test_v6_host_reservation_cql_conflicts_two_entries_for_one_host_different_subnets():
| misc.test_setup()
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::10')
srv_control.enable_db_backend_reservation('Cassandra')
srv_control.new_db_backend_reservation('Cassandra', 'duid', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_control.update_db_backend_reservation('dhcp6_subnet_id', '1', 'Cas... | ', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_control.update_db_backend_reservation('dhcp6_subnet_id', '1', 'Cassandra', '1')
srv_control.ipv6_address_db_backend_reservation('3000::1', '$(EMPTY)', 'Cassandra', '1')
srv_control.new_db_backend_reservation('Cassandra', 'duid', '00:03:00:01:f6:f5:f4:f3:f2:11')
s... | 256 | 256 | 963 | 37 | 219 | shawnmullaney/forge | tests/dhcpv6/kea_only/host_reservation/test_host_reservation_address_conflicts_cql.py | Python | test_v6_host_reservation_cql_conflicts_two_entries_for_one_host_different_subnets | test_v6_host_reservation_cql_conflicts_two_entries_for_one_host_different_subnets | 58 | 127 | 58 | 61 | 070f73fa5b2c8b6709ec28032a671e0acb939ae2 | bigcode/the-stack | train |
4b62f89d96c02859ec629b88 | train | function | @pytest.mark.disabled
@pytest.mark.host_reservation
@pytest.mark.kea_only
def test_v6_host_reservation_cql_duplicate_reservation_duid():
misc.test_setup()
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::10')
srv_control.enable_db_backend_reservation('Cassandra')
srv_control.new_db_backend_re... | @pytest.mark.disabled
@pytest.mark.host_reservation
@pytest.mark.kea_only
def test_v6_host_reservation_cql_duplicate_reservation_duid():
| misc.test_setup()
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::10')
srv_control.enable_db_backend_reservation('Cassandra')
srv_control.new_db_backend_reservation('Cassandra', 'duid', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_control.update_db_backend_reservation('dhcp6_subnet_id', '1', 'Ca... | """Host Reservation DHCPv6"""
# pylint: disable=invalid-name,line-too-long
import pytest
import srv_msg
import srv_control
import misc
@pytest.mark.disabled
@pytest.mark.host_reservation
@pytest.mark.kea_only
def test_v6_host_reservation_cql_duplicate_reservation_duid():
| 63 | 92 | 307 | 31 | 31 | shawnmullaney/forge | tests/dhcpv6/kea_only/host_reservation/test_host_reservation_address_conflicts_cql.py | Python | test_v6_host_reservation_cql_duplicate_reservation_duid | test_v6_host_reservation_cql_duplicate_reservation_duid | 12 | 32 | 12 | 15 | 9b60d7ff904c16b513c44623cd4a39c240224535 | bigcode/the-stack | train |
6891c0d6cd7082c1bf990633 | train | function | @pytest.mark.disabled
@pytest.mark.host_reservation
@pytest.mark.kea_only
def test_v6_host_reservation_cql_conflicts_reconfigure_server_with_reservation_of_used_address_renew_before_expire():
misc.test_setup()
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::2')
# Use Cassandra reservation system.... | @pytest.mark.disabled
@pytest.mark.host_reservation
@pytest.mark.kea_only
def test_v6_host_reservation_cql_conflicts_reconfigure_server_with_reservation_of_used_address_renew_before_expire():
| misc.test_setup()
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::2')
# Use Cassandra reservation system.
srv_control.build_and_send_config_files('SSH', 'config-file')
srv_control.start_srv('DHCP', 'started')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'DUID', '00:0... | 'IA-NA')
srv_msg.client_send_msg('SOLICIT')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', None, 'ADVERTISE')
misc.test_procedure()
srv_msg.client_copy_option('IA_NA')
srv_msg.client_copy_option('server-id')
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:f6:f5:f4:f3:... | 256 | 256 | 1,496 | 42 | 214 | shawnmullaney/forge | tests/dhcpv6/kea_only/host_reservation/test_host_reservation_address_conflicts_cql.py | Python | test_v6_host_reservation_cql_conflicts_reconfigure_server_with_reservation_of_used_address_renew_before_expire | test_v6_host_reservation_cql_conflicts_reconfigure_server_with_reservation_of_used_address_renew_before_expire | 310 | 427 | 310 | 313 | b443f36fde16f4b598bf3c330d790eef0e241a3c | bigcode/the-stack | train |
f7651f9767355f5d06d64a33 | train | function | @pytest.mark.disabled
@pytest.mark.host_reservation
@pytest.mark.kea_only
def test_v6_host_reservation_cql_duplicate_reservation_address():
misc.test_setup()
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::10')
srv_control.enable_db_backend_reservation('Cassandra')
srv_control.new_db_backend... | @pytest.mark.disabled
@pytest.mark.host_reservation
@pytest.mark.kea_only
def test_v6_host_reservation_cql_duplicate_reservation_address():
| misc.test_setup()
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::10')
srv_control.enable_db_backend_reservation('Cassandra')
srv_control.new_db_backend_reservation('Cassandra', 'duid', '00:03:00:01:f6:f5:f4:f3:f2:01')
srv_control.update_db_backend_reservation('dhcp6_subnet_id', '1', 'Ca... | EMPTY)', 'Cassandra', '2')
srv_control.upload_db_reservation('Cassandra')
# upload should failed!#TODO add step to failed upload
srv_control.build_and_send_config_files('SSH', 'config-file')
srv_control.start_srv('DHCP', 'started')
@pytest.mark.disabled
@pytest.mark.host_reservation
@pytest.mark.kea_on... | 91 | 91 | 306 | 30 | 61 | shawnmullaney/forge | tests/dhcpv6/kea_only/host_reservation/test_host_reservation_address_conflicts_cql.py | Python | test_v6_host_reservation_cql_duplicate_reservation_address | test_v6_host_reservation_cql_duplicate_reservation_address | 35 | 55 | 35 | 38 | 31c3486082f5b12b29dcc6150b8cd3422cd69a10 | bigcode/the-stack | train |
2bac47cb70d8f629862e4663 | train | function | @pytest.mark.disabled
@pytest.mark.host_reservation
@pytest.mark.kea_only
def test_v6_host_reservation_cql_conflicts_reconfigure_server_with_reservation_of_used_address_2():
misc.test_setup()
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::2')
srv_control.build_and_send_config_files('SSH', 'config... | @pytest.mark.disabled
@pytest.mark.host_reservation
@pytest.mark.kea_only
def test_v6_host_reservation_cql_conflicts_reconfigure_server_with_reservation_of_used_address_2():
| misc.test_setup()
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::2')
srv_control.build_and_send_config_files('SSH', 'config-file')
srv_control.start_srv('DHCP', 'started')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:66:55:44:33:22:11')
srv_msg.c... | ', None, 'IA-NA')
srv_msg.client_send_msg('SOLICIT')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', None, 'ADVERTISE')
misc.test_procedure()
srv_msg.client_copy_option('server-id')
srv_msg.client_copy_option('IA_NA')
srv_msg.client_sets_value('Client', 'DUID', '00:03:00:01:f6:f... | 256 | 256 | 1,162 | 39 | 217 | shawnmullaney/forge | tests/dhcpv6/kea_only/host_reservation/test_host_reservation_address_conflicts_cql.py | Python | test_v6_host_reservation_cql_conflicts_reconfigure_server_with_reservation_of_used_address_2 | test_v6_host_reservation_cql_conflicts_reconfigure_server_with_reservation_of_used_address_2 | 213 | 307 | 213 | 216 | fe90ae618716bcdd65e5e6ecdde36e4ba3e69180 | bigcode/the-stack | train |
51745462cda7106d696a8cd3 | train | function | def print_build_errors_and_exit(
build_errors: Dict[str, List[DocBuildError]],
spelling_errors: Dict[str, List[SpellingError]],
) -> None:
"""Prints build errors and exists."""
if build_errors or spelling_errors:
if build_errors:
display_errors_summary(build_errors)
print... | def print_build_errors_and_exit(
build_errors: Dict[str, List[DocBuildError]],
spelling_errors: Dict[str, List[SpellingError]],
) -> None:
| """Prints build errors and exists."""
if build_errors or spelling_errors:
if build_errors:
display_errors_summary(build_errors)
print()
if spelling_errors:
display_spelling_error_summary(spelling_errors)
print()
print("The documentation has... | 20)
print(tabulate(tabular_data=tabular_data, headers="keys"))
print("#" * 50)
def print_build_errors_and_exit(
build_errors: Dict[str, List[DocBuildError]],
spelling_errors: Dict[str, List[SpellingError]],
) -> None:
| 64 | 64 | 122 | 37 | 27 | marshall7m/airflow | docs/build_docs.py | Python | print_build_errors_and_exit | print_build_errors_and_exit | 165 | 181 | 165 | 168 | 1aaffa98495d1f241ca24338c85993b646bead7b | bigcode/the-stack | train |
54be0b67ff5bb46f9cbe602c | train | function | def display_packages_summary(
build_errors: Dict[str, List[DocBuildError]], spelling_errors: Dict[str, List[SpellingError]]
):
"""Displays a summary that contains information on the number of errors in each packages"""
packages_names = {*build_errors.keys(), *spelling_errors.keys()}
tabular_data = [
... | def display_packages_summary(
build_errors: Dict[str, List[DocBuildError]], spelling_errors: Dict[str, List[SpellingError]]
):
| """Displays a summary that contains information on the number of errors in each packages"""
packages_names = {*build_errors.keys(), *spelling_errors.keys()}
tabular_data = [
{
"Package name": package_name,
"Count of doc build errors": len(build_errors.get(package_name, [])),
... | _sphinx_docs()
if docs_errors:
all_build_errors[package_name].extend(docs_errors)
return all_build_errors, all_spelling_errors
def display_packages_summary(
build_errors: Dict[str, List[DocBuildError]], spelling_errors: Dict[str, List[SpellingError]]
):
| 64 | 64 | 176 | 31 | 32 | marshall7m/airflow | docs/build_docs.py | Python | display_packages_summary | display_packages_summary | 147 | 162 | 147 | 149 | 6bb2c84eb2a62217525da88f7d9bd2fa6bb817be | bigcode/the-stack | train |
3c27fefcde8acc091c7f8496 | train | function | def main():
"""Main code"""
args = _get_parser().parse_args()
available_packages = get_available_packages()
docs_only = args.docs_only
spellcheck_only = args.spellcheck_only
disable_checks = args.disable_checks
package_filters = args.package_filter
for_production = args.for_production
... | def main():
| """Main code"""
args = _get_parser().parse_args()
available_packages = get_available_packages()
docs_only = args.docs_only
spellcheck_only = args.spellcheck_only
disable_checks = args.disable_checks
package_filters = args.package_filter
for_production = args.for_production
if not pa... | k: k or '')
]
print("#" * 20, "Packages errors summary", "#" * 20)
print(tabulate(tabular_data=tabular_data, headers="keys"))
print("#" * 50)
def print_build_errors_and_exit(
build_errors: Dict[str, List[DocBuildError]],
spelling_errors: Dict[str, List[SpellingError]],
) -> None:
"""Print... | 174 | 174 | 583 | 3 | 171 | marshall7m/airflow | docs/build_docs.py | Python | main | main | 184 | 259 | 184 | 184 | 563806010e2a180e1dc970c047db7df268e8a9b7 | bigcode/the-stack | train |
222ad28ac691cc9f4734dbf3 | train | function | def _get_parser():
available_packages_list = " * " + "\n * ".join(get_available_packages())
parser = argparse.ArgumentParser(
description='Builds documentation and runs spell checking',
epilog=f"List of supported documentation packages:\n{available_packages_list}",
)
parser.formatter_cla... | def _get_parser():
| available_packages_list = " * " + "\n * ".join(get_available_packages())
parser = argparse.ArgumentParser(
description='Builds documentation and runs spell checking',
epilog=f"List of supported documentation packages:\n{available_packages_list}",
)
parser.formatter_class = argparse.RawTe... | print("You can also use other extra flags to iterate faster:")
print(" --docs-only - Only build documentation")
print(" --spellcheck-only - Only perform spellchecking")
print()
print("For more info:")
print(" ./breeze build-docs --help")
print(TEXT_RESET)
def _get_parser():
| 74 | 74 | 247 | 5 | 69 | marshall7m/airflow | docs/build_docs.py | Python | _get_parser | _get_parser | 91 | 119 | 91 | 91 | 92b27960195df9bb95a0c17af00c60de9d5ff315 | bigcode/the-stack | train |
28b47e0ea3e5dd79b25f586a | train | function | def build_docs_for_packages(
current_packages: List[str], docs_only: bool, spellcheck_only: bool, for_production: bool
) -> Tuple[Dict[str, List[DocBuildError]], Dict[str, List[SpellingError]]]:
"""Builds documentation for single package and returns errors"""
all_build_errors: Dict[str, List[DocBuildError]]... | def build_docs_for_packages(
current_packages: List[str], docs_only: bool, spellcheck_only: bool, for_production: bool
) -> Tuple[Dict[str, List[DocBuildError]], Dict[str, List[SpellingError]]]:
| """Builds documentation for single package and returns errors"""
all_build_errors: Dict[str, List[DocBuildError]] = defaultdict(list)
all_spelling_errors: Dict[str, List[SpellingError]] = defaultdict(list)
for package_no, package_name in enumerate(current_packages, start=1):
print("#" * 20, f"[{... | action='store_true',
help='Builds documentation for official release i.e. all links point to stable version',
)
return parser
def build_docs_for_packages(
current_packages: List[str], docs_only: bool, spellcheck_only: bool, for_production: bool
) -> Tuple[Dict[str, List[DocBuildError]], Dic... | 84 | 84 | 280 | 53 | 30 | marshall7m/airflow | docs/build_docs.py | Python | build_docs_for_packages | build_docs_for_packages | 122 | 144 | 122 | 124 | 56ee7126de80ffd0b8ff4a959eeff8e55ba40788 | bigcode/the-stack | train |
e4298dc68634b3916c139174 | train | function | def _promote_new_flags():
print(TEXT_BLUE)
print("Tired of waiting for documentation to be built?")
print()
if ON_GITHUB_ACTIONS:
print("You can quickly build documentation locally with just one command.")
print(" ./breeze build-docs")
print()
print("Still too slow?")
... | def _promote_new_flags():
| print(TEXT_BLUE)
print("Tired of waiting for documentation to be built?")
print()
if ON_GITHUB_ACTIONS:
print("You can quickly build documentation locally with just one command.")
print(" ./breeze build-docs")
print()
print("Still too slow?")
print()
print(... | inventories with the following issues',
'undefined label:',
'unknown document:',
]
ON_GITHUB_ACTIONS = os.environ.get('GITHUB_ACTIONS', 'false') == "true"
TEXT_BLUE = '\033[94m'
TEXT_RESET = '\033[0m'
def _promote_new_flags():
| 64 | 64 | 193 | 7 | 57 | marshall7m/airflow | docs/build_docs.py | Python | _promote_new_flags | _promote_new_flags | 67 | 88 | 67 | 67 | 23ba26c466e82317d01b879c79757d75c1d8befc | bigcode/the-stack | train |
79112c3906a7f140071f4b0e | train | function | def start_dungeon():
result = level1.first_room()
if result == 1:
print(asciiart.chicken())
print("Have fun baking pies in safety, you baby.")
return
else:
print("You are a brave soul!")
print("")
time.sleep(0.75)
result = level1.second_room()
if(resul... | def start_dungeon():
| result = level1.first_room()
if result == 1:
print(asciiart.chicken())
print("Have fun baking pies in safety, you baby.")
return
else:
print("You are a brave soul!")
print("")
time.sleep(0.75)
result = level1.second_room()
if(result == 1):
prin... | agon())
# print(asciiart.big_skull())
# print(asciiart.dragon())
# print(asciiart.samurai())
# print(asciiart.skull_cross())
# print(asciiart.warrior())
# print(asciiart.chicken())
def start_dungeon():
| 64 | 64 | 172 | 5 | 59 | goosemanjack/python_intro_class | class_3/dungeon.py | Python | start_dungeon | start_dungeon | 19 | 49 | 19 | 19 | 2234697ac4a4395c06bb927cb08faf68e2d9fda4 | bigcode/the-stack | train |
bac0855a2da09b55a1ebe433 | train | function | def run_second_room():
print("")
result = level2.nest()
if result == 1:
print(asciiart.baby_dragon())
time.sleep(0.75)
print("You have birthed a baby!")
return
elif result == 2:
print(asciiart.dragon())
print("Oh no! Momma dragon is here and she isn't hap... | def run_second_room():
| print("")
result = level2.nest()
if result == 1:
print(asciiart.baby_dragon())
time.sleep(0.75)
print("You have birthed a baby!")
return
elif result == 2:
print(asciiart.dragon())
print("Oh no! Momma dragon is here and she isn't happy!")
time.slee... | open the box.")
return
elif(result == 3):
return start_dungeon()
print("")
result = level1.next_level()
if(result == 1):
result = level1.second_room()
#...
return
elif(result == 2):
return run_second_room()
def run_second_room():
| 71 | 71 | 238 | 5 | 66 | goosemanjack/python_intro_class | class_3/dungeon.py | Python | run_second_room | run_second_room | 53 | 86 | 53 | 53 | 16520b78da20adc543ce160945f9c8f5aa0b638f | bigcode/the-stack | train |
f5fb301e0afe61beedf17571 | train | class | class TextInput(WrappedComponent):
"""Represents a UI text input.
This can only be used in a :class:`~.ui.Modal`.
.. versionadded:: 2.4
Parameters
----------
label: :class:`str`
The label of the text input.
custom_id: :class:`str`
The ID of the text input that gets receive... | class TextInput(WrappedComponent):
| """Represents a UI text input.
This can only be used in a :class:`~.ui.Modal`.
.. versionadded:: 2.4
Parameters
----------
label: :class:`str`
The label of the text input.
custom_id: :class:`str`
The ID of the text input that gets received during an interaction.
style:... | software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject ... | 256 | 256 | 997 | 7 | 249 | Enegg/disnake | disnake/ui/text_input.py | Python | TextInput | TextInput | 36 | 174 | 36 | 36 | b2f97f534a3e655fa34881ffcddd5481b00328c1 | bigcode/the-stack | train |
23d1aaf0fdad60629c45a82c | train | function | def ceil(value):
if is_constant(value):
return math.ceil(value)
if is_numpy(value):
return np.ceil(value)
omap = {'Ceil': 'Identity'}
with tf.get_default_graph().gradient_override_map(omap):
return tf.ceil(value)
| def ceil(value):
| if is_constant(value):
return math.ceil(value)
if is_numpy(value):
return np.ceil(value)
omap = {'Ceil': 'Identity'}
with tf.get_default_graph().gradient_override_map(omap):
return tf.ceil(value)
| .num_elements()
def floor(value):
if is_constant(value):
return math.floor(value)
if is_numpy(value):
return np.floor(value)
omap = {'Floor': 'Identity'}
with tf.get_default_graph().gradient_override_map(omap):
return tf.floor(value)
def ceil(value):
| 64 | 64 | 58 | 4 | 60 | deep-fry/mayo | mayo/override/util.py | Python | ceil | ceil | 100 | 107 | 100 | 100 | c014ef0cd013855574c27983b0bd20b43dac6912 | bigcode/the-stack | train |
d2ebfdeea452f433ff7695d4 | train | function | def logical_not(value):
if is_constant(value):
_constants_not_accepted('Logical NOT')
if is_numpy(value):
return np.logical_not(value)
return tf.logical_not(value)
| def logical_not(value):
| if is_constant(value):
_constants_not_accepted('Logical NOT')
if is_numpy(value):
return np.logical_not(value)
return tf.logical_not(value)
| ')
if is_numpy(a, b):
return getattr(np, op)(a, b)
return getattr(tf, op)(a, b)
logical_or = partial(_binary_bool_operation, op='logical_or')
logical_and = partial(_binary_bool_operation, op='logical_and')
def logical_not(value):
| 64 | 64 | 41 | 5 | 59 | deep-fry/mayo | mayo/override/util.py | Python | logical_not | logical_not | 176 | 181 | 176 | 176 | d605b303058a9f0d09dd4f51476edbb32d3fe9a5 | bigcode/the-stack | train |
74912d43f8b8ad60605abb87 | train | function | def log(value, base=None):
if is_constant(value, base):
return math.log(value, base)
if is_numpy(value, base):
return np.log(value) / np.log(base)
return tf.log(value) / tf.log(cast(base, float))
| def log(value, base=None):
| if is_constant(value, base):
return math.log(value, base)
if is_numpy(value, base):
return np.log(value) / np.log(base)
return tf.log(value) / tf.log(cast(base, float))
| return abs(value)
if is_numpy(value):
return np.abs(value)
return tf.abs(value)
def sqrt(value):
if is_constant(value):
return math.sqrt(value)
if is_numpy(value):
return np.sqrt(value)
return tf.sqrt(value)
def log(value, base=None):
| 64 | 64 | 57 | 7 | 57 | deep-fry/mayo | mayo/override/util.py | Python | log | log | 156 | 161 | 156 | 156 | 2ad1c3929d5a56a9c8ed34cc8f1c8cb00261ba91 | bigcode/the-stack | train |
8e190aea518965dfc8357df8 | train | function | def sqrt(value):
if is_constant(value):
return math.sqrt(value)
if is_numpy(value):
return np.sqrt(value)
return tf.sqrt(value)
| def sqrt(value):
| if is_constant(value):
return math.sqrt(value)
if is_numpy(value):
return np.sqrt(value)
return tf.sqrt(value)
| Identity'}
with tf.get_default_graph().gradient_override_map(omap):
return tf.greater_equal(value1, value2)
def abs(value):
if is_constant(value):
return abs(value)
if is_numpy(value):
return np.abs(value)
return tf.abs(value)
def sqrt(value):
| 64 | 64 | 34 | 4 | 60 | deep-fry/mayo | mayo/override/util.py | Python | sqrt | sqrt | 148 | 153 | 148 | 148 | eb07bb537fd447c203e321b3db833c95eceb4bcb | bigcode/the-stack | train |
6456157fd25c1d091fe3b47a | train | function | def is_constant(*args):
return all(isinstance(a, (bool, int, float)) for a in args)
| def is_constant(*args):
| return all(isinstance(a, (bool, int, float)) for a in args)
| import math
from functools import partial
import numpy as np
import tensorflow as tf
def is_constant(*args):
| 24 | 64 | 25 | 6 | 17 | deep-fry/mayo | mayo/override/util.py | Python | is_constant | is_constant | 8 | 9 | 8 | 8 | 99a9da48be274d4aa9f87814a5bf2f5458a7947e | bigcode/the-stack | train |
af5abedbd152d4f8a918c09d | train | function | def count(value):
if is_constant(value):
_constants_not_accepted(where)
if is_numpy(value):
return value.size
return value.shape.num_elements()
| def count(value):
| if is_constant(value):
_constants_not_accepted(where)
if is_numpy(value):
return value.size
return value.shape.num_elements()
| _accepted(where)
if is_numpy(value):
return np.sum(value)
return tf.reduce_sum(value)
def mean(value):
if is_constant(value):
_constants_not_accepted(where)
if is_numpy(value):
return np.mean(value)
return tf.reduce_mean(value)
def count(value):
| 64 | 64 | 36 | 4 | 60 | deep-fry/mayo | mayo/override/util.py | Python | count | count | 82 | 87 | 82 | 82 | a80df6f25c4f9ca9f1089922a0c85f9f8400dcaa | bigcode/the-stack | train |
6d52dca1fe963b79d03db7bb | train | function | def _clip(*args, min_max=None):
if is_constant(*args):
return min(*args) if min_max else max(*args)
if is_numpy(*args):
return np.minimum(*args) if min_max else np.maximum(*args)
return tf.minimum(*args) if min_max else tf.maximum(*args)
| def _clip(*args, min_max=None):
| if is_constant(*args):
return min(*args) if min_max else max(*args)
if is_numpy(*args):
return np.minimum(*args) if min_max else np.maximum(*args)
return tf.minimum(*args) if min_max else tf.maximum(*args)
| _and = partial(_binary_bool_operation, op='logical_and')
def logical_not(value):
if is_constant(value):
_constants_not_accepted('Logical NOT')
if is_numpy(value):
return np.logical_not(value)
return tf.logical_not(value)
def _clip(*args, min_max=None):
| 64 | 64 | 70 | 10 | 54 | deep-fry/mayo | mayo/override/util.py | Python | _clip | _clip | 184 | 189 | 184 | 184 | 8ad3763f49e0c9b13ba99b9eba55da77a03f52d0 | bigcode/the-stack | train |
004ac3f6d3fc780b5ecfee3f | train | function | def moments(tensor, axes):
if is_tensor(tensor):
return tf.nn.moments(tf.abs(tensor), axes=axes)
mean = np.mean(tensor, axis=tuple(axes))
var = np.var(tensor, axis=tuple(axes))
return (mean, var)
| def moments(tensor, axes):
| if is_tensor(tensor):
return tf.nn.moments(tf.abs(tensor), axes=axes)
mean = np.mean(tensor, axis=tuple(axes))
var = np.var(tensor, axis=tuple(axes))
return (mean, var)
| (tensor, k):
if is_tensor(tensor):
tensor = tf.reshape(tensor, [-1])
topk = tf.nn.top_k(tensor, k)
return tf.reduce_min(cast(topk.values, float))
return sorted(tensor)[k]
def moments(tensor, axes):
| 64 | 64 | 65 | 7 | 57 | deep-fry/mayo | mayo/override/util.py | Python | moments | moments | 214 | 219 | 214 | 214 | bb6e7741de937292f9547e43662631db90f009f0 | bigcode/the-stack | train |
8ff8facc57f89b030df91137 | train | function | def stochastic_round(tensor, stochastic):
value_floor = floor(tensor)
value_ceil = ceil(tensor)
if stochastic == 'naive':
prob = 0.5
elif stochastic == 'ulp':
# tensor is scaled so ulp is 1
prob = (tensor - value_floor)
else:
raise TypeError(
'Stochastic m... | def stochastic_round(tensor, stochastic):
| value_floor = floor(tensor)
value_ceil = ceil(tensor)
if stochastic == 'naive':
prob = 0.5
elif stochastic == 'ulp':
# tensor is scaled so ulp is 1
prob = (tensor - value_floor)
else:
raise TypeError(
'Stochastic mode {!r} not recognized.'.format(stochasti... | np.mean(tensor, axis=tuple(axes))
var = np.var(tensor, axis=tuple(axes))
return (mean, var)
def get_shape(tensor):
if is_tensor(tensor):
return tensor.get_shape()
return tensor.shape
def stochastic_round(tensor, stochastic):
| 64 | 64 | 132 | 8 | 55 | deep-fry/mayo | mayo/override/util.py | Python | stochastic_round | stochastic_round | 228 | 241 | 228 | 228 | 1e2c9a7e0ef56b3c7a4259922892ec834c8b271c | bigcode/the-stack | train |
16ea898ca53276766635657d | train | function | def _constants_not_accepted(func):
raise TypeError('{} does not accept constants as argmuents.'.format(func))
| def _constants_not_accepted(func):
| raise TypeError('{} does not accept constants as argmuents.'.format(func))
| : np.bool,
}
return np.cast[dtypes[dtype]](value)
dtypes = {
float: tf.float32,
int: tf.int32,
bool: tf.bool,
}
return tf.cast(value, dtypes[dtype])
def _constants_not_accepted(func):
| 64 | 64 | 25 | 8 | 56 | deep-fry/mayo | mayo/override/util.py | Python | _constants_not_accepted | _constants_not_accepted | 42 | 43 | 42 | 42 | 8185cfcdf0c6fb6946e9d19f52f37a15be080ead | bigcode/the-stack | train |
4a8a3cf851ed9c0633c7ee57 | train | function | def greater_equal(value1, value2):
if is_constant(value1):
return value1 >= value2
if is_numpy(value1):
return value1 >= value2
omap = {'Round': 'Identity'}
with tf.get_default_graph().gradient_override_map(omap):
return tf.greater_equal(value1, value2)
| def greater_equal(value1, value2):
| if is_constant(value1):
return value1 >= value2
if is_numpy(value1):
return value1 >= value2
omap = {'Round': 'Identity'}
with tf.get_default_graph().gradient_override_map(omap):
return tf.greater_equal(value1, value2)
| return value1 == value2
if is_numpy(value1):
return value1 == value2
omap = {'Round': 'Identity'}
with tf.get_default_graph().gradient_override_map(omap):
return tf.equal(value1, value2)
def greater_equal(value1, value2):
| 64 | 64 | 74 | 9 | 55 | deep-fry/mayo | mayo/override/util.py | Python | greater_equal | greater_equal | 130 | 137 | 130 | 130 | 5d00631db0ff333bb43f61a0ef6d97f97c3ae24b | bigcode/the-stack | train |
521398490332b03a73fb0c96 | train | function | def equal(value1, value2):
if is_constant(value1):
return value1 == value2
if is_numpy(value1):
return value1 == value2
omap = {'Round': 'Identity'}
with tf.get_default_graph().gradient_override_map(omap):
return tf.equal(value1, value2)
| def equal(value1, value2):
| if is_constant(value1):
return value1 == value2
if is_numpy(value1):
return value1 == value2
omap = {'Round': 'Identity'}
with tf.get_default_graph().gradient_override_map(omap):
return tf.equal(value1, value2)
| is_constant(value):
return math.floor(value + 0.5)
if is_numpy(value):
return np.round(value)
omap = {'Round': 'Identity'}
with tf.get_default_graph().gradient_override_map(omap):
return tf.round(value)
def equal(value1, value2):
| 64 | 64 | 71 | 8 | 56 | deep-fry/mayo | mayo/override/util.py | Python | equal | equal | 120 | 127 | 120 | 120 | 9b040a77af1bac5ae2b9a6bcc8d8863368148997 | bigcode/the-stack | train |
6bddef92af215a93e3eb58c3 | train | function | def is_numpy(*args):
if is_constant(*args):
return False
return all(isinstance(
a, (bool, int, float, np.ndarray, np.float32, np.int32, np.bool_))
for a in args)
| def is_numpy(*args):
| if is_constant(*args):
return False
return all(isinstance(
a, (bool, int, float, np.ndarray, np.float32, np.int32, np.bool_))
for a in args)
| import math
from functools import partial
import numpy as np
import tensorflow as tf
def is_constant(*args):
return all(isinstance(a, (bool, int, float)) for a in args)
def is_numpy(*args):
| 49 | 64 | 54 | 6 | 43 | deep-fry/mayo | mayo/override/util.py | Python | is_numpy | is_numpy | 12 | 17 | 12 | 12 | 58c3f4232e1e81e58ab8f7a40b1b37e5580fc1a1 | bigcode/the-stack | train |
94a2123e900be90bc78ad213 | train | function | def abs(value):
if is_constant(value):
return abs(value)
if is_numpy(value):
return np.abs(value)
return tf.abs(value)
| def abs(value):
| if is_constant(value):
return abs(value)
if is_numpy(value):
return np.abs(value)
return tf.abs(value)
| 1):
return value1 >= value2
if is_numpy(value1):
return value1 >= value2
omap = {'Round': 'Identity'}
with tf.get_default_graph().gradient_override_map(omap):
return tf.greater_equal(value1, value2)
def abs(value):
| 64 | 64 | 33 | 4 | 60 | deep-fry/mayo | mayo/override/util.py | Python | abs | abs | 140 | 145 | 140 | 140 | 8511b4fa5a3ad8c3a7a43a495122cf4d394246cc | bigcode/the-stack | train |
f9fa16d5c571952f43827883 | train | function | def mean(value):
if is_constant(value):
_constants_not_accepted(where)
if is_numpy(value):
return np.mean(value)
return tf.reduce_mean(value)
| def mean(value):
| if is_constant(value):
_constants_not_accepted(where)
if is_numpy(value):
return np.mean(value)
return tf.reduce_mean(value)
| (value)
raise TypeError(
'Tensorflow does not implement a function to compute non-zero values.')
def sum(value):
if is_constant(value):
_constants_not_accepted(where)
if is_numpy(value):
return np.sum(value)
return tf.reduce_sum(value)
def mean(value):
| 64 | 64 | 37 | 4 | 60 | deep-fry/mayo | mayo/override/util.py | Python | mean | mean | 74 | 79 | 74 | 74 | 6b126ac57790758ed115882f0382f91234a9a467 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.