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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
af25419baeba4b6690723622 | train | function | def style_string(string, ansi_style, colormode, nested=False):
"""
Style the given string according to the given
ANSI style string.
:param str string: the string to style
:param tuple ansi_style: the styling string returned by ``translate_style``
:param int colormode: the color mode to use. See... | def style_string(string, ansi_style, colormode, nested=False):
| """
Style the given string according to the given
ANSI style string.
:param str string: the string to style
:param tuple ansi_style: the styling string returned by ``translate_style``
:param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``
:returns: a string contain... | ansi_end_code)
except StopIteration: # we've consumed all parts of the styling string
pass
# construct and return ANSI escape code sequence
return ''.join(ansi_start_sequence), ''.join(ansi_end_sequence)
def style_string(string, ansi_style, colormode, nested=False):
| 64 | 64 | 212 | 15 | 49 | 0ki/colorful | colorful/core.py | Python | style_string | style_string | 196 | 219 | 196 | 196 | 2fea6f538905594e6875e74661cc126f1dfe29fe | bigcode/the-stack | train |
31cf50337cad15bc6cd3d8e4 | train | class | class ColorfulError(Exception):
"""
Exception which is raised for Colorful specific
usage errors.
"""
pass
| class ColorfulError(Exception):
| """
Exception which is raised for Colorful specific
usage errors.
"""
pass
| .environ.get(
'COLORFUL_DEFAULT_COLOR_PALETTE',
os.path.join(os.path.dirname(__file__), 'data', 'rgb.txt'))
#: Holds the color names mapped to RGB channels
COLOR_PALETTE = rgb.parse_rgb_txt_file(path=DEFAULT_RGB_TXT_PATH)
class ColorfulError(Exception):
| 64 | 64 | 27 | 6 | 58 | 0ki/colorful | colorful/core.py | Python | ColorfulError | ColorfulError | 35 | 40 | 35 | 35 | 76134ca8d42668b4fa263bd160d91135661872fe | bigcode/the-stack | train |
ea768fc96500c9384211a304 | train | function | def translate_colorname_to_ansi_code(colorname, offset, colormode, colorpalette):
"""
Translate the given color name to a valid
ANSI escape code.
:parma str colorname: the name of the color to resolve
:parma str offset: the offset for the color code
:param int colormode: the color mode to use. ... | def translate_colorname_to_ansi_code(colorname, offset, colormode, colorpalette):
| """
Translate the given color name to a valid
ANSI escape code.
:parma str colorname: the name of the color to resolve
:parma str offset: the offset for the color code
:param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``
:parma dict colorpalette: the color palette... | end_code = ansi.ANSI_ESCAPE_CODE.format(code=offset + ansi.COLOR_CLOSE_OFFSET)
return start_code, end_code
raise ColorfulError('invalid color mode "{0}"'.format(colormode))
def translate_colorname_to_ansi_code(colorname, offset, colormode, colorpalette):
| 66 | 66 | 223 | 20 | 46 | 0ki/colorful | colorful/core.py | Python | translate_colorname_to_ansi_code | translate_colorname_to_ansi_code | 88 | 108 | 88 | 88 | 02b9cb6f63996750a636bfce551c80dbb8422123 | bigcode/the-stack | train |
fa0d4d420dad3f33cce20fa3 | train | class | class Colorful(object):
"""
Provides methods to style strings for terminal
output.
:param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``
"""
# re-expose the color modes from ``colorful.terminal``
# on a package level.
NO_COLORS = terminal.NO_COLORS
ANSI_8_C... | class Colorful(object):
| """
Provides methods to style strings for terminal
output.
:param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``
"""
# re-expose the color modes from ``colorful.terminal``
# on a package level.
NO_COLORS = terminal.NO_COLORS
ANSI_8_COLORS = terminal.ANSI_8_... | return self
def __radd__(self, other):
if isinstance(other, ColorfulString):
return ColorfulString(
other.orig_string + self.orig_string,
other.styled_string + self.styled_string)
# we return handover the conversion to the
# object on the... | 256 | 256 | 2,014 | 5 | 250 | 0ki/colorful | colorful/core.py | Python | Colorful | Colorful | 297 | 541 | 297 | 297 | 52fcf943a2f0527283501ec68d25dc9670f551a4 | bigcode/the-stack | train |
6aa9d9a39642587f5e05b062 | train | class | class SSHKeyViewSet(AuthModelViewSet):
"""
API endpoint that allows providers to be viewed or edited.
"""
serializer_class = SSHKeySerializer
def get_queryset(self):
"""
Filter projects by current user
"""
user = self.request.user
return SSHKey.objects.filter... | class SSHKeyViewSet(AuthModelViewSet):
| """
API endpoint that allows providers to be viewed or edited.
"""
serializer_class = SSHKeySerializer
def get_queryset(self):
"""
Filter projects by current user
"""
user = self.request.user
return SSHKey.objects.filter(atmo_user=user)
| from api.v2.views.base import AuthModelViewSet
from api.v2.serializers.details import SSHKeySerializer
from core.models import SSHKey
class SSHKeyViewSet(AuthModelViewSet):
| 41 | 64 | 69 | 10 | 30 | xuhang57/atmosphere | api/v2/views/ssh_key.py | Python | SSHKeyViewSet | SSHKeyViewSet | 7 | 18 | 7 | 8 | 5c1184784da35e3e215afe21b88579b7e28a8f50 | bigcode/the-stack | train |
38d8829e10279380bf17ad75 | train | class | class SurveyTemplateViewSet(
AllowedPermissionsMixin, viewsets.GenericViewSet, mixins.ListModelMixin,
mixins.RetrieveModelMixin
):
queryset = Survey.objects.all().prefetch_related('questions').filter(
template_type__isnull=False
)
permission_classes = [SurveyTemplatePermissions]
lookup_f... | class SurveyTemplateViewSet(
AllowedPermissionsMixin, viewsets.GenericViewSet, mixins.ListModelMixin,
mixins.RetrieveModelMixin
):
| queryset = Survey.objects.all().prefetch_related('questions').filter(
template_type__isnull=False
)
permission_classes = [SurveyTemplatePermissions]
lookup_field = 'template_type'
filter_backends = (DjangoFilterBackend, )
def get_serializer_class(self):
if self.action in ['retri... | ', 'partial_update']:
return SurveyUpdateSerializer
elif self.action in ['retrieve']:
return SurveyReadDetailedSerializer
return SurveyReadSerializer
class SurveyTemplateViewSet(
AllowedPermissionsMixin, viewsets.GenericViewSet, mixins.ListModelMixin,
mixins.RetrieveModel... | 64 | 64 | 114 | 32 | 31 | andrinelo/lego | lego/apps/surveys/views.py | Python | SurveyTemplateViewSet | SurveyTemplateViewSet | 32 | 46 | 32 | 35 | 1fb2a1520fbb7a405cb22e4960415225dd83f680 | bigcode/the-stack | train |
f7c7c8396482b8557d65df91 | train | class | class SurveyViewSet(AllowedPermissionsMixin, viewsets.ModelViewSet):
queryset = Survey.objects.all().prefetch_related('questions', 'submissions')
permission_classes = [SurveyPermissions]
filter_backends = (DjangoFilterBackend, )
def get_serializer_class(self):
if self.action in ['create']:
... | class SurveyViewSet(AllowedPermissionsMixin, viewsets.ModelViewSet):
| queryset = Survey.objects.all().prefetch_related('questions', 'submissions')
permission_classes = [SurveyPermissions]
filter_backends = (DjangoFilterBackend, )
def get_serializer_class(self):
if self.action in ['create']:
return SurveyCreateSerializer
elif self.action in ['u... | , SurveyPermissions, SurveyTemplatePermissions
)
from lego.apps.surveys.serializers import (
SubmissionCreateAndUpdateSerializer, SubmissionReadSerializer, SurveyCreateSerializer,
SurveyReadDetailedSerializer, SurveyReadSerializer, SurveyUpdateSerializer
)
class SurveyViewSet(AllowedPermissionsMixin, viewsets.M... | 64 | 64 | 112 | 15 | 49 | andrinelo/lego | lego/apps/surveys/views.py | Python | SurveyViewSet | SurveyViewSet | 17 | 29 | 17 | 17 | d6f37bb28f7e72fbc1a4011a9db4649b287b9d30 | bigcode/the-stack | train |
ec2a30497d65b242cc371255 | train | class | class SubmissionViewSet(AllowedPermissionsMixin, viewsets.ModelViewSet):
queryset = Submission.objects.all()
permission_classes = [SubmissionPermissions]
filter_class = SubmissionFilterSet
filter_backends = (DjangoFilterBackend, )
def get_queryset(self):
survey_id = self.kwargs['survey_pk']... | class SubmissionViewSet(AllowedPermissionsMixin, viewsets.ModelViewSet):
| queryset = Submission.objects.all()
permission_classes = [SubmissionPermissions]
filter_class = SubmissionFilterSet
filter_backends = (DjangoFilterBackend, )
def get_queryset(self):
survey_id = self.kwargs['survey_pk']
return Submission.objects.filter(survey=survey_id)
def get_... | ]
lookup_field = 'template_type'
filter_backends = (DjangoFilterBackend, )
def get_serializer_class(self):
if self.action in ['retrieve']:
return SurveyReadDetailedSerializer
return SurveyReadSerializer
class SubmissionViewSet(AllowedPermissionsMixin, viewsets.ModelViewSet):
| 64 | 64 | 174 | 15 | 48 | andrinelo/lego | lego/apps/surveys/views.py | Python | SubmissionViewSet | SubmissionViewSet | 49 | 70 | 49 | 49 | 7d7a53f8288db4c299cb077fe4d9ab7f0952e01d | bigcode/the-stack | train |
3ebf9386021e1fde6c5ae696 | train | class | class GameState(metaclass=Singleton):
def __init__(self):
self.logger = logging.getLogger(self.__class__.__name__)
self._role_mapper = RoleMapper()
self._ball = Ball()
self._field = Field(self._ball)
self._blue_team = Team(team_color=TeamColor.BLUE)
self._yellow_te... | class GameState(metaclass=Singleton):
| def __init__(self):
self.logger = logging.getLogger(self.__class__.__name__)
self._role_mapper = RoleMapper()
self._ball = Ball()
self._field = Field(self._ball)
self._blue_team = Team(team_color=TeamColor.BLUE)
self._yellow_team = Team(team_color=TeamColor.YELLOW)
... | # Under MIT License, see LICENSE.txt
import logging
from multiprocessing.managers import DictProxy
from Util import Position
from Util.constant import TeamColor, FieldSide
from Util.role_mapper import RoleMapper
from Util.singleton import Singleton
from Util.team_color_service import TeamColorService
from ai.Algorith... | 96 | 256 | 1,072 | 9 | 86 | RoboCupULaval/StrategyAI | ai/states/game_state.py | Python | GameState | GameState | 15 | 161 | 15 | 16 | ffb64e3d68999fd42adc4e18261f6ab1d42e87b6 | bigcode/the-stack | train |
3e328ab7c1aeb2c4a2174ce9 | train | class | class BaseValidationError(Exception):
def __init__(self, message=None, data=None):
if not isinstance(message, str):
message = f"{message}"
self.message = message
self.data = data
def __repr__(self):
return f"{type(self)}: {self.message}"
| class BaseValidationError(Exception):
| def __init__(self, message=None, data=None):
if not isinstance(message, str):
message = f"{message}"
self.message = message
self.data = data
def __repr__(self):
return f"{type(self)}: {self.message}"
| class BaseValidationError(Exception):
| 6 | 64 | 65 | 6 | 0 | LKI/tonggong | tonggong/validations/errors.py | Python | BaseValidationError | BaseValidationError | 1 | 9 | 1 | 1 | cf7707789fd43653d780c2835755bdc1e0fd44a7 | bigcode/the-stack | train |
f70cc4344d3ce255c9de3c19 | train | class | class LengthError(BaseValidationError):
"""长度不符合异常类型"""
| class LengthError(BaseValidationError):
| """长度不符合异常类型"""
| ):
"""参数错误异常类型"""
class MinLengthError(BaseValidationError):
"""小于最小长度异常类型"""
class MaxLengthError(BaseValidationError):
"""超出最大长度异常类型"""
class NullError(BaseValidationError):
"""参数为空异常类型"""
class LengthError(BaseValidationError):
| 64 | 64 | 15 | 7 | 57 | LKI/tonggong | tonggong/validations/errors.py | Python | LengthError | LengthError | 28 | 29 | 28 | 28 | 4cf91651a878eb7ab8322ef8c42030886c105f63 | bigcode/the-stack | train |
117b192c6607e7833ec50685 | train | class | class ParamError(BaseValidationError):
"""参数错误异常类型"""
| class ParamError(BaseValidationError):
| """参数错误异常类型"""
| init__(self, message=None, data=None):
if not isinstance(message, str):
message = f"{message}"
self.message = message
self.data = data
def __repr__(self):
return f"{type(self)}: {self.message}"
class ParamError(BaseValidationError):
| 63 | 64 | 14 | 7 | 56 | LKI/tonggong | tonggong/validations/errors.py | Python | ParamError | ParamError | 12 | 13 | 12 | 12 | 1b413cf1958c253814770c5d383219782042ba6d | bigcode/the-stack | train |
3750ed3a76692710e9dc1a7d | train | class | class MinLengthError(BaseValidationError):
"""小于最小长度异常类型"""
| class MinLengthError(BaseValidationError):
| """小于最小长度异常类型"""
| , str):
message = f"{message}"
self.message = message
self.data = data
def __repr__(self):
return f"{type(self)}: {self.message}"
class ParamError(BaseValidationError):
"""参数错误异常类型"""
class MinLengthError(BaseValidationError):
| 64 | 64 | 18 | 8 | 56 | LKI/tonggong | tonggong/validations/errors.py | Python | MinLengthError | MinLengthError | 16 | 17 | 16 | 16 | d9f0719300a8e486760dd59092708a08ccd5df99 | bigcode/the-stack | train |
8a37443e6e04d61e6c111264 | train | class | class SchemaError(BaseValidationError):
"""schema错误异常类型"""
| class SchemaError(BaseValidationError):
| """schema错误异常类型"""
| (BaseValidationError):
"""超出最大长度异常类型"""
class NullError(BaseValidationError):
"""参数为空异常类型"""
class LengthError(BaseValidationError):
"""长度不符合异常类型"""
class EmailError(BaseValidationError):
"""邮箱格式错误异常类型"""
class SchemaError(BaseValidationError):
| 64 | 64 | 14 | 7 | 57 | LKI/tonggong | tonggong/validations/errors.py | Python | SchemaError | SchemaError | 36 | 37 | 36 | 36 | dc173c63377f257c4c536c6317feeb6b67b5770f | bigcode/the-stack | train |
c3c450e120c074ca1e428ab2 | train | class | class NullError(BaseValidationError):
"""参数为空异常类型"""
| class NullError(BaseValidationError):
| """参数为空异常类型"""
| (self)}: {self.message}"
class ParamError(BaseValidationError):
"""参数错误异常类型"""
class MinLengthError(BaseValidationError):
"""小于最小长度异常类型"""
class MaxLengthError(BaseValidationError):
"""超出最大长度异常类型"""
class NullError(BaseValidationError):
| 64 | 64 | 14 | 7 | 57 | LKI/tonggong | tonggong/validations/errors.py | Python | NullError | NullError | 24 | 25 | 24 | 24 | b2dd3e8fff349cf789a1ca6a2cfb62ea8eea2429 | bigcode/the-stack | train |
1df356b8b73ec00b64f04ad2 | train | class | class MaxLengthError(BaseValidationError):
"""超出最大长度异常类型"""
| class MaxLengthError(BaseValidationError):
| """超出最大长度异常类型"""
| .data = data
def __repr__(self):
return f"{type(self)}: {self.message}"
class ParamError(BaseValidationError):
"""参数错误异常类型"""
class MinLengthError(BaseValidationError):
"""小于最小长度异常类型"""
class MaxLengthError(BaseValidationError):
| 64 | 64 | 17 | 8 | 56 | LKI/tonggong | tonggong/validations/errors.py | Python | MaxLengthError | MaxLengthError | 20 | 21 | 20 | 20 | 6601271bfc491cb0a6aa4ff3ca24bf8d81966627 | bigcode/the-stack | train |
40e4448792b88cd6954af024 | train | class | class EmailError(BaseValidationError):
"""邮箱格式错误异常类型"""
| class EmailError(BaseValidationError):
| """邮箱格式错误异常类型"""
| ):
"""小于最小长度异常类型"""
class MaxLengthError(BaseValidationError):
"""超出最大长度异常类型"""
class NullError(BaseValidationError):
"""参数为空异常类型"""
class LengthError(BaseValidationError):
"""长度不符合异常类型"""
class EmailError(BaseValidationError):
| 64 | 64 | 15 | 7 | 57 | LKI/tonggong | tonggong/validations/errors.py | Python | EmailError | EmailError | 32 | 33 | 32 | 32 | 77f16e341d3b19ee58886d7e04a02f86920b2cb0 | bigcode/the-stack | train |
9e9d91940aec86645ed80dc1 | train | class | class CollGateMessenger(ApplicationMain):
name = '.'.join(__name__.split('.')[0:-1])
def __init__(self, app_name, app_module):
super(CollGateMessenger, self).__init__(app_name, app_module)
def ready(self):
super().ready()
# register main cache category
from main.cache impo... | class CollGateMessenger(ApplicationMain):
| name = '.'.join(__name__.split('.')[0:-1])
def __init__(self, app_name, app_module):
super(CollGateMessenger, self).__init__(app_name, app_module)
def ready(self):
super().ready()
# register main cache category
from main.cache import cache_manager
cache_manager.reg... | RA/CIRAD
# @license MIT (see LICENSE file)
# @details
from igdectk.common.apphelpers import ApplicationMain
from igdectk.module.manager import module_manager
from igdectk.module.module import Module
from . import tcpclient
class CollGateMessenger(ApplicationMain):
| 64 | 64 | 213 | 7 | 56 | coll-gate/collgate | server/messenger/apps.py | Python | CollGateMessenger | CollGateMessenger | 18 | 52 | 18 | 18 | c5611e5c91649273d37746f0ff473e9cc78fe53d | bigcode/the-stack | train |
4dcc8c7b77780dd0a558f0a6 | train | function | @respond_to('help')
def help(message):
attachments = [{
'I can help you': 'I have found a Ticket sire...',
'author_name': '*AUTOBOT COMMAND LIST*',
'author_link': '',
'text': 'Below is a list of commands AUTOBOT can recieve',
'mrkdwn_in': ['author_name','fields'],
'fields': [
{
'title': 'Ti... | @respond_to('help')
def help(message):
| attachments = [{
'I can help you': 'I have found a Ticket sire...',
'author_name': '*AUTOBOT COMMAND LIST*',
'author_link': '',
'text': 'Below is a list of commands AUTOBOT can recieve',
'mrkdwn_in': ['author_name','fields'],
'fields': [
{
'title': 'Ticket Search',
'value': '@AUTOBOT _tic... |
from slackbot.bot import respond_to
from slackbot.bot import listen_to
import re
import json
@respond_to('help')
def help(message):
| 33 | 105 | 353 | 10 | 22 | bjensen91/AutoTask-Slackbot | help.py | Python | help | help | 7 | 48 | 7 | 8 | 8b8c8850e7a920d66bd5ac987a7250c5de898e5d | bigcode/the-stack | train |
04e8531b392946efcc4c3e46 | train | function | def segment(text: str, custom_dict: Union[Trie, List[str], str] = None) -> List[str]:
if not text or not isinstance(text, str):
return []
if custom_dict:
if isinstance(custom_dict, Trie):
custom_dict = list(custom_dict)
return tokenize(text, custom_dict)
return tokeniz... | def segment(text: str, custom_dict: Union[Trie, List[str], str] = None) -> List[str]:
| if not text or not isinstance(text, str):
return []
if custom_dict:
if isinstance(custom_dict, Trie):
custom_dict = list(custom_dict)
return tokenize(text, custom_dict)
return tokenize(text)
| `GitHub repository <https://github.com/rkcosmos/deepcut>`_
"""
from typing import List, Union
from deepcut import tokenize
from .trie import Trie
def segment(text: str, custom_dict: Union[Trie, List[str], str] = None) -> List[str]:
| 64 | 64 | 73 | 25 | 38 | Datatouille/pythainlp | pythainlp/tokenize/deepcut.py | Python | segment | segment | 18 | 28 | 18 | 18 | 3f3f856d4e6c0db6b3ddf1468336740b4b35c16b | bigcode/the-stack | train |
788c9c4d2340f205dba6d8a4 | train | class | class Config:
def __init__(self):
self.imageShape=(1228,1228,3)
self.inputShape=(256,256,3)
self.pretrainedModel=None
self.classes=3
self.model="PathoNet" #PathoNet,FRRN_A,FCRN_B,Deeplab_xception,Deeplab_mobilenet
self.logPath="logs/"
self.data_path=""
... | class Config:
| def __init__(self):
self.imageShape=(1228,1228,3)
self.inputShape=(256,256,3)
self.pretrainedModel=None
self.classes=3
self.model="PathoNet" #PathoNet,FRRN_A,FCRN_B,Deeplab_xception,Deeplab_mobilenet
self.logPath="logs/"
self.data_path=""
self.loss="ms... | import json
class Config:
| 6 | 72 | 240 | 3 | 2 | GliozzoJ/PathoNet | config.py | Python | Config | Config | 3 | 30 | 3 | 3 | dbee8d79ab05418a87a20afde51770b4746e2a41 | bigcode/the-stack | train |
84993942a75c00379db64a13 | train | class | class Input(object):
interactive = True
def __init__(self, definition=None):
self.interactive = True
self._stream = None
if definition is None:
self.arguments = {}
self.options = {}
self.definition = InputDefinition()
else:
self.b... | class Input(object):
| interactive = True
def __init__(self, definition=None):
self.interactive = True
self._stream = None
if definition is None:
self.arguments = {}
self.options = {}
self.definition = InputDefinition()
else:
self.bind(definition)
... | # -*- coding: utf-8 -*-
import re
from .input_definition import InputDefinition
from ..validators import ValidationError, Callable, Validator
from .input_argument import InvalidArgument
from .input_option import InvalidOption
from ..exceptions import MissingArguments, NoSuchOption
class Input(object):
| 61 | 256 | 1,039 | 4 | 56 | Kolawole39/masonite-guides-tutorial | env/lib/python3.7/site-packages/cleo/inputs/input.py | Python | Input | Input | 11 | 173 | 11 | 12 | e10ea63554e3006b2d86d893de77e42ad300cdde | bigcode/the-stack | train |
63a01fee7a52203ae79b02aa | train | class | class V1SearchSpec(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
... | class V1SearchSpec(object):
| """NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The... | #!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | 241 | 256 | 1,455 | 7 | 233 | rimon-safesitehq/polyaxon | sdks/python/http_client/v1/polyaxon_sdk/models/v1_search_spec.py | Python | V1SearchSpec | V1SearchSpec | 38 | 267 | 38 | 38 | e2c2f3d990627cb0e20b96a97151b90e485183b8 | bigcode/the-stack | train |
14a13e231c0040ac84b0faa2 | train | class | class CollectionsSOPS(object):
"""Collections of SOPS APIS"""
def __init__(self, client):
self.client = client
self.create_task = ComponentAPI(
client=self.client, method="POST", path="/api/c/compapi{bk_api_ver}/sops/create_task/", description="创建任务"
)
self.get_task... | class CollectionsSOPS(object):
| """Collections of SOPS APIS"""
def __init__(self, client):
self.client = client
self.create_task = ComponentAPI(
client=self.client, method="POST", path="/api/c/compapi{bk_api_ver}/sops/create_task/", description="创建任务"
)
self.get_task_status = ComponentAPI(
... | "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://opensource.org/licenses/MIT
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 ... | 104 | 104 | 348 | 6 | 97 | brookylin/bk-sops | packages/blueking/component/apis/sops.py | Python | CollectionsSOPS | CollectionsSOPS | 17 | 55 | 17 | 17 | b52d7f07eac42489c824aa3bc1b3afddb386cf19 | bigcode/the-stack | train |
4ded03b1c0d1af6122ce6b83 | train | class | class ExecState(IntEnum):
"""ActiveX ExecStateEnum"""
eBad = 0
eIdle = 1
eRunTopLevel = 2
eRunning = 3
| class ExecState(IntEnum):
| """ActiveX ExecStateEnum"""
eBad = 0
eIdle = 1
eRunTopLevel = 2
eRunning = 3
| com.client import VARIANT
import numpy as np
from autolv.vistrings import parse_vistrings
from autolv.datatypes import (
IORefNum,
make_control,
DataFlow,
valididentifier,
TimeStamp,
Array,
Cluster,
)
class ExecState(IntEnum):
| 64 | 64 | 44 | 6 | 58 | pkthong/autolv | autolv/interface.py | Python | ExecState | ExecState | 29 | 35 | 29 | 29 | 3ba9a6e1c81bdf40ec954f4299960c2a002d4e0a | bigcode/the-stack | train |
59d94a957ac9e5639029d628 | train | class | class VI:
"""ActiveX connection to a VI
Parameters
----------
viref : win32com.client.CDispatch
"""
def __init__(self, viref: win32com.client.CDispatch):
self._vi = viref
self.name = self._vi.Name
methods = [
"ExportVIStrings",
"SetControlValue",... | class VI:
| """ActiveX connection to a VI
Parameters
----------
viref : win32com.client.CDispatch
"""
def __init__(self, viref: win32com.client.CDispatch):
self._vi = viref
self.name = self._vi.Name
methods = [
"ExportVIStrings",
"SetControlValue",
... | """Interact with LabVIEW VIs from Python"""
# pylint:disable=no-name-in-module
from pathlib import Path
from tempfile import TemporaryDirectory
from enum import IntEnum
import asyncio
from datetime import timezone
import itertools
import warnings
import struct
import pythoncom
from pythoncom import VT_ARRAY, VT_BYREF, ... | 253 | 256 | 2,052 | 3 | 249 | pkthong/autolv | autolv/interface.py | Python | VI | VI | 49 | 311 | 49 | 49 | 58f2d486824f1c605c9987e96034acbd82207b2b | bigcode/the-stack | train |
f8909da974d47855015f4147 | train | class | class App:
"""ActiveX connection to LabVIEW application"""
def __init__(self):
self.__enter__()
@property
def version(self) -> str:
"""LabVIEW version"""
return self._lv.Version
def get_VI(self, vi_name: str) -> VI:
"""Instantiate a VI object
Parameters
... | class App:
| """ActiveX connection to LabVIEW application"""
def __init__(self):
self.__enter__()
@property
def version(self) -> str:
"""LabVIEW version"""
return self._lv.Version
def get_VI(self, vi_name: str) -> VI:
"""Instantiate a VI object
Parameters
-----... | ctrl.as_dict().values():
cvalue = clstr_ctrl.value
if isinstance(clstr_ctrl, Array):
cvalue = VARIANT(VT_ARRAY | VT_VARIANT, cvalue)
clstr_values.append(cvalue)
value = VARIANT(VT_ARRAY | VT_VARIANT, clstr_values)
... | 209 | 209 | 697 | 3 | 205 | pkthong/autolv | autolv/interface.py | Python | App | App | 315 | 414 | 315 | 315 | 9b7d3a9aa81383dfcdbdb89f47f237dd459f84a1 | bigcode/the-stack | train |
9569800c371c8573e581e95e | train | class | class FPState(IntEnum):
"""Front panel state"""
Invalid = 0
Standard = 1
Closed = 2
Hidden = 3
Minimized = 4
Maximized = 5
| class FPState(IntEnum):
| """Front panel state"""
Invalid = 0
Standard = 1
Closed = 2
Hidden = 3
Minimized = 4
Maximized = 5
| valididentifier,
TimeStamp,
Array,
Cluster,
)
class ExecState(IntEnum):
"""ActiveX ExecStateEnum"""
eBad = 0
eIdle = 1
eRunTopLevel = 2
eRunning = 3
class FPState(IntEnum):
| 64 | 64 | 50 | 6 | 57 | pkthong/autolv | autolv/interface.py | Python | FPState | FPState | 38 | 46 | 38 | 38 | 54a9f346f23f75c947f372e13ec659f1c7fc053b | bigcode/the-stack | train |
a099ab7d1cbc804f435dd5d7 | train | class | class FireData():
def __init__(self, cfg):
self.cfg = cfg
def getTrainValDataloader(self):
if self.cfg['val_path'] != '':
print("[INFO] val_path is not none, not use kflod to split train-val data ...")
train_data = getFileNames(self.cfg['train_path']... | class FireData():
| def __init__(self, cfg):
self.cfg = cfg
def getTrainValDataloader(self):
if self.cfg['val_path'] != '':
print("[INFO] val_path is not none, not use kflod to split train-val data ...")
train_data = getFileNames(self.cfg['train_path'])
trai... |
import os
import random
import numpy as np
from sklearn.model_selection import KFold
import cv2
from torchvision import transforms
from fire.datatools import getDataLoader, getFileNames
from fire.dataaug_user import TrainDataAug
class FireData():
| 57 | 245 | 817 | 4 | 52 | fire717/fire | fire/data.py | Python | FireData | FireData | 15 | 121 | 15 | 15 | 65b1bf1bf789d5d8084f45433c3b0c7309749e16 | bigcode/the-stack | train |
7a9bf843975ebc7156d2e9b3 | train | class | class SelectQueryHandler:
def is_temporal_query(query):
# will add more clauses as they're implemented
temporal_clause_pattern = re.compile(r"(as of|to|between|contained in)")
temporal_clause_matches = temporal_clause_pattern.finditer(query)
temporal_clause_match = None
f... | class SelectQueryHandler:
| def is_temporal_query(query):
# will add more clauses as they're implemented
temporal_clause_pattern = re.compile(r"(as of|to|between|contained in)")
temporal_clause_matches = temporal_clause_pattern.finditer(query)
temporal_clause_match = None
for match in temporal_claus... | SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import re
class SelectQueryHandler:
| 64 | 64 | 97 | 5 | 58 | thatdevsherry/historia | historia/intercept/select_handler.py | Python | SelectQueryHandler | SelectQueryHandler | 25 | 42 | 25 | 25 | f2814977a53465f686ca7305ba1b3e8d44c92368 | bigcode/the-stack | train |
8bfd94b82eeb73d3d260e294 | train | function | def identify_cols(data):
# Create empty dictionary and lists for dimensions and measures
column_data_types = {}
dimensions = []
measures = []
# Populate a dictionary with columns and data types
for i in data.columns.values:
column_data_types[i] = str(data[i].dtype)
# Identify the ... | def identify_cols(data):
# Create empty dictionary and lists for dimensions and measures
| column_data_types = {}
dimensions = []
measures = []
# Populate a dictionary with columns and data types
for i in data.columns.values:
column_data_types[i] = str(data[i].dtype)
# Identify the datatypes in each column and split them into categorical dimensions or continuous measures
... | """
"""
import pandas as pd
def parse_arguments(args):
pass
def identify_cols(data):
# Create empty dictionary and lists for dimensions and measures
| 33 | 64 | 140 | 17 | 15 | nmannheimer/DataWhisperer2.0 | whisper/util.py | Python | identify_cols | identify_cols | 12 | 30 | 12 | 14 | 299112d37b1cd04489987df1e3508cd9e166ae4a | bigcode/the-stack | train |
18e716d4d881bea7c8ec87ac | train | function | def parse_arguments(args):
pass
| def parse_arguments(args):
| pass
| """
"""
import pandas as pd
def parse_arguments(args):
| 13 | 64 | 8 | 5 | 7 | nmannheimer/DataWhisperer2.0 | whisper/util.py | Python | parse_arguments | parse_arguments | 9 | 10 | 9 | 9 | 5ccbfc49ee68562aba9254534301858991336f7a | bigcode/the-stack | train |
8a60e727352aafc1a015ff88 | train | class | class S26_WCheckError(SlotCheckError):
""" """
pass
| class S26_WCheckError(SlotCheckError):
| """ """
pass
| 26_WCheckError
You must have W0 < 2*R1
"""
if self.R1 * 2 <= self.W0:
raise S26_WCheckError("You must have W0 < 2*R1")
class S26_WCheckError(SlotCheckError):
| 64 | 64 | 17 | 11 | 53 | ajpina/pyleecan | pyleecan/Methods/Slot/SlotW26/check.py | Python | S26_WCheckError | S26_WCheckError | 27 | 30 | 27 | 27 | 536696d5b67b9c5675a62ebddf46e15ee47bf199 | bigcode/the-stack | train |
344c69807c00b1c1d7297afc | train | function | def check(self):
"""Check that the SlotW26 object is correct
Parameters
----------
self : SlotW26
A SlotW26 object
Returns
-------
None
Raises
-------
S26_WCheckError
You must have W0 < 2*R1
"""
if self.R1 * 2 <= self.W0:
raise S26_WCheckError("... | def check(self):
| """Check that the SlotW26 object is correct
Parameters
----------
self : SlotW26
A SlotW26 object
Returns
-------
None
Raises
-------
S26_WCheckError
You must have W0 < 2*R1
"""
if self.R1 * 2 <= self.W0:
raise S26_WCheckError("You must have W0 ... | # -*- coding: utf-8 -*-
from ....Methods.Slot.Slot.check import SlotCheckError
def check(self):
| 25 | 64 | 103 | 4 | 20 | ajpina/pyleecan | pyleecan/Methods/Slot/SlotW26/check.py | Python | check | check | 6 | 24 | 6 | 6 | dc354c2924c4a9b70d3d6b12fc2a26f29e2305f5 | bigcode/the-stack | train |
ec5271107e84be46c5aa34cb | train | class | class User(BaseModel):
username: str
password: str
| class User(BaseModel):
| username: str
password: str
| import os
from passlib.context import CryptContext
from pydantic import BaseModel
class User(BaseModel):
| 24 | 64 | 15 | 5 | 18 | LuQ232/Chessboard-Importer | app/code/authorization.py | Python | User | User | 5 | 7 | 5 | 5 | 6ca847b554a0786696c3cb1519dc3505f63cbe71 | bigcode/the-stack | train |
05ccc71451e42b23f1f20232 | train | class | class Auth:
@staticmethod
def verify_password(plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password)
@staticmethod
def get_password_hash(password):
return pwd_context.hash(password)
@staticmethod
def get_user(data_base, username: str):
... | class Auth:
@staticmethod
| def verify_password(plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password)
@staticmethod
def get_password_hash(password):
return pwd_context.hash(password)
@staticmethod
def get_user(data_base, username: str):
if username in data_base... |
from pydantic import BaseModel
class User(BaseModel):
username: str
password: str
class Settings(BaseModel):
authjwt_secret_key: str = os.environ['SECRET']
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
class Auth:
@staticmethod
| 64 | 64 | 144 | 7 | 57 | LuQ232/Chessboard-Importer | app/code/authorization.py | Python | Auth | Auth | 16 | 42 | 16 | 18 | 57652f8b1ab3f099dc2496743b3313897fce1624 | bigcode/the-stack | train |
f85556d28ef2a8675ab94b92 | train | class | class Settings(BaseModel):
authjwt_secret_key: str = os.environ['SECRET']
| class Settings(BaseModel):
| authjwt_secret_key: str = os.environ['SECRET']
| import os
from passlib.context import CryptContext
from pydantic import BaseModel
class User(BaseModel):
username: str
password: str
class Settings(BaseModel):
| 39 | 64 | 18 | 5 | 33 | LuQ232/Chessboard-Importer | app/code/authorization.py | Python | Settings | Settings | 10 | 11 | 10 | 10 | ebfb589a1bb6efd0635de0a06fc912992524a75f | bigcode/the-stack | train |
4ba7138fcdd87aae87ee38cd | train | class | class CompanieshouseSpider(scrapy.Spider):
name = "companieshouse"
allowed_domains = ["beta.companieshouse.gov.uk"]
start_urls = ["https://beta.companieshouse.gov.uk/officers/eYKVcUJujkKZPwW0R6P16Tu6cmI/appointments"]
def parse(self, response):
uri = urlparse(response.url)
for sel in re... | class CompanieshouseSpider(scrapy.Spider):
| name = "companieshouse"
allowed_domains = ["beta.companieshouse.gov.uk"]
start_urls = ["https://beta.companieshouse.gov.uk/officers/eYKVcUJujkKZPwW0R6P16Tu6cmI/appointments"]
def parse(self, response):
uri = urlparse(response.url)
for sel in response.xpath('//main[@id="page-container"]/... | import scrapy, re
from companieshouse.items import CompanieshouseItem, OfficerItem
from urlparse import urlparse
class CompanieshouseSpider(scrapy.Spider):
| 33 | 165 | 551 | 9 | 23 | xaxes/companieshouse | companieshouse/spiders/companieshouse_spider.py | Python | CompanieshouseSpider | CompanieshouseSpider | 6 | 52 | 6 | 6 | 52c4e311e502df9e878891e7311c6ed69fd1e768 | bigcode/the-stack | train |
e293dcf94d9a2aa5c66ae6f6 | train | function | def verify_request(public_key: str, request: Request, body: str) -> bool:
verify_key = VerifyKey(bytes.fromhex(public_key))
try:
signature = request.headers["X-Signature-Ed25519"]
timestamp = request.headers["X-Signature-Timestamp"]
except KeyError:
return False
try:
ve... | def verify_request(public_key: str, request: Request, body: str) -> bool:
| verify_key = VerifyKey(bytes.fromhex(public_key))
try:
signature = request.headers["X-Signature-Ed25519"]
timestamp = request.headers["X-Signature-Timestamp"]
except KeyError:
return False
try:
verify_key.verify(f'{timestamp}{body}'.encode(), bytes.fromhex(signature))
... | OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from aiohttp.web_request import Request
from nacl.signing import VerifyKey
from nacl.exceptions import BadSignatureError
def verify_request(public_key: str, request: Request, body: str) -> bool:
| 64 | 64 | 104 | 19 | 44 | justanotherbyte/discord-rest | drest/security.py | Python | verify_request | verify_request | 31 | 44 | 31 | 31 | 3517bda5d12b3cdbf96829c6ba66f69300aed422 | bigcode/the-stack | train |
b4cc37284f35c2d8c56f4c99 | train | function | def test_total_packet_sizes(trace, sample_trace):
"""It should return the correct amount of packet sizes."""
# trace parameterised and may be the same as sample_trace, that's okay.
# We're primarily testing the version of trace that's a recarray here
expected = _features.total_packet_sizes(sample_trace)... | def test_total_packet_sizes(trace, sample_trace):
| """It should return the correct amount of packet sizes."""
# trace parameterised and may be the same as sample_trace, that's okay.
# We're primarily testing the version of trace that's a recarray here
expected = _features.total_packet_sizes(sample_trace)
result = _features.total_packet_sizes(trace)
... | .
"""
ref_in, ref_out = rf_fextract.perc_inc_out(as_lines(sample_trace))
result = _features.in_out_fraction(trace)
assert ref_in == result['fraction-incoming']
assert ref_out == result['fraction-outgoing']
def test_total_packet_sizes(trace, sample_trace):
| 64 | 64 | 81 | 10 | 54 | jpcsmith/wf-tools | tests/classifiers/kfingerprinting/test_features.py | Python | test_total_packet_sizes | test_total_packet_sizes | 144 | 150 | 144 | 144 | 2404476c30d8e1ca5ad00c29258e6d6f83a27b1b | bigcode/the-stack | train |
135e282c60e92e8fd4cc403b | train | function | @pytest.fixture(name="dataset_seq")
def fixture_dataset_seq(dataset) -> tuple:
"""Return multipe (times, sizes, expected_features) where each is
an ndarray storing multiple samples.
"""
sizes, times, classes = dataset
return times[:10], sizes[:10]
times = times[:10]
features = np.ndarray((l... | @pytest.fixture(name="dataset_seq")
def fixture_dataset_seq(dataset) -> tuple:
| """Return multipe (times, sizes, expected_features) where each is
an ndarray storing multiple samples.
"""
sizes, times, classes = dataset
return times[:10], sizes[:10]
times = times[:10]
features = np.ndarray((len(sizes), 165), dtype=float)
for i, (size_row, times_row) in enumerate(zip... | 200, 300])
def test_extract_features_length(n_features, trace):
"""The number of features should be as expected."""
features = _features.extract_features(trace, n_features)
assert len(features) == n_features
@pytest.fixture(name="dataset_seq")
def fixture_dataset_seq(dataset) -> tuple:
| 64 | 64 | 131 | 16 | 47 | jpcsmith/wf-tools | tests/classifiers/kfingerprinting/test_features.py | Python | fixture_dataset_seq | fixture_dataset_seq | 197 | 211 | 197 | 198 | 08539833b389daad8ca0d4c6e58f0126c9a1788e | bigcode/the-stack | train |
52ce9ba978149cd5772d054a | train | function | def test_packet_concentration_stats(trace, sample_trace: Trace):
"""Concentrations should match the reference implementation."""
*ref_stats, ref_conc = rf_fextract.pkt_concentration_stats(
as_lines(sample_trace))
stats, conc = _features.packet_concentration_stats(trace, 20)
assert ref_stats == ... | def test_packet_concentration_stats(trace, sample_trace: Trace):
| """Concentrations should match the reference implementation."""
*ref_stats, ref_conc = rf_fextract.pkt_concentration_stats(
as_lines(sample_trace))
stats, conc = _features.packet_concentration_stats(trace, 20)
assert ref_stats == list(stats.values())
assert ref_conc == conc
| reference implementation.
"""
ref_result = rf_fextract.first_and_last_30_pkts_stats(
as_lines(sample_trace))
result = _features.head_and_tail_concentration(trace, 30)
assert ref_result == list(result.values())
def test_packet_concentration_stats(trace, sample_trace: Trace):
| 64 | 64 | 81 | 13 | 51 | jpcsmith/wf-tools | tests/classifiers/kfingerprinting/test_features.py | Python | test_packet_concentration_stats | test_packet_concentration_stats | 106 | 113 | 106 | 106 | 2dff08ced5d0d68c1ed58ec9f08ecc0ab6158ae1 | bigcode/the-stack | train |
8263933bb170d84bc2a38b70 | train | function | @pytest.fixture(name="trace", params=["recarray", "Trace"])
def fixture_trace(request, sample_trace):
"""Return trace data as a recarray or Trace. To get the same data
as a trace use the sample_trace fixture.
"""
if request.param == "Trace":
return sample_trace
assert request.param == "reca... | @pytest.fixture(name="trace", params=["recarray", "Trace"])
def fixture_trace(request, sample_trace):
| """Return trace data as a recarray or Trace. To get the same data
as a trace use the sample_trace fixture.
"""
if request.param == "Trace":
return sample_trace
assert request.param == "recarray"
trace = np.asarray(sample_trace, dtype=[
("timestamp", "f8"), ("direction", "i1"), (... | ]
sizes = trace[:, 1] * trace[:, 2]
return namedtuple( # type: ignore
"split_trace", ["timestamps", "sizes"])(times, sizes)
@pytest.fixture(name="trace", params=["recarray", "Trace"])
def fixture_trace(request, sample_trace):
| 64 | 64 | 116 | 22 | 42 | jpcsmith/wf-tools | tests/classifiers/kfingerprinting/test_features.py | Python | fixture_trace | fixture_trace | 32 | 44 | 32 | 33 | d7ea442a99650415c55ea644741e8091873a66f5 | bigcode/the-stack | train |
47228da0ecf8e6f2534a6ddc | train | function | def test_extract_features_split(sample_trace: Trace, split_trace):
"""The resulting feature sets should be equivalent for the
first 46 features.
"""
times, sizes = split_trace
features = _features.extract_features(sample_trace)
features_split = _features.extract_features(sizes=sizes, timestamps=... | def test_extract_features_split(sample_trace: Trace, split_trace):
| """The resulting feature sets should be equivalent for the
first 46 features.
"""
times, sizes = split_trace
features = _features.extract_features(sample_trace)
features_split = _features.extract_features(sizes=sizes, timestamps=times)
assert len(features) == len(features_split)
assert ... | converted = _features.make_trace_array(
timestamps=split_trace.timestamps, sizes=split_trace.sizes
).astype('f,f,f').view('f').reshape((-1, 3))
np.testing.assert_allclose(expected, converted)
def test_extract_features_split(sample_trace: Trace, split_trace):
| 64 | 64 | 143 | 13 | 51 | jpcsmith/wf-tools | tests/classifiers/kfingerprinting/test_features.py | Python | test_extract_features_split | test_extract_features_split | 172 | 187 | 172 | 172 | 8f7ba47b015b3973dca070242e270868518ed708 | bigcode/the-stack | train |
535def6421640dca27988b98 | train | function | def test_packet_ordering_stats(trace, sample_trace: Trace):
"""The packet ordering statistics should match the reference."""
ref_stats = rf_fextract.avg_pkt_ordering_stats(as_lines(sample_trace))
stats = _features.packet_ordering_stats(trace)
assert ref_stats == tuple(stats.values())
| def test_packet_ordering_stats(trace, sample_trace: Trace):
| """The packet ordering statistics should match the reference."""
ref_stats = rf_fextract.avg_pkt_ordering_stats(as_lines(sample_trace))
stats = _features.packet_ordering_stats(trace)
assert ref_stats == tuple(stats.values())
| ref_stats, ref_pps = rf_fextract.number_per_sec(as_lines(sample_trace))
stats, pps = _features.packets_per_second_stats(trace)
assert ref_stats == list(stats.values())
assert ref_pps == pps
def test_packet_ordering_stats(trace, sample_trace: Trace):
| 64 | 64 | 61 | 13 | 50 | jpcsmith/wf-tools | tests/classifiers/kfingerprinting/test_features.py | Python | test_packet_ordering_stats | test_packet_ordering_stats | 125 | 130 | 125 | 125 | 8f6547bb613c19c74b99deaac48b423c8a9aadc1 | bigcode/the-stack | train |
1168f95ccbedf48cf8a19f0c | train | function | def test_make_trace_array(split_trace, sample_trace):
"""It should correctly convert a split_trace to a trace."""
expected = sample_trace
converted = _features.make_trace_array(
timestamps=split_trace.timestamps, sizes=split_trace.sizes
).astype('f,f,f').view('f').reshape((-1, 3))
np.testing... | def test_make_trace_array(split_trace, sample_trace):
| """It should correctly convert a split_trace to a trace."""
expected = sample_trace
converted = _features.make_trace_array(
timestamps=split_trace.timestamps, sizes=split_trace.sizes
).astype('f,f,f').view('f').reshape((-1, 3))
np.testing.assert_allclose(expected, converted)
| sets should be equivalent for the
first 46 features.
"""
ref_features = rf_fextract.TOTAL_FEATURES(as_lines(sample_trace))
features = _features.extract_features(trace)
assert ref_features[:46] == tuple(features[:46])
def test_make_trace_array(split_trace, sample_trace):
| 64 | 64 | 82 | 11 | 53 | jpcsmith/wf-tools | tests/classifiers/kfingerprinting/test_features.py | Python | test_make_trace_array | test_make_trace_array | 163 | 169 | 163 | 163 | b0e8b31a1b07f39a875bbbc5645dd4f44370e204 | bigcode/the-stack | train |
073e5014bc1aaab77005a658 | train | function | def test_time_percentiles(trace, sample_trace: Trace):
"""The percentiles of the timestamps should match the reference."""
ref_result = rf_fextract.time_percentile_stats(as_lines(sample_trace))
result = _features.time_percentiles(trace)
assert ref_result == [
result['time::in::percentile-25'], ... | def test_time_percentiles(trace, sample_trace: Trace):
| """The percentiles of the timestamps should match the reference."""
ref_result = rf_fextract.time_percentile_stats(as_lines(sample_trace))
result = _features.time_percentiles(trace)
assert ref_result == [
result['time::in::percentile-25'], result['time::in::percentile-50'],
result['time... | result['interarrival::overall::std'],
result['interarrival::in::percentile-75'],
result['interarrival::out::percentile-75'],
result['interarrival::overall::percentile-75'],
)]
def test_time_percentiles(trace, sample_trace: Trace):
| 64 | 64 | 199 | 12 | 52 | jpcsmith/wf-tools | tests/classifiers/kfingerprinting/test_features.py | Python | test_time_percentiles | test_time_percentiles | 70 | 84 | 70 | 70 | cbae1cbd1ae789ee6d2125f5f02ca6849038b1d0 | bigcode/the-stack | train |
e1d634af95698734fcb23844 | train | function | def as_lines(trace) -> Sequence[str]:
"""Return the trace as a sequence of lines."""
return [' '.join(str(val) for val in pkt) for pkt in trace]
| def as_lines(trace) -> Sequence[str]:
| """Return the trace as a sequence of lines."""
return [' '.join(str(val) for val in pkt) for pkt in trace]
| return sample_trace
assert request.param == "recarray"
trace = np.asarray(sample_trace, dtype=[
("timestamp", "f8"), ("direction", "i1"), ("size", "i8")
])
return trace.view(np.recarray)
def as_lines(trace) -> Sequence[str]:
| 64 | 64 | 38 | 9 | 55 | jpcsmith/wf-tools | tests/classifiers/kfingerprinting/test_features.py | Python | as_lines | as_lines | 47 | 49 | 47 | 47 | a94bf573cb7a05b50c4185123fde1e9d35769a1b | bigcode/the-stack | train |
efe236e2024dc02167ac8279 | train | function | @pytest.fixture
def split_trace(sample_trace) -> tuple:
"""Return a sample trace as timestamps and sizes."""
trace = np.asarray(sample_trace)
times = trace[:, 0]
sizes = trace[:, 1] * trace[:, 2]
return namedtuple( # type: ignore
"split_trace", ["timestamps", "sizes"])(times, sizes)
| @pytest.fixture
def split_trace(sample_trace) -> tuple:
| """Return a sample trace as timestamps and sizes."""
trace = np.asarray(sample_trace)
times = trace[:, 0]
sizes = trace[:, 1] * trace[:, 2]
return namedtuple( # type: ignore
"split_trace", ["timestamps", "sizes"])(times, sizes)
| printing import _features
@pytest.fixture
def sample_trace() -> Trace:
"""Return a sample real world trace."""
path = Path(__file__).with_name('sample-trace.json')
return TraceData.deserialise(path.read_text()).trace
@pytest.fixture
def split_trace(sample_trace) -> tuple:
| 64 | 64 | 80 | 12 | 51 | jpcsmith/wf-tools | tests/classifiers/kfingerprinting/test_features.py | Python | split_trace | split_trace | 22 | 29 | 22 | 23 | bab0e1184428cc0b967f093fd30b1410b0862133 | bigcode/the-stack | train |
e1823b3c9c00bdde1a496c84 | train | function | @pytest.mark.parametrize('n_features', [100, 300])
def test_extract_features_sequence_mp(dataset_seq, n_features):
"""It should correct extract features that are provided as a sequence.
"""
times, sizes = dataset_seq
features = _features.extract_features_sequence(
timestamps=times, sizes=sizes, ... | @pytest.mark.parametrize('n_features', [100, 300])
def test_extract_features_sequence_mp(dataset_seq, n_features):
| """It should correct extract features that are provided as a sequence.
"""
times, sizes = dataset_seq
features = _features.extract_features_sequence(
timestamps=times, sizes=sizes, max_size=n_features, n_jobs=3)
expected_features = np.asarray([
_features.extract_features(
... | =size_row, timestamps=time_row, max_size=n_features)
for size_row, time_row in zip(sizes, times)
])
np.testing.assert_allclose(expected_features, features)
@pytest.mark.parametrize('n_features', [100, 300])
def test_extract_features_sequence_mp(dataset_seq, n_features):
| 64 | 64 | 131 | 25 | 39 | jpcsmith/wf-tools | tests/classifiers/kfingerprinting/test_features.py | Python | test_extract_features_sequence_mp | test_extract_features_sequence_mp | 230 | 243 | 230 | 231 | f5f2f113dd9b8b3e4a901a43bdc6a77015d42429 | bigcode/the-stack | train |
4cc8ec3b6eb60d2986f4a500 | train | function | def test_interarrival_stats(trace, sample_trace: Trace):
"""The interarrival stats computation should match the reference."""
ref_result = rf_fextract.interarrival_maxminmeansd_stats(sample_trace)
result = _features.interarrival_stats(trace)
assert ref_result == [(
result['interarrival::in::max... | def test_interarrival_stats(trace, sample_trace: Trace):
| """The interarrival stats computation should match the reference."""
ref_result = rf_fextract.interarrival_maxminmeansd_stats(sample_trace)
result = _features.interarrival_stats(trace)
assert ref_result == [(
result['interarrival::in::max'], result['interarrival::out::max'],
result['int... | "i8")
])
return trace.view(np.recarray)
def as_lines(trace) -> Sequence[str]:
"""Return the trace as a sequence of lines."""
return [' '.join(str(val) for val in pkt) for pkt in trace]
def test_interarrival_stats(trace, sample_trace: Trace):
| 64 | 64 | 187 | 12 | 52 | jpcsmith/wf-tools | tests/classifiers/kfingerprinting/test_features.py | Python | test_interarrival_stats | test_interarrival_stats | 52 | 67 | 52 | 52 | 0c4ed2e014a4181da7141ef313e5e760cd08b44a | bigcode/the-stack | train |
282c4b504b76d6535b4ad66f | train | function | def test_packets_per_second(trace, sample_trace: Trace):
"""The packets per second should match the reference implementation."""
*ref_stats, ref_pps = rf_fextract.number_per_sec(as_lines(sample_trace))
stats, pps = _features.packets_per_second_stats(trace)
assert ref_stats == list(stats.values())
a... | def test_packets_per_second(trace, sample_trace: Trace):
| """The packets per second should match the reference implementation."""
*ref_stats, ref_pps = rf_fextract.number_per_sec(as_lines(sample_trace))
stats, pps = _features.packets_per_second_stats(trace)
assert ref_stats == list(stats.values())
assert ref_pps == pps
| ref_conc = rf_fextract.pkt_concentration_stats(
as_lines(sample_trace))
stats, conc = _features.packet_concentration_stats(trace, 20)
assert ref_stats == list(stats.values())
assert ref_conc == conc
def test_packets_per_second(trace, sample_trace: Trace):
| 64 | 64 | 77 | 12 | 51 | jpcsmith/wf-tools | tests/classifiers/kfingerprinting/test_features.py | Python | test_packets_per_second | test_packets_per_second | 116 | 122 | 116 | 116 | f751805319ca1a3cc6e8b860ba50133cb8d893ec | bigcode/the-stack | train |
4ae5310ee346a26868716727 | train | function | @pytest.fixture
def sample_trace() -> Trace:
"""Return a sample real world trace."""
path = Path(__file__).with_name('sample-trace.json')
return TraceData.deserialise(path.read_text()).trace
| @pytest.fixture
def sample_trace() -> Trace:
| """Return a sample real world trace."""
path = Path(__file__).with_name('sample-trace.json')
return TraceData.deserialise(path.read_text()).trace
|
from typing import Sequence, Tuple
from collections import namedtuple
import pytest
import numpy as np
from lab.trace import TraceData, Trace
from lab.classifiers.kfingerprinting import rf_fextract
from lab.classifiers.kfingerprinting import _features
@pytest.fixture
def sample_trace() -> Trace:
| 64 | 64 | 47 | 10 | 53 | jpcsmith/wf-tools | tests/classifiers/kfingerprinting/test_features.py | Python | sample_trace | sample_trace | 15 | 19 | 15 | 16 | ef731ea2aa7588e94a527e41bfb83f95ea59e4f0 | bigcode/the-stack | train |
0f3db4bca0cbe9bbb9d14057 | train | function | def test_in_out_fraction(trace, sample_trace: Trace):
"""The fraction of incoming and outgoing packets should match the
reference implementation.
"""
ref_in, ref_out = rf_fextract.perc_inc_out(as_lines(sample_trace))
result = _features.in_out_fraction(trace)
assert ref_in == result['fraction-in... | def test_in_out_fraction(trace, sample_trace: Trace):
| """The fraction of incoming and outgoing packets should match the
reference implementation.
"""
ref_in, ref_out = rf_fextract.perc_inc_out(as_lines(sample_trace))
result = _features.in_out_fraction(trace)
assert ref_in == result['fraction-incoming']
assert ref_out == result['fraction-outgoi... | _trace: Trace):
"""The packet ordering statistics should match the reference."""
ref_stats = rf_fextract.avg_pkt_ordering_stats(as_lines(sample_trace))
stats = _features.packet_ordering_stats(trace)
assert ref_stats == tuple(stats.values())
def test_in_out_fraction(trace, sample_trace: Trace):
| 64 | 64 | 82 | 12 | 52 | jpcsmith/wf-tools | tests/classifiers/kfingerprinting/test_features.py | Python | test_in_out_fraction | test_in_out_fraction | 133 | 141 | 133 | 133 | d35e56fd5f30aa7fa022a8295c4ac654b645cd28 | bigcode/the-stack | train |
fccc7e3f799d909d431742a3 | train | function | def test_packet_counts(trace, sample_trace: Trace):
"""The packet counts should match the reference."""
ref_result = rf_fextract.number_pkt_stats(as_lines(sample_trace))
result = _features.packet_counts(trace)
assert ref_result == tuple(result.values())
| def test_packet_counts(trace, sample_trace: Trace):
| """The packet counts should match the reference."""
ref_result = rf_fextract.number_pkt_stats(as_lines(sample_trace))
result = _features.packet_counts(trace)
assert ref_result == tuple(result.values())
| 100'],
result['time::overall::percentile-25'],
result['time::overall::percentile-50'],
result['time::overall::percentile-75'],
result['time::overall::percentile-100'],
]
def test_packet_counts(trace, sample_trace: Trace):
| 63 | 64 | 54 | 11 | 52 | jpcsmith/wf-tools | tests/classifiers/kfingerprinting/test_features.py | Python | test_packet_counts | test_packet_counts | 87 | 92 | 87 | 87 | 6fad2d80a6044a6b6fb2584e08316066e852b35f | bigcode/the-stack | train |
072455fbf860cd653ebe7f79 | train | function | def test_extract_features(trace, sample_trace: Trace):
"""The resulting feature sets should be equivalent for the
first 46 features.
"""
ref_features = rf_fextract.TOTAL_FEATURES(as_lines(sample_trace))
features = _features.extract_features(trace)
assert ref_features[:46] == tuple(features[:46]... | def test_extract_features(trace, sample_trace: Trace):
| """The resulting feature sets should be equivalent for the
first 46 features.
"""
ref_features = rf_fextract.TOTAL_FEATURES(as_lines(sample_trace))
features = _features.extract_features(trace)
assert ref_features[:46] == tuple(features[:46])
| may be the same as sample_trace, that's okay.
# We're primarily testing the version of trace that's a recarray here
expected = _features.total_packet_sizes(sample_trace)
result = _features.total_packet_sizes(trace)
assert expected == result
def test_extract_features(trace, sample_trace: Trace):
| 64 | 64 | 69 | 11 | 52 | jpcsmith/wf-tools | tests/classifiers/kfingerprinting/test_features.py | Python | test_extract_features | test_extract_features | 153 | 160 | 153 | 153 | cd6772382a43e12f0f46d3c474e8a2bcd4fd53a5 | bigcode/the-stack | train |
eb93f40d57a0ba4a63c429d4 | train | function | @pytest.mark.parametrize('n_features', [50, 100, 150, 200, 300])
def test_extract_features_length(n_features, trace):
"""The number of features should be as expected."""
features = _features.extract_features(trace, n_features)
assert len(features) == n_features
| @pytest.mark.parametrize('n_features', [50, 100, 150, 200, 300])
def test_extract_features_length(n_features, trace):
| """The number of features should be as expected."""
features = _features.extract_features(trace, n_features)
assert len(features) == n_features
| _DEFAULT_FEATURES
):
np.testing.assert_allclose(
expected, result, err_msg=f"Result differs in feature {tag!r}")
@pytest.mark.parametrize('n_features', [50, 100, 150, 200, 300])
def test_extract_features_length(n_features, trace):
| 63 | 64 | 64 | 32 | 31 | jpcsmith/wf-tools | tests/classifiers/kfingerprinting/test_features.py | Python | test_extract_features_length | test_extract_features_length | 190 | 194 | 190 | 191 | 4b67d082bb0ef86a02b2fe902400fed22110cf47 | bigcode/the-stack | train |
0617a3fd0dbe6c9d9318ad0b | train | function | @pytest.mark.parametrize('n_features', [100, 300])
def test_extract_features_sequence(dataset_seq, n_features):
"""It should correct extract features that are provided as a sequence.
"""
times, sizes = dataset_seq
features = _features.extract_features_sequence(
timestamps=times, sizes=sizes, max... | @pytest.mark.parametrize('n_features', [100, 300])
def test_extract_features_sequence(dataset_seq, n_features):
| """It should correct extract features that are provided as a sequence.
"""
times, sizes = dataset_seq
features = _features.extract_features_sequence(
timestamps=times, sizes=sizes, max_size=n_features)
expected_features = np.asarray([
_features.extract_features(
sizes=si... | , times_row) in enumerate(zip(sizes, times)):
features[i] = _features.extract_features(
timestamps=times_row, sizes=size_row)
return times, sizes, features
@pytest.mark.parametrize('n_features', [100, 300])
def test_extract_features_sequence(dataset_seq, n_features):
| 64 | 64 | 125 | 24 | 39 | jpcsmith/wf-tools | tests/classifiers/kfingerprinting/test_features.py | Python | test_extract_features_sequence | test_extract_features_sequence | 214 | 227 | 214 | 215 | 3a01e5df517229134a56f02c8884c322bd225c7d | bigcode/the-stack | train |
2fa60c00e5d28787e4af2b64 | train | function | def test_head_tail_concentration(trace, sample_trace: Trace):
"""The concentration of first and last 30 packets should match the
reference implementation.
"""
ref_result = rf_fextract.first_and_last_30_pkts_stats(
as_lines(sample_trace))
result = _features.head_and_tail_concentration(trace, ... | def test_head_tail_concentration(trace, sample_trace: Trace):
| """The concentration of first and last 30 packets should match the
reference implementation.
"""
ref_result = rf_fextract.first_and_last_30_pkts_stats(
as_lines(sample_trace))
result = _features.head_and_tail_concentration(trace, 30)
assert ref_result == list(result.values())
| _counts(trace, sample_trace: Trace):
"""The packet counts should match the reference."""
ref_result = rf_fextract.number_pkt_stats(as_lines(sample_trace))
result = _features.packet_counts(trace)
assert ref_result == tuple(result.values())
def test_head_tail_concentration(trace, sample_trace: Trace):
| 64 | 64 | 80 | 13 | 51 | jpcsmith/wf-tools | tests/classifiers/kfingerprinting/test_features.py | Python | test_head_tail_concentration | test_head_tail_concentration | 95 | 103 | 95 | 95 | d13cccaeeaa08e46a95530ed2fa84c355d10d4a7 | bigcode/the-stack | train |
187b1444bf66f12941b775db | train | function | @pytest.mark.parametrize('n_jobs', [2, None])
def test_extract_features_sequence_mp_jobs(dataset_seq, n_jobs):
"""It should correct extract features that are provided as a sequence.
"""
times, sizes = dataset_seq
features = _features.extract_features_sequence(
timestamps=times, sizes=sizes, n_jo... | @pytest.mark.parametrize('n_jobs', [2, None])
def test_extract_features_sequence_mp_jobs(dataset_seq, n_jobs):
| """It should correct extract features that are provided as a sequence.
"""
times, sizes = dataset_seq
features = _features.extract_features_sequence(
timestamps=times, sizes=sizes, n_jobs=n_jobs)
expected_features = np.asarray([
_features.extract_features(sizes=size_row, timestamps=... | =size_row, timestamps=time_row, max_size=n_features)
for size_row, time_row in zip(sizes, times)
])
np.testing.assert_allclose(expected_features, features)
@pytest.mark.parametrize('n_jobs', [2, None])
def test_extract_features_sequence_mp_jobs(dataset_seq, n_jobs):
| 64 | 64 | 120 | 25 | 39 | jpcsmith/wf-tools | tests/classifiers/kfingerprinting/test_features.py | Python | test_extract_features_sequence_mp_jobs | test_extract_features_sequence_mp_jobs | 246 | 258 | 246 | 247 | 4c34e17f8d822046f00d378d2ffd6bd93c0ebfb2 | bigcode/the-stack | train |
d1b975ffe2626066db7c29bd | train | function | def check_function_argument_count(func, input_arity, infeed_queue):
"""Validate the number of input arguments to a tpu function.
Args:
func: the Python function that will be called to generate the body
of a TPUFunction.
input_arity: the number of explicit arguments supplied by the
caller.
i... | def check_function_argument_count(func, input_arity, infeed_queue):
| """Validate the number of input arguments to a tpu function.
Args:
func: the Python function that will be called to generate the body
of a TPUFunction.
input_arity: the number of explicit arguments supplied by the
caller.
infeed_queue: if not None, the infeed queue that will supply
ad... | being built.
_current_tpu_context = TpuContext()
@contextlib.contextmanager
def tpu_shard_context(number_of_shards):
if _current_tpu_context.number_of_shards is not None:
raise NotImplementedError("tpu_shard_context cannot be nested.")
try:
_current_tpu_context.set_number_of_shards(number_of_shards)
... | 126 | 126 | 422 | 15 | 110 | tianyapiaozi/tensorflow | tensorflow/contrib/tpu/python/tpu/tpu_function.py | Python | check_function_argument_count | check_function_argument_count | 62 | 105 | 62 | 62 | b957ba05092033e1d229c9fca7b4d731fe4e3089 | bigcode/the-stack | train |
9a344a8839ff4a79152126e3 | train | class | class TpuContext(object):
"""A context object holding state about the TPU computation being built."""
def __init__(self):
"""Creates a new TpuContext."""
self._number_of_shards = None
@property
def number_of_shards(self):
return self._number_of_shards
def set_number_of_shards(self, number_of_sh... | class TpuContext(object):
| """A context object holding state about the TPU computation being built."""
def __init__(self):
"""Creates a new TpuContext."""
self._number_of_shards = None
@property
def number_of_shards(self):
return self._number_of_shards
def set_number_of_shards(self, number_of_shards):
self._number_of... | permissions and
# limitations under the License.
# =============================================================================
"""Helper library for functions used during TPU compilation."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import context... | 64 | 64 | 94 | 6 | 57 | tianyapiaozi/tensorflow | tensorflow/contrib/tpu/python/tpu/tpu_function.py | Python | TpuContext | TpuContext | 27 | 39 | 27 | 27 | 8eeb5a2d7add29365050e75ba9a458e190683497 | bigcode/the-stack | train |
6fef4f4dcc91f6f5763ff86a | train | function | def get_tpu_context():
return _current_tpu_context
| def get_tpu_context():
| return _current_tpu_context
| ards is not None:
raise NotImplementedError("tpu_shard_context cannot be nested.")
try:
_current_tpu_context.set_number_of_shards(number_of_shards)
yield
finally:
_current_tpu_context.set_number_of_shards(None)
def get_tpu_context():
| 64 | 64 | 14 | 6 | 58 | tianyapiaozi/tensorflow | tensorflow/contrib/tpu/python/tpu/tpu_function.py | Python | get_tpu_context | get_tpu_context | 58 | 59 | 58 | 58 | e173736322e6f95596c58a20a9c16bc25bc8d857 | bigcode/the-stack | train |
933daaadf5bed5b55ff17358 | train | function | @contextlib.contextmanager
def tpu_shard_context(number_of_shards):
if _current_tpu_context.number_of_shards is not None:
raise NotImplementedError("tpu_shard_context cannot be nested.")
try:
_current_tpu_context.set_number_of_shards(number_of_shards)
yield
finally:
_current_tpu_context.set_number... | @contextlib.contextmanager
def tpu_shard_context(number_of_shards):
| if _current_tpu_context.number_of_shards is not None:
raise NotImplementedError("tpu_shard_context cannot be nested.")
try:
_current_tpu_context.set_number_of_shards(number_of_shards)
yield
finally:
_current_tpu_context.set_number_of_shards(None)
| _shards = number_of_shards
# The Tpu context holds the number of shards when a sharded computation is
# being built, or None if no computation is being built.
_current_tpu_context = TpuContext()
@contextlib.contextmanager
def tpu_shard_context(number_of_shards):
| 64 | 64 | 85 | 17 | 47 | tianyapiaozi/tensorflow | tensorflow/contrib/tpu/python/tpu/tpu_function.py | Python | tpu_shard_context | tpu_shard_context | 47 | 55 | 47 | 48 | 9f0dca3fd3a3d6c3abc9b42058f478c2da3cc182 | bigcode/the-stack | train |
ef7cacb4ddd55b2562191574 | train | function | def response_with(response, value=None, message=None, error=None, headers={}, pagination=None):
result = {}
if value is not None:
result.update(value)
if response.get('message', None) is not None:
result.update({'message': response['message']})
result.update({'code': response['... | def response_with(response, value=None, message=None, error=None, headers={}, pagination=None):
| result = {}
if value is not None:
result.update(value)
if response.get('message', None) is not None:
result.update({'message': response['message']})
result.update({'code': response['code']})
if error is not None:
result.update({'errors': error})
if paginat... | from flask import make_response, jsonify
def response_with(response, value=None, message=None, error=None, headers={}, pagination=None):
| 27 | 64 | 143 | 19 | 7 | adevecchi/flask-rest-api-jwt | api/utils/responses.py | Python | response_with | response_with | 3 | 22 | 3 | 3 | b33555b89d87486d66fd92e303764925a45d5478 | bigcode/the-stack | train |
5ea0c8b25012a8bc7508e8d9 | train | class | class BgcolorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self,
plotly_name='bgcolor',
parent_name='scatter3d.marker.colorbar',
**kwargs
):
super(BgcolorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=paren... | class BgcolorValidator(_plotly_utils.basevalidators.ColorValidator):
| def __init__(
self,
plotly_name='bgcolor',
parent_name='scatter3d.marker.colorbar',
**kwargs
):
super(BgcolorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop('edit_type', 'calc'),
... | import _plotly_utils.basevalidators
class BgcolorValidator(_plotly_utils.basevalidators.ColorValidator):
| 21 | 64 | 103 | 13 | 7 | gnestor/plotly.py | plotly/validators/scatter3d/marker/colorbar/_bgcolor.py | Python | BgcolorValidator | BgcolorValidator | 4 | 18 | 4 | 5 | cb3a7dfeadc37a19e5947b1e078dcf5eb9dbbca0 | bigcode/the-stack | train |
1326683a8e3ac9c84b6bdf67 | train | class | class TestDrive(GraphTestCase):
"""OneDrive specific test case base class"""
def test1_get_drives(self):
drives = self.client.drives.top(2).get().execute_query()
self.assertLessEqual(len(drives), 2)
for drive in drives:
self.assertIsNotNone(drive.web_url)
def test2_get_... | class TestDrive(GraphTestCase):
| """OneDrive specific test case base class"""
def test1_get_drives(self):
drives = self.client.drives.top(2).get().execute_query()
self.assertLessEqual(len(drives), 2)
for drive in drives:
self.assertIsNotNone(drive.web_url)
def test2_get_drives_alt(self):
resp =... | from tests.graph_case import GraphTestCase
class TestDrive(GraphTestCase):
| 16 | 72 | 242 | 7 | 8 | wreiner/Office365-REST-Python-Client | tests/onedrive/test_drive.py | Python | TestDrive | TestDrive | 4 | 30 | 4 | 4 | a79326a22bed8f39f2429c7772bb20d344d00f90 | bigcode/the-stack | train |
a3b6dc53dcfe0498634e6a0b | train | class | class FilamentConan(ConanFile):
name = "filament"
version = "1.9.21"
license = "Apache License 2.0"
homepage = "https://github.com/google/filament"
url = "https://github.com/luizgabriel/conan-filament"
description = "Filament is a real-time physically based rendering engine for Android, iOS, Win... | class FilamentConan(ConanFile):
| name = "filament"
version = "1.9.21"
license = "Apache License 2.0"
homepage = "https://github.com/google/filament"
url = "https://github.com/luizgabriel/conan-filament"
description = "Filament is a real-time physically based rendering engine for Android, iOS, Windows, Linux, " \
... | from conans import ConanFile, CMake, tools
class FilamentConan(ConanFile):
| 22 | 225 | 753 | 10 | 11 | luizgabriel/Spatial.Engine | vendor/filament.py | Python | FilamentConan | FilamentConan | 4 | 76 | 4 | 4 | 3c5769ac3d6e6faaaca4c3c2964155774163d21b | bigcode/the-stack | train |
134558152f05e00d16d328ea | train | class | class Migration(BaseMigration):
def migrate(self):
self.db.delete_column("sa_activator", "ip")
self.db.delete_column("sa_activator", "to_ip")
self.db.execute("ALTER TABLE sa_activator ALTER prefix_table_id SET NOT NULL")
| class Migration(BaseMigration):
| def migrate(self):
self.db.delete_column("sa_activator", "ip")
self.db.delete_column("sa_activator", "to_ip")
self.db.execute("ALTER TABLE sa_activator ALTER prefix_table_id SET NOT NULL")
| # ----------------------------------------------------------------------
# activator drop ip
# ----------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# NOC module... | 57 | 64 | 58 | 5 | 51 | prorevizor/noc | sa/migrations/0068_activator_drop_ip.py | Python | Migration | Migration | 12 | 16 | 12 | 12 | b7e1dab4c224b3545e48d0f3b7f2d8387e254292 | bigcode/the-stack | train |
02c5eb33cde1da9da56f0522 | train | class | class ScalarFunctionWithInferredInverse(bijector.Bijector):
"""Bijector to associate a numeric inverse with any invertible function."""
def __init__(self,
fn,
domain_constraint_fn=None,
root_search_fn=tfp_math.secant_root,
max_iterations=50,
... | class ScalarFunctionWithInferredInverse(bijector.Bijector):
| """Bijector to associate a numeric inverse with any invertible function."""
def __init__(self,
fn,
domain_constraint_fn=None,
root_search_fn=tfp_math.secant_root,
max_iterations=50,
require_convergence=True,
validate_args=Fal... | # Copyright 2020 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | 223 | 256 | 1,063 | 14 | 209 | mattwescott/probability | tensorflow_probability/python/experimental/bijectors/scalar_function_with_inferred_inverse.py | Python | ScalarFunctionWithInferredInverse | ScalarFunctionWithInferredInverse | 27 | 144 | 27 | 27 | 4ae674143038aa5252da766b6192c804e5e7ad83 | bigcode/the-stack | train |
93a9e43ba9e6ec6165e17f08 | train | function | @pytest.fixture
def create_client(host, email, dev_key):
def _create_client():
return Client(host, email=email, dev_key=dev_key, debug=True)
return _create_client
| @pytest.fixture
def create_client(host, email, dev_key):
| def _create_client():
return Client(host, email=email, dev_key=dev_key, debug=True)
return _create_client
| def create_organization(client, created_entities):
def _create_organization(name=None):
org = client._create_organization(name or _utils.generate_default_name())
created_entities.append(org)
return org
return _create_organization
@pytest.fixture
def create_client(host, email, dev_key):... | 64 | 64 | 42 | 13 | 50 | stefan-petrov-toptal/modeldb | client/verta/tests/test_permissions/conftest.py | Python | create_client | create_client | 18 | 23 | 18 | 19 | 7a738954cdc052498b65c29cfac9f117545534fd | bigcode/the-stack | train |
7840b96de98ceba409ab0c7d | train | function | @pytest.fixture
def create_organization(client, created_entities):
def _create_organization(name=None):
org = client._create_organization(name or _utils.generate_default_name())
created_entities.append(org)
return org
return _create_organization
| @pytest.fixture
def create_organization(client, created_entities):
| def _create_organization(name=None):
org = client._create_organization(name or _utils.generate_default_name())
created_entities.append(org)
return org
return _create_organization
| import pytest
from verta import Client
from verta._internal_utils import _utils
@pytest.fixture
def create_organization(client, created_entities):
| 29 | 64 | 54 | 12 | 16 | stefan-petrov-toptal/modeldb | client/verta/tests/test_permissions/conftest.py | Python | create_organization | create_organization | 7 | 15 | 7 | 8 | 6f97859fe5192bf10f035a44a623bd94d477eb80 | bigcode/the-stack | train |
485cf73d3c4be3dbb879f926 | train | function | def fn_args(fn):
"""Get argument names for function-like object.
Args:
fn: Function, or function-like object (e.g., result of `functools.partial`).
Returns:
`tuple` of string argument names.
Raises:
ValueError: if partial function has positionally bound arguments
"""
_, fn = tf_decorator.unwr... | def fn_args(fn):
| """Get argument names for function-like object.
Args:
fn: Function, or function-like object (e.g., result of `functools.partial`).
Returns:
`tuple` of string argument names.
Raises:
ValueError: if partial function has positionally bound arguments
"""
_, fn = tf_decorator.unwrap(fn)
# Handl... | governing permissions and
# limitations under the License.
# ==============================================================================
"""Utility to retrieve function args.."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.ut... | 68 | 68 | 228 | 5 | 62 | DEVESHTARASIA/tensorflow | tensorflow/python/estimator/util.py | Python | fn_args | fn_args | 26 | 57 | 26 | 26 | 79ed0a0bf23e93a0686896efe6dfebc1643452d8 | bigcode/the-stack | train |
b7788cf45841c61e8abd56d3 | train | class | class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Question',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
... | class Migration(migrations.Migration):
| initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Question',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('question_text', models.CharField(max_l... | # Generated by Django 2.2.3 on 2019-07-07 21:33
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 45 | 64 | 179 | 7 | 37 | jingluomaf/django-mysite | mysite/polls/migrations/0001_initial.py | Python | Migration | Migration | 7 | 32 | 7 | 8 | 87380473378d01d160db436b9c8f6eedb18b2673 | bigcode/the-stack | train |
7466bb9d1666ce168a93b1e4 | train | function | def _determine_display(display_value):
if isinstance(display_value, six.string_types):
return "typeahead"
return "select" if len(display_value) <= 50 else "typeahead"
| def _determine_display(display_value):
| if isinstance(display_value, six.string_types):
return "typeahead"
return "select" if len(display_value) <= 50 else "typeahead"
| _string, parsers[parse_as])
else:
for parser in parsers.values():
try:
return _parse(input_string, parser)
except ParseError:
continue
raise ParseError('Unable to successfully parse input "%s"' % input_string)
def _determine_display(display_value)... | 64 | 64 | 42 | 8 | 56 | scott-taubman/brewtils | brewtils/choices.py | Python | _determine_display | _determine_display | 103 | 107 | 103 | 103 | f1ed5db09c85ef1d8d174767b95d16a78100ac48 | bigcode/the-stack | train |
29d8b68966b5eaa984cfe550 | train | function | def parse(input_string, parse_as=None):
"""Attempt to parse a string into a choices dictionary.
Args:
input_string: The string to parse
parse_as: String specifying how to parse `input_string`. Valid values are
'func' or 'url'. Will try all valid values if None.
Returns:
... | def parse(input_string, parse_as=None):
| """Attempt to parse a string into a choices dictionary.
Args:
input_string: The string to parse
parse_as: String specifying how to parse `input_string`. Valid values are
'func' or 'url'. Will try all valid values if None.
Returns:
Dictionary containing the parse results... | 1 else []}
@staticmethod
def reference(s):
return str(s[0])
@staticmethod
def arg_pair(s):
return str(s[0]), str(s[1])
func_args = list
url_args = list
def parse(input_string, parse_as=None):
| 64 | 64 | 216 | 9 | 54 | scott-taubman/brewtils | brewtils/choices.py | Python | parse | parse | 70 | 100 | 70 | 70 | 9ae5b2b77e8993d928a1ee2fc80db502b4cec481 | bigcode/the-stack | train |
c78bfbebc10446e2fd8f5ba0 | train | class | class FunctionTransformer(Transformer):
@staticmethod
def func(s):
return {"name": str(s[0]), "args": s[1] if len(s) > 1 else []}
@staticmethod
def url(s):
return {"address": str(s[0]), "args": s[1] if len(s) > 1 else []}
@staticmethod
def reference(s):
return str(s[0])... | class FunctionTransformer(Transformer):
@staticmethod
| def func(s):
return {"name": str(s[0]), "args": s[1] if len(s) > 1 else []}
@staticmethod
def url(s):
return {"address": str(s[0]), "args": s[1] if len(s) > 1 else []}
@staticmethod
def reference(s):
return str(s[0])
@staticmethod
def arg_pair(s):
return st... | ignore WS
"""
parsers = {
"func": Lark(choices_grammar, start="func"),
"url": Lark(choices_grammar, start="url"),
"reference": Lark(choices_grammar, start="reference"),
}
class FunctionTransformer(Transformer):
@staticmethod
| 64 | 64 | 128 | 10 | 54 | scott-taubman/brewtils | brewtils/choices.py | Python | FunctionTransformer | FunctionTransformer | 49 | 67 | 49 | 50 | 287b7c5f75075cdf0c8e45c1a03c9573a122eb4c | bigcode/the-stack | train |
567b0718ad6dbecda3f14b9a | train | function | def _determine_type(type_value):
if isinstance(type_value, six.string_types):
return "url" if type_value.startswith("http") else "command"
return "static"
| def _determine_type(type_value):
| if isinstance(type_value, six.string_types):
return "url" if type_value.startswith("http") else "command"
return "static"
| Error('Unable to successfully parse input "%s"' % input_string)
def _determine_display(display_value):
if isinstance(display_value, six.string_types):
return "typeahead"
return "select" if len(display_value) <= 50 else "typeahead"
def _determine_type(type_value):
| 64 | 64 | 39 | 8 | 56 | scott-taubman/brewtils | brewtils/choices.py | Python | _determine_type | _determine_type | 110 | 114 | 110 | 110 | 6201c4846400ec662368a73f411b9945f4955842 | bigcode/the-stack | train |
14534bb74b46710e52699ce2 | train | function | def process_choices(choices):
# type: (Union[dict, str, Iterable, Callable]) -> Optional[Choices]
"""Process a choices definition into a usable Choices object
Args:
choices: Raw choices definition, usually from a decorator
Returns:
Choices: Dictionary that fully describes a choices spe... | def process_choices(choices):
# type: (Union[dict, str, Iterable, Callable]) -> Optional[Choices]
| """Process a choices definition into a usable Choices object
Args:
choices: Raw choices definition, usually from a decorator
Returns:
Choices: Dictionary that fully describes a choices specification
"""
if choices is None or isinstance(choices, Choices):
return choices
... | the parse results
Raises:
lark.common.ParseError: Unable to find a valid parsing of `input_string`
"""
def _parse(_input_string, _parser):
try:
return FunctionTransformer().transform(_parser.parse(_input_string))
except (GrammarError, LexError, ParseError) as e:
... | 251 | 251 | 837 | 26 | 225 | scott-taubman/brewtils | brewtils/choices.py | Python | process_choices | process_choices | 117 | 236 | 117 | 118 | f07e2db03445968f4f3e4f4487570dc2853960c2 | bigcode/the-stack | train |
1972a2af6d19a1f78d585446 | train | class | class ReportTest(unittest.TestCase):
"""Test Report class."""
def testAddData(self):
"""test AddData."""
test_report = report.Report("create")
test_report.AddData("devices", {"instance_name": "instance_1"})
test_report.AddData("devices", {"instance_name": "instance_2"})
... | class ReportTest(unittest.TestCase):
| """Test Report class."""
def testAddData(self):
"""test AddData."""
test_report = report.Report("create")
test_report.AddData("devices", {"instance_name": "instance_1"})
test_report.AddData("devices", {"instance_name": "instance_2"})
expected = {
"devices": [... | #!/usr/bin/env python
#
# Copyright 2016 - The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | 164 | 256 | 863 | 7 | 156 | CarbonROM/android_tools_acloud | public/report_test.py | Python | ReportTest | ReportTest | 23 | 127 | 23 | 23 | 4f36d2b2e2c1223934d73305bd9a9b6485216aa8 | bigcode/the-stack | train |
f27bf7e1835283c3c67590e1 | train | class | class NoExtraArg:
pass
| class NoExtraArg:
| pass
| :
tok = plexer.token()
if not tok: break
print(tok.lineno, [tok.type, tok.value], tok.lexpos)
#"""
from js_ast import *
from js_parse import parser
plexer.lineno = 0
from js_typespace import *
class NoExtraArg:
| 64 | 64 | 8 | 5 | 59 | joeedh/webblender | tools/extjs_cc/javascript_type_checker.py | Python | NoExtraArg | NoExtraArg | 106 | 107 | 106 | 106 | 1f1fe32a739efcace1be8526f944a66b3e419d82 | bigcode/the-stack | train |
267f39cc3d379d8a0bc40e48 | train | function | def parse():
result = parser.parse(data, lexer=plexer)
#print(result)
print("\n")
def traverse(node, ntype, func, extra_arg=NoExtraArg, depth=0):
for c in node.children:
traverse(c, ntype, func, extra_arg, depth+1)
if type(node) == ntype:
if extra_arg == NoExtraArg:
func... | def parse():
| result = parser.parse(data, lexer=plexer)
#print(result)
print("\n")
def traverse(node, ntype, func, extra_arg=NoExtraArg, depth=0):
for c in node.children:
traverse(c, ntype, func, extra_arg, depth+1)
if type(node) == ntype:
if extra_arg == NoExtraArg:
func(node, depth)... | (this, "faces", {get: function() {
return new MeshIterate(MeshIter.VERT_FACES, this);
}});
}
"""
data = \
"""
//#$().class
function Test() {
this.a = 0;
//#$().undefined
this.func = function() {
var d = this.a;
d += 1;
}
}
//#$().undefined
Test.prototype.b = function() {
this.c = 0;
}
"""
... | 256 | 256 | 1,183 | 3 | 252 | joeedh/webblender | tools/extjs_cc/javascript_type_checker.py | Python | parse | parse | 109 | 241 | 109 | 109 | ee0d6e7c391772d8e85e4079721cf7fd436b1cb0 | bigcode/the-stack | train |
a0e18797c6444c30ac9b08f1 | train | class | class AuthMethod:
v = {'rsa-sig': 1,
'shared-key': 2}
@staticmethod
def value(key): return AuthMethod.v[key]
| class AuthMethod:
| v = {'rsa-sig': 1,
'shared-key': 2}
@staticmethod
def value(key): return AuthMethod.v[key]
| from ipaddress import IPv4Address, AddressValueError
from vpp_object import VppObject
from vpp_papi import VppEnum
class AuthMethod:
| 35 | 64 | 38 | 4 | 30 | yasics/vpp | test/vpp_ikev2.py | Python | AuthMethod | AuthMethod | 6 | 11 | 6 | 6 | a532a6a277b26ebd81a2ba529c5769f778fa5c11 | bigcode/the-stack | train |
0b8f91971c7c506ad37bb40c | train | class | class Profile(VppObject):
""" IKEv2 profile """
def __init__(self, test, profile_name):
self.test = test
self.vapi = test.vapi
self.profile_name = profile_name
self.udp_encap = False
self.natt = True
def disable_natt(self):
self.natt = False
def add_auth... | class Profile(VppObject):
| """ IKEv2 profile """
def __init__(self, test, profile_name):
self.test = test
self.vapi = test.vapi
self.profile_name = profile_name
self.udp_encap = False
self.natt = True
def disable_natt(self):
self.natt = False
def add_auth(self, method, data, is_he... | from ipaddress import IPv4Address, AddressValueError
from vpp_object import VppObject
from vpp_papi import VppEnum
class AuthMethod:
v = {'rsa-sig': 1,
'shared-key': 2}
@staticmethod
def value(key): return AuthMethod.v[key]
class IDType:
v = {'ip4-addr': 1,
'fqdn': 2,
'ip... | 124 | 256 | 1,260 | 6 | 118 | yasics/vpp | test/vpp_ikev2.py | Python | Profile | Profile | 23 | 179 | 23 | 23 | c3085909cbe261d60abf22d0e7b526d2a07e9135 | bigcode/the-stack | train |
27c743563e2492cb3ae8dc58 | train | class | class IDType:
v = {'ip4-addr': 1,
'fqdn': 2,
'ip6-addr': 5}
@staticmethod
def value(key): return IDType.v[key]
| class IDType:
| v = {'ip4-addr': 1,
'fqdn': 2,
'ip6-addr': 5}
@staticmethod
def value(key): return IDType.v[key]
| ValueError
from vpp_object import VppObject
from vpp_papi import VppEnum
class AuthMethod:
v = {'rsa-sig': 1,
'shared-key': 2}
@staticmethod
def value(key): return AuthMethod.v[key]
class IDType:
| 64 | 64 | 49 | 4 | 60 | yasics/vpp | test/vpp_ikev2.py | Python | IDType | IDType | 14 | 20 | 14 | 14 | 8ec19d586934d515231cfc3fb0f3ab7e94b76d40 | bigcode/the-stack | train |
2273691306d4c9b9b8a3da5c | train | class | class TestV1alpha1PriorityClass(unittest.TestCase):
""" V1alpha1PriorityClass unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testV1alpha1PriorityClass(self):
"""
Test V1alpha1PriorityClass
"""
# FIXME: construct object with manda... | class TestV1alpha1PriorityClass(unittest.TestCase):
| """ V1alpha1PriorityClass unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testV1alpha1PriorityClass(self):
"""
Test V1alpha1PriorityClass
"""
# FIXME: construct object with mandatory attributes with example values
#model =... | __future__ import absolute_import
import os
import sys
import unittest
import kubernetes.client
from kubernetes.client.rest import ApiException
from kubernetes.client.models.v1alpha1_priority_class import V1alpha1PriorityClass
class TestV1alpha1PriorityClass(unittest.TestCase):
| 64 | 64 | 105 | 12 | 51 | scele/kubernetes-client-python | kubernetes/test/test_v1alpha1_priority_class.py | Python | TestV1alpha1PriorityClass | TestV1alpha1PriorityClass | 25 | 40 | 25 | 25 | 860240176800a48a8055fcec89c36427aa038067 | bigcode/the-stack | train |
f9b6106eb7655d0b1fec9be9 | train | class | class Config():
def __init__(self):
self.squadLocation = "/content/bi-att-flow/data/squad"
self.gloveLocation = "/content/bi-att-flow/data/glove"
pass
| class Config():
| def __init__(self):
self.squadLocation = "/content/bi-att-flow/data/squad"
self.gloveLocation = "/content/bi-att-flow/data/glove"
pass
| class Config():
| 3 | 64 | 45 | 3 | 0 | JobQiu/bi-att-flow | config/configuration.py | Python | Config | Config | 1 | 6 | 1 | 1 | 2930e6a882c912e364dcf73ebabcf11f05ffafc5 | bigcode/the-stack | train |
16ea2c7021cb7579518921cd | train | class | class TensorboardLoggerHook(LoggerHook):
def __init__(self,
log_dir=None,
interval=10,
ignore_last=True,
reset_flag=True):
super(TensorboardLoggerHook, self).__init__(interval, ignore_last,
... | class TensorboardLoggerHook(LoggerHook):
| def __init__(self,
log_dir=None,
interval=10,
ignore_last=True,
reset_flag=True):
super(TensorboardLoggerHook, self).__init__(interval, ignore_last,
reset_flag)
self.log_dir = log_... | import os.path as osp
import torch
from mmcv.runner.dist_utils import master_only
from mmcv.runner.hooks.logger.base import LoggerHook
class TensorboardLoggerHook(LoggerHook):
| 39 | 119 | 399 | 8 | 30 | tuggeluk/mmdetection | debugging/tensorboard.py | Python | TensorboardLoggerHook | TensorboardLoggerHook | 9 | 62 | 9 | 10 | d2891a5dadaeb01a1731deadf3662da8057d3a99 | bigcode/the-stack | train |
0a5d4be1ebcb3583fba65c96 | train | function | def save_to_query(source_dir: str):
from shutil import copytree, rmtree
query_dir = '/'.join(source_dir.split('/')[:-2]) + '/query/'
if os.path.exists(query_dir):
rmtree(query_dir)
copytree(source_dir, query_dir)
| def save_to_query(source_dir: str):
| from shutil import copytree, rmtree
query_dir = '/'.join(source_dir.split('/')[:-2]) + '/query/'
if os.path.exists(query_dir):
rmtree(query_dir)
copytree(source_dir, query_dir)
| _from_img(self.outputDirs[i], self.personDirs[i], self.txtFiles[i])
images_dir_reduce(self.personDirs[i], self.selectPersonDirs[i])
save_to_query(self.selectPersonDirs[i])
self.finishedOneFileProcess.emit()
self.finished.emit()
def save_to_query(source_dir: str):
| 64 | 64 | 60 | 9 | 55 | CSD-AI/Integrated-detection-and-pedestrian-re-identification-system | ui_tools/fileProcessor.py | Python | save_to_query | save_to_query | 45 | 50 | 45 | 45 | b2b4e5f47fc0826296451509dfda91a002f4910d | bigcode/the-stack | train |
45e387af2793f4de47310789 | train | class | class FileProcessor(Thread, QObject):
finishedOneFileProcess = pyqtSignal()
finished = pyqtSignal()
def __init__(self, video_paths, output_dirs, person_dirs, txt_files, select_person_dirs):
Thread.__init__(self)
QObject.__init__(self)
self.videoPaths = video_paths
self.outpu... | class FileProcessor(Thread, QObject):
| finishedOneFileProcess = pyqtSignal()
finished = pyqtSignal()
def __init__(self, video_paths, output_dirs, person_dirs, txt_files, select_person_dirs):
Thread.__init__(self)
QObject.__init__(self)
self.videoPaths = video_paths
self.outputDirs = output_dirs
self.perso... | import os
from threading import Thread
from PyQt5.QtCore import pyqtSignal, QObject
from os.path import exists
from ui_tools.img_utils import video_to_img, get_person_from_img, images_dir_reduce
class FileProcessor(Thread, QObject):
| 53 | 70 | 234 | 7 | 45 | CSD-AI/Integrated-detection-and-pedestrian-re-identification-system | ui_tools/fileProcessor.py | Python | FileProcessor | FileProcessor | 9 | 42 | 9 | 9 | 7556d0153053b3d24b39061accbe77daa243afdb | bigcode/the-stack | train |
7ead5e4709e7d43b2205f9ac | train | class | class Dataloader():
def __init__(self, epochs, batch_size, cont, rt, ua, start_split, single_att, vocab=None, next_word=False, embed_prefix=None, max_length=-1):
self.nbatch_returns = 16
self.train_data_path = "train_contexts"
self.dev_data_path = "dev_contexts"
self.test_data_path =... | class Dataloader():
| def __init__(self, epochs, batch_size, cont, rt, ua, start_split, single_att, vocab=None, next_word=False, embed_prefix=None, max_length=-1):
self.nbatch_returns = 16
self.train_data_path = "train_contexts"
self.dev_data_path = "dev_contexts"
self.test_data_path = "test_contexts"
... |
import datetime, inspect, random, msgpack, os, sys, math, time, torch, pdb
import numpy as np
from pprint import pprint
from scipy.sparse.csgraph import floyd_warshall
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, pa... | 195 | 256 | 4,113 | 4 | 190 | cfwelch/longitudinal_dialog | model/dataloader.py | Python | Dataloader | Dataloader | 19 | 393 | 19 | 19 | 31bb8615234e321f6682af5e8211e2721b2eabee | bigcode/the-stack | train |
d738b1a774a9c964d2e84eab | train | function | def cprint(msg, error=False, important=False):
gprint(msg, "dataloader", error, important)
| def cprint(msg, error=False, important=False):
| gprint(msg, "dataloader", error, important)
| OK_OTHER, SPTOK_UNK, SPTOK_EOS, tag_set, RA_IND, FAM_IND, SCC_IND, SG_IND, SCH_IND, WORK_IND, NPR_IND, uv_to_parts, uax_set, NUMBER_OF_PEOPLE
def cprint(msg, error=False, important=False):
| 64 | 64 | 24 | 11 | 52 | cfwelch/longitudinal_dialog | model/dataloader.py | Python | cprint | cprint | 14 | 15 | 14 | 14 | 4230fd02ca0c163481aae7ee6b2c966ab0ff6e33 | bigcode/the-stack | train |
b06e2673d5138b8f447020a3 | train | class | class GetAlertsOutput(insightconnect_plugin_runtime.Output):
schema = json.loads("""
{
"type": "object",
"title": "Variables",
"properties": {
"alert_ids": {
"type": "array",
"title": "Alert IDs",
"description": "List of alert IDs",
"items": {
"type": "string"
},
... | class GetAlertsOutput(insightconnect_plugin_runtime.Output):
| schema = json.loads("""
{
"type": "object",
"title": "Variables",
"properties": {
"alert_ids": {
"type": "array",
"title": "Alert IDs",
"description": "List of alert IDs",
"items": {
"type": "string"
},
"order": 1
}
},
"required": [
"alert_ids"
... | RA, Other",
"items": {
"type": "string"
},
"order": 3
}
}
}
""")
def __init__(self):
super(self.__class__, self).__init__(self.schema)
class GetAlertsOutput(insightconnect_plugin_runtime.Output):
| 64 | 64 | 130 | 11 | 53 | lukaszlaszuk/insightconnect-plugins | plugins/rapid7_intsights/icon_rapid7_intsights/actions/get_alerts/schema.py | Python | GetAlertsOutput | GetAlertsOutput | 162 | 185 | 162 | 162 | 0ae46ca6685d6d4c7c8c69729ad44e5fe66a145d | bigcode/the-stack | train |
2ce37b839ce0c71ff07334ee | train | class | class Component:
DESCRIPTION = "Search alerts based on criteria"
| class Component:
| DESCRIPTION = "Search alerts based on criteria"
| # GENERATED BY KOMAND SDK - DO NOT EDIT
import insightconnect_plugin_runtime
import json
class Component:
| 23 | 64 | 13 | 3 | 19 | lukaszlaszuk/insightconnect-plugins | plugins/rapid7_intsights/icon_rapid7_intsights/actions/get_alerts/schema.py | Python | Component | Component | 6 | 7 | 6 | 6 | b96672778cf652e3ad90c09b64ddac1c58bf2f38 | bigcode/the-stack | train |
1236a55a7e53bb5b46f19430 | train | class | class Output:
ALERT_IDS = "alert_ids"
| class Output:
| ALERT_IDS = "alert_ids"
| "matched_asset_value"
NETWORK_TYPE = "network_type"
REMEDIATION_STATUS = "remediation_status"
SEVERITY = "severity"
SOURCE_DATE_FROM = "source_date_from"
SOURCE_DATE_TO = "source_date_to"
SOURCE_TYPE = "source_type"
class Output:
| 63 | 64 | 11 | 3 | 60 | lukaszlaszuk/insightconnect-plugins | plugins/rapid7_intsights/icon_rapid7_intsights/actions/get_alerts/schema.py | Python | Output | Output | 27 | 28 | 27 | 27 | b1ebc8f506a0791d4557d95e9fc6b544e9054261 | bigcode/the-stack | train |
7ab334375be68c0fdd966df7 | train | class | class GetAlertsInput(insightconnect_plugin_runtime.Input):
schema = json.loads("""
{
"type": "object",
"title": "Variables",
"properties": {
"alert_type": {
"type": "array",
"title": "Alert Type",
"description": "List of alert types. Allowed values: AttackIndication, DataLeakage, Phis... | class GetAlertsInput(insightconnect_plugin_runtime.Input):
| schema = json.loads("""
{
"type": "object",
"title": "Variables",
"properties": {
"alert_type": {
"type": "array",
"title": "Alert Type",
"description": "List of alert types. Allowed values: AttackIndication, DataLeakage, Phishing, BrandSecurity, ExploitableData, vip",
"items": ... | # GENERATED BY KOMAND SDK - DO NOT EDIT
import insightconnect_plugin_runtime
import json
class Component:
DESCRIPTION = "Search alerts based on criteria"
class Input:
ALERT_TYPE = "alert_type"
ASSIGNED = "assigned"
FOUND_DATE_FROM = "found_date_from"
FOUND_DATE_TO = "found_date_to"
HAS_INDIC... | 191 | 256 | 1,019 | 11 | 180 | lukaszlaszuk/insightconnect-plugins | plugins/rapid7_intsights/icon_rapid7_intsights/actions/get_alerts/schema.py | Python | GetAlertsInput | GetAlertsInput | 31 | 159 | 31 | 31 | 452b6412dd576448e990de6c30449a9faaac662d | bigcode/the-stack | train |
8b6804bdb8e59c76db9ca5a0 | train | class | class Input:
ALERT_TYPE = "alert_type"
ASSIGNED = "assigned"
FOUND_DATE_FROM = "found_date_from"
FOUND_DATE_TO = "found_date_to"
HAS_INDICATORS = "has_indicators"
IS_CLOSED = "is_closed"
IS_FLAGGED = "is_flagged"
MATCHED_ASSET_VALUE = "matched_asset_value"
NETWORK_TYPE = "network_typ... | class Input:
| ALERT_TYPE = "alert_type"
ASSIGNED = "assigned"
FOUND_DATE_FROM = "found_date_from"
FOUND_DATE_TO = "found_date_to"
HAS_INDICATORS = "has_indicators"
IS_CLOSED = "is_closed"
IS_FLAGGED = "is_flagged"
MATCHED_ASSET_VALUE = "matched_asset_value"
NETWORK_TYPE = "network_type"
REMEDI... | # GENERATED BY KOMAND SDK - DO NOT EDIT
import insightconnect_plugin_runtime
import json
class Component:
DESCRIPTION = "Search alerts based on criteria"
class Input:
| 36 | 64 | 135 | 3 | 33 | lukaszlaszuk/insightconnect-plugins | plugins/rapid7_intsights/icon_rapid7_intsights/actions/get_alerts/schema.py | Python | Input | Input | 10 | 24 | 10 | 10 | bbedfcd9f384f9b578561333605f4bc78eb6e768 | bigcode/the-stack | train |
6e4a2383f3c9b47137677656 | train | function | def test_should_save_tensor_behavior_without_prepare_collections(out_dir):
"""Always return false if an attempt to save a tensor is made before the collections are prepared.
This can happen if the fn is called before callbacks are init."""
hook = smd.KerasHook(out_dir, save_config=SaveConfig(save_interval=3... | def test_should_save_tensor_behavior_without_prepare_collections(out_dir):
| """Always return false if an attempt to save a tensor is made before the collections are prepared.
This can happen if the fn is called before callbacks are init."""
hook = smd.KerasHook(out_dir, save_config=SaveConfig(save_interval=3), save_all=True)
assert not hook.should_save_tensor_or_collection("dum... | _or_collection(layer_name, CollectionKeys.LAYERS)
else:
assert not hook.should_save_tensor_or_collection(layer_name, CollectionKeys.GRADIENTS)
assert not hook.should_save_tensor_or_collection(layer_name, CollectionKeys.LAYERS)
def test_should_save_tensor_behavior_without_prepare_collecti... | 64 | 64 | 109 | 13 | 51 | jsspric/sagemaker-debugger | tests/tensorflow2/test_should_save_tensor.py | Python | test_should_save_tensor_behavior_without_prepare_collections | test_should_save_tensor_behavior_without_prepare_collections | 66 | 71 | 66 | 66 | 31300a6ea919b4ae0f77f38562c25ef25024ed90 | bigcode/the-stack | train |
7e18bf1598280da90a488aee | train | function | def helper_create_hook(out_dir, collections, include_regex=None):
hook = smd.KerasHook(
out_dir, save_config=SaveConfig(save_interval=3), include_collections=collections
)
if include_regex:
for collection in collections:
hook.get_collection(collection).include(include_regex)
... | def helper_create_hook(out_dir, collections, include_regex=None):
| hook = smd.KerasHook(
out_dir, save_config=SaveConfig(save_interval=3), include_collections=collections
)
if include_regex:
for collection in collections:
hook.get_collection(collection).include(include_regex)
hook.register_model(model)
hook.set_mode(ModeKeys.TRAIN)
... | .keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation="relu"),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation="softmax"),
]
)
def helper_create_hook(out_dir, collections, include_regex=None):
| 64 | 64 | 107 | 13 | 51 | jsspric/sagemaker-debugger | tests/tensorflow2/test_should_save_tensor.py | Python | helper_create_hook | helper_create_hook | 21 | 35 | 21 | 21 | cfbe1b43a95bdc22498d03464c79a7e3362e868e | bigcode/the-stack | train |
8104cc4084e997172189f8eb | train | function | def test_should_save_tensor_with_custom_collection(out_dir):
hook = helper_create_hook(out_dir, ["custom_coll"], include_regex="dense")
for layer in model.layers:
layer_name = layer.name
if "dense" in layer_name:
assert hook.should_save_tensor_or_collection(layer_name, CollectionKeys... | def test_should_save_tensor_with_custom_collection(out_dir):
| hook = helper_create_hook(out_dir, ["custom_coll"], include_regex="dense")
for layer in model.layers:
layer_name = layer.name
if "dense" in layer_name:
assert hook.should_save_tensor_or_collection(layer_name, CollectionKeys.GRADIENTS)
assert hook.should_save_tensor_or_col... | .LAYERS])
for layer in model.layers:
layer_name = layer.name
assert hook.should_save_tensor_or_collection(layer_name, CollectionKeys.GRADIENTS)
assert hook.should_save_tensor_or_collection(layer_name, CollectionKeys.LAYERS)
def test_should_save_tensor_with_custom_collection(out_dir):
| 64 | 64 | 127 | 11 | 53 | jsspric/sagemaker-debugger | tests/tensorflow2/test_should_save_tensor.py | Python | test_should_save_tensor_with_custom_collection | test_should_save_tensor_with_custom_collection | 54 | 63 | 54 | 54 | f4a5cda5b235c3a2e727e51830d0cba074f165ca | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.