blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4a3d25c7358022048e0f534ec908b5337c91dbe5 | [
"self.config: Dict[str, str] = {}\nself.config[AcnNodeConfig.KEY] = key\nself.config[AcnNodeConfig.URI] = uri\nself.config[AcnNodeConfig.EXTERNAL_URI] = external_uri if external_uri is not None else ''\nself.config[AcnNodeConfig.DELEGATE_URI] = delegate_uri if delegate_uri is not None else ''\nself.config[AcnNodeCo... | <|body_start_0|>
self.config: Dict[str, str] = {}
self.config[AcnNodeConfig.KEY] = key
self.config[AcnNodeConfig.URI] = uri
self.config[AcnNodeConfig.EXTERNAL_URI] = external_uri if external_uri is not None else ''
self.config[AcnNodeConfig.DELEGATE_URI] = delegate_uri if delegat... | Store the configuration of an acn node as a dictionary. | AcnNodeConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AcnNodeConfig:
"""Store the configuration of an acn node as a dictionary."""
def __init__(self, key: str, uri: str, external_uri: Optional[str]=None, delegate_uri: Optional[str]=None, monitoring_uri: Optional[str]=None, entry_peers_maddrs: Optional[List[str]]=None, log_file: Optional[str]=No... | stack_v2_sparse_classes_10k_train_001700 | 12,337 | permissive | [
{
"docstring": "Initialize a new ACN configuration from arguments :param key: node private key to use as identity :param uri: node local uri to bind to :param external_uri: node external uri, needed to be reached by others :param delegate_uri: node local uri for delegate service :param monitoring_uri: node moni... | 6 | null | Implement the Python class `AcnNodeConfig` described below.
Class description:
Store the configuration of an acn node as a dictionary.
Method signatures and docstrings:
- def __init__(self, key: str, uri: str, external_uri: Optional[str]=None, delegate_uri: Optional[str]=None, monitoring_uri: Optional[str]=None, entr... | Implement the Python class `AcnNodeConfig` described below.
Class description:
Store the configuration of an acn node as a dictionary.
Method signatures and docstrings:
- def __init__(self, key: str, uri: str, external_uri: Optional[str]=None, delegate_uri: Optional[str]=None, monitoring_uri: Optional[str]=None, entr... | bec49adaeba661d8d0f03ac9935dc89f39d95a0d | <|skeleton|>
class AcnNodeConfig:
"""Store the configuration of an acn node as a dictionary."""
def __init__(self, key: str, uri: str, external_uri: Optional[str]=None, delegate_uri: Optional[str]=None, monitoring_uri: Optional[str]=None, entry_peers_maddrs: Optional[List[str]]=None, log_file: Optional[str]=No... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AcnNodeConfig:
"""Store the configuration of an acn node as a dictionary."""
def __init__(self, key: str, uri: str, external_uri: Optional[str]=None, delegate_uri: Optional[str]=None, monitoring_uri: Optional[str]=None, entry_peers_maddrs: Optional[List[str]]=None, log_file: Optional[str]=None, enable_ch... | the_stack_v2_python_sparse | scripts/acn/run_acn_node_standalone.py | fetchai/agents-aea | train | 192 |
39ee2d764e15535a2c3d2686b8bf978760cb2943 | [
"from pages.regions.accordion import Accordion\nfrom pages.regions.treeaccordionitem import LegacyTreeAccordionItem\nreturn Accordion(self.testsetup, LegacyTreeAccordionItem)",
"self.accordion.current_content.find_node_by_name(service_name).click()\nself._wait_for_results_refresh()\nreturn self",
"if self.accor... | <|body_start_0|>
from pages.regions.accordion import Accordion
from pages.regions.treeaccordionitem import LegacyTreeAccordionItem
return Accordion(self.testsetup, LegacyTreeAccordionItem)
<|end_body_0|>
<|body_start_1|>
self.accordion.current_content.find_node_by_name(service_name).cli... | MyServices | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyServices:
def accordion(self):
"""accordion"""
<|body_0|>
def select_service_in_tree(self, service_name):
"""Select service"""
<|body_1|>
def is_service_present(self, service_name):
"""Select service"""
<|body_2|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_10k_train_001701 | 10,539 | no_license | [
{
"docstring": "accordion",
"name": "accordion",
"signature": "def accordion(self)"
},
{
"docstring": "Select service",
"name": "select_service_in_tree",
"signature": "def select_service_in_tree(self, service_name)"
},
{
"docstring": "Select service",
"name": "is_service_pres... | 3 | null | Implement the Python class `MyServices` described below.
Class description:
Implement the MyServices class.
Method signatures and docstrings:
- def accordion(self): accordion
- def select_service_in_tree(self, service_name): Select service
- def is_service_present(self, service_name): Select service | Implement the Python class `MyServices` described below.
Class description:
Implement the MyServices class.
Method signatures and docstrings:
- def accordion(self): accordion
- def select_service_in_tree(self, service_name): Select service
- def is_service_present(self, service_name): Select service
<|skeleton|>
cla... | 51bb86fda7d897e90444a6a0380a5aa2c61be6ff | <|skeleton|>
class MyServices:
def accordion(self):
"""accordion"""
<|body_0|>
def select_service_in_tree(self, service_name):
"""Select service"""
<|body_1|>
def is_service_present(self, service_name):
"""Select service"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MyServices:
def accordion(self):
"""accordion"""
from pages.regions.accordion import Accordion
from pages.regions.treeaccordionitem import LegacyTreeAccordionItem
return Accordion(self.testsetup, LegacyTreeAccordionItem)
def select_service_in_tree(self, service_name):
... | the_stack_v2_python_sparse | pages/services.py | sshveta/cfme_tests | train | 0 | |
051d98d928b1727f5ae46206de978dc480ffa208 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Proto file describing the Bidding Strategy service. Service to manage bidding strategies. | BiddingStrategyServiceServicer | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BiddingStrategyServiceServicer:
"""Proto file describing the Bidding Strategy service. Service to manage bidding strategies."""
def GetBiddingStrategy(self, request, context):
"""Returns the requested bidding strategy in full detail."""
<|body_0|>
def MutateBiddingStrate... | stack_v2_sparse_classes_10k_train_001702 | 3,550 | permissive | [
{
"docstring": "Returns the requested bidding strategy in full detail.",
"name": "GetBiddingStrategy",
"signature": "def GetBiddingStrategy(self, request, context)"
},
{
"docstring": "Creates, updates, or removes bidding strategies. Operation statuses are returned.",
"name": "MutateBiddingSt... | 2 | stack_v2_sparse_classes_30k_train_003819 | Implement the Python class `BiddingStrategyServiceServicer` described below.
Class description:
Proto file describing the Bidding Strategy service. Service to manage bidding strategies.
Method signatures and docstrings:
- def GetBiddingStrategy(self, request, context): Returns the requested bidding strategy in full d... | Implement the Python class `BiddingStrategyServiceServicer` described below.
Class description:
Proto file describing the Bidding Strategy service. Service to manage bidding strategies.
Method signatures and docstrings:
- def GetBiddingStrategy(self, request, context): Returns the requested bidding strategy in full d... | 0fc8a7dbf31d9e8e2a4364df93bec5f6b7edd50a | <|skeleton|>
class BiddingStrategyServiceServicer:
"""Proto file describing the Bidding Strategy service. Service to manage bidding strategies."""
def GetBiddingStrategy(self, request, context):
"""Returns the requested bidding strategy in full detail."""
<|body_0|>
def MutateBiddingStrate... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BiddingStrategyServiceServicer:
"""Proto file describing the Bidding Strategy service. Service to manage bidding strategies."""
def GetBiddingStrategy(self, request, context):
"""Returns the requested bidding strategy in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
... | the_stack_v2_python_sparse | google/ads/google_ads/v2/proto/services/bidding_strategy_service_pb2_grpc.py | juanmacugat/google-ads-python | train | 1 |
725f7a094142175602be5a6823557701de741c8e | [
"self.metric_name = metric['name'] or DATA_MODEL.metrics[metric['type']].name\nself.metric_unit = metric['unit'] or DATA_MODEL.metrics[metric['type']].unit.value\nself.subject_name = subject.get('name') or DATA_MODEL.subjects[subject['type']].name\nscale = metric['scale']\nself.new_metric_value = None\nself.old_met... | <|body_start_0|>
self.metric_name = metric['name'] or DATA_MODEL.metrics[metric['type']].name
self.metric_unit = metric['unit'] or DATA_MODEL.metrics[metric['type']].unit.value
self.subject_name = subject.get('name') or DATA_MODEL.subjects[subject['type']].name
scale = metric['scale']
... | Handle metric data needed for notifications. | MetricNotificationData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetricNotificationData:
"""Handle metric data needed for notifications."""
def __init__(self, metric: Metric, measurements: list[Measurement], subject: Subject) -> None:
"""Initialise the Notification with metric data."""
<|body_0|>
def __user_friendly_status(metric_stat... | stack_v2_sparse_classes_10k_train_001703 | 2,152 | permissive | [
{
"docstring": "Initialise the Notification with metric data.",
"name": "__init__",
"signature": "def __init__(self, metric: Metric, measurements: list[Measurement], subject: Subject) -> None"
},
{
"docstring": "Get the user friendly status name from the data model.",
"name": "__user_friendl... | 2 | stack_v2_sparse_classes_30k_train_005660 | Implement the Python class `MetricNotificationData` described below.
Class description:
Handle metric data needed for notifications.
Method signatures and docstrings:
- def __init__(self, metric: Metric, measurements: list[Measurement], subject: Subject) -> None: Initialise the Notification with metric data.
- def __... | Implement the Python class `MetricNotificationData` described below.
Class description:
Handle metric data needed for notifications.
Method signatures and docstrings:
- def __init__(self, metric: Metric, measurements: list[Measurement], subject: Subject) -> None: Initialise the Notification with metric data.
- def __... | 5d9952bf0bd47895824fa78428d3e4f4d6b5d9b3 | <|skeleton|>
class MetricNotificationData:
"""Handle metric data needed for notifications."""
def __init__(self, metric: Metric, measurements: list[Measurement], subject: Subject) -> None:
"""Initialise the Notification with metric data."""
<|body_0|>
def __user_friendly_status(metric_stat... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MetricNotificationData:
"""Handle metric data needed for notifications."""
def __init__(self, metric: Metric, measurements: list[Measurement], subject: Subject) -> None:
"""Initialise the Notification with metric data."""
self.metric_name = metric['name'] or DATA_MODEL.metrics[metric['typ... | the_stack_v2_python_sparse | components/notifier/src/models/metric_notification_data.py | ICTU/quality-time | train | 43 |
007e5f7d7e13511c443b5dae4709037f6a504a55 | [
"super().__init__(num_features, eps=eps)\nif not 0 < decay < 1:\n raise ValueError('decay must be between 0 and 1')\nself.decay = decay\nself.register_buffer('inv_learning_rate', th.empty(()))\nself.register_buffer('num_batches', th.empty((), dtype=th.int))\nEMANorm.reset_running_stats(self)",
"super().reset_r... | <|body_start_0|>
super().__init__(num_features, eps=eps)
if not 0 < decay < 1:
raise ValueError('decay must be between 0 and 1')
self.decay = decay
self.register_buffer('inv_learning_rate', th.empty(()))
self.register_buffer('num_batches', th.empty((), dtype=th.int))
... | Similar to RunningNorm but uses an exponential weighting. | EMANorm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EMANorm:
"""Similar to RunningNorm but uses an exponential weighting."""
def __init__(self, num_features: int, decay: float=0.99, eps: float=1e-05):
"""Builds EMARunningNorm. Args: num_features: Number of features; the length of the non-batch dim. decay: how quickly the weight on pas... | stack_v2_sparse_classes_10k_train_001704 | 14,535 | no_license | [
{
"docstring": "Builds EMARunningNorm. Args: num_features: Number of features; the length of the non-batch dim. decay: how quickly the weight on past samples decays over time. eps: small constant for numerical stability. Raises: ValueError: if decay is out of range.",
"name": "__init__",
"signature": "d... | 3 | stack_v2_sparse_classes_30k_train_000561 | Implement the Python class `EMANorm` described below.
Class description:
Similar to RunningNorm but uses an exponential weighting.
Method signatures and docstrings:
- def __init__(self, num_features: int, decay: float=0.99, eps: float=1e-05): Builds EMARunningNorm. Args: num_features: Number of features; the length o... | Implement the Python class `EMANorm` described below.
Class description:
Similar to RunningNorm but uses an exponential weighting.
Method signatures and docstrings:
- def __init__(self, num_features: int, decay: float=0.99, eps: float=1e-05): Builds EMARunningNorm. Args: num_features: Number of features; the length o... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class EMANorm:
"""Similar to RunningNorm but uses an exponential weighting."""
def __init__(self, num_features: int, decay: float=0.99, eps: float=1e-05):
"""Builds EMARunningNorm. Args: num_features: Number of features; the length of the non-batch dim. decay: how quickly the weight on pas... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EMANorm:
"""Similar to RunningNorm but uses an exponential weighting."""
def __init__(self, num_features: int, decay: float=0.99, eps: float=1e-05):
"""Builds EMARunningNorm. Args: num_features: Number of features; the length of the non-batch dim. decay: how quickly the weight on past samples dec... | the_stack_v2_python_sparse | generated/test_HumanCompatibleAI_imitation.py | jansel/pytorch-jit-paritybench | train | 35 |
f1120224241851c19baa225fddf63173832d53ab | [
"try:\n serializer = PatientHistorySerializers(PatientHistory.objects.all(), many=True)\n return JsonResponse({'message': 'listed all', 'data': serializer.data}, status=200)\nexcept Exception as e:\n info_message = 'Internal Server Error'\n logger.error(info_message, e)\n return JsonResponse({'error'... | <|body_start_0|>
try:
serializer = PatientHistorySerializers(PatientHistory.objects.all(), many=True)
return JsonResponse({'message': 'listed all', 'data': serializer.data}, status=200)
except Exception as e:
info_message = 'Internal Server Error'
logger.e... | PatientHistoryView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PatientHistoryView:
def get(self, request):
"""Get all patients"""
<|body_0|>
def post(self, request):
"""Save patient data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
serializer = PatientHistorySerializers(PatientHistory.object... | stack_v2_sparse_classes_10k_train_001705 | 12,219 | no_license | [
{
"docstring": "Get all patients",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Save patient data",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004528 | Implement the Python class `PatientHistoryView` described below.
Class description:
Implement the PatientHistoryView class.
Method signatures and docstrings:
- def get(self, request): Get all patients
- def post(self, request): Save patient data | Implement the Python class `PatientHistoryView` described below.
Class description:
Implement the PatientHistoryView class.
Method signatures and docstrings:
- def get(self, request): Get all patients
- def post(self, request): Save patient data
<|skeleton|>
class PatientHistoryView:
def get(self, request):
... | b63849983a592fd6a1f654191020fd86aa0787ae | <|skeleton|>
class PatientHistoryView:
def get(self, request):
"""Get all patients"""
<|body_0|>
def post(self, request):
"""Save patient data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PatientHistoryView:
def get(self, request):
"""Get all patients"""
try:
serializer = PatientHistorySerializers(PatientHistory.objects.all(), many=True)
return JsonResponse({'message': 'listed all', 'data': serializer.data}, status=200)
except Exception as e:
... | the_stack_v2_python_sparse | patient/views.py | RupeshKurlekar/biocare | train | 1 | |
8c524a0b4ab14b07d04730b1ee181af5c5ea6459 | [
"UserAuthnMethod.__init__(self, srv)\nself.totp = totp\nself.passwd = pwd\nself.mako_template = tmako\nself.template_lookup = template_lookup",
"resp = Response('OK')\nif UserManager.verify_match(username, password):\n '\\n Update the password\\n '\n try:\n usernm = UserManager.... | <|body_start_0|>
UserAuthnMethod.__init__(self, srv)
self.totp = totp
self.passwd = pwd
self.mako_template = tmako
self.template_lookup = template_lookup
<|end_body_0|>
<|body_start_1|>
resp = Response('OK')
if UserManager.verify_match(username, password):
... | Modifier_module | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Modifier_module:
def __init__(self, srv, tmako, template_lookup, totp, pwd):
""":param srv: The server instance :param tmako: Template mako :param template_lookup: template lookup :param totp: TOTP dictionary like database :param pwd: Username/password dictionary like database :return:""... | stack_v2_sparse_classes_10k_train_001706 | 2,911 | no_license | [
{
"docstring": ":param srv: The server instance :param tmako: Template mako :param template_lookup: template lookup :param totp: TOTP dictionary like database :param pwd: Username/password dictionary like database :return:",
"name": "__init__",
"signature": "def __init__(self, srv, tmako, template_looku... | 3 | stack_v2_sparse_classes_30k_train_006008 | Implement the Python class `Modifier_module` described below.
Class description:
Implement the Modifier_module class.
Method signatures and docstrings:
- def __init__(self, srv, tmako, template_lookup, totp, pwd): :param srv: The server instance :param tmako: Template mako :param template_lookup: template lookup :par... | Implement the Python class `Modifier_module` described below.
Class description:
Implement the Modifier_module class.
Method signatures and docstrings:
- def __init__(self, srv, tmako, template_lookup, totp, pwd): :param srv: The server instance :param tmako: Template mako :param template_lookup: template lookup :par... | 4455de4eb61fb4bddf6cfa8a4ce9e5f9f8e9d812 | <|skeleton|>
class Modifier_module:
def __init__(self, srv, tmako, template_lookup, totp, pwd):
""":param srv: The server instance :param tmako: Template mako :param template_lookup: template lookup :param totp: TOTP dictionary like database :param pwd: Username/password dictionary like database :return:""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Modifier_module:
def __init__(self, srv, tmako, template_lookup, totp, pwd):
""":param srv: The server instance :param tmako: Template mako :param template_lookup: template lookup :param totp: TOTP dictionary like database :param pwd: Username/password dictionary like database :return:"""
User... | the_stack_v2_python_sparse | server/modifydb.py | CarlosGonzalezLuzardo/SECAS | train | 0 | |
8e5749d582627e01df978ee621d036a5016a53ac | [
"self.Kp = P\nself.Ki = I\nself.Kd = D\nself.dt = dt\nself.heights = 0\nif simple:\n self.clear_simple()\nelse:\n self.clear()",
"self.integral = 0\nself.previous_error = 0\nself.window_up = 20",
"if self.Ki != 0:\n self.Ti = self.Kp / self.Ki\nelse:\n self.Ti = 10000000\nif self.Kd != 0:\n self.... | <|body_start_0|>
self.Kp = P
self.Ki = I
self.Kd = D
self.dt = dt
self.heights = 0
if simple:
self.clear_simple()
else:
self.clear()
<|end_body_0|>
<|body_start_1|>
self.integral = 0
self.previous_error = 0
self.win... | PID | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PID:
def __init__(self, P, I, D, dt, simple):
"""PID definitions Parameters ---------- P : Proportional gain I : Integral gain D : Derivative gain dt : Sample time"""
<|body_0|>
def clear_simple(self):
"""Variables initialization for update_simple() Parameters ------... | stack_v2_sparse_classes_10k_train_001707 | 3,290 | permissive | [
{
"docstring": "PID definitions Parameters ---------- P : Proportional gain I : Integral gain D : Derivative gain dt : Sample time",
"name": "__init__",
"signature": "def __init__(self, P, I, D, dt, simple)"
},
{
"docstring": "Variables initialization for update_simple() Parameters ---------- se... | 5 | stack_v2_sparse_classes_30k_train_005410 | Implement the Python class `PID` described below.
Class description:
Implement the PID class.
Method signatures and docstrings:
- def __init__(self, P, I, D, dt, simple): PID definitions Parameters ---------- P : Proportional gain I : Integral gain D : Derivative gain dt : Sample time
- def clear_simple(self): Variab... | Implement the Python class `PID` described below.
Class description:
Implement the PID class.
Method signatures and docstrings:
- def __init__(self, P, I, D, dt, simple): PID definitions Parameters ---------- P : Proportional gain I : Integral gain D : Derivative gain dt : Sample time
- def clear_simple(self): Variab... | da67c53cb7fc7f16c0df862a5cff820e9a0a470f | <|skeleton|>
class PID:
def __init__(self, P, I, D, dt, simple):
"""PID definitions Parameters ---------- P : Proportional gain I : Integral gain D : Derivative gain dt : Sample time"""
<|body_0|>
def clear_simple(self):
"""Variables initialization for update_simple() Parameters ------... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PID:
def __init__(self, P, I, D, dt, simple):
"""PID definitions Parameters ---------- P : Proportional gain I : Integral gain D : Derivative gain dt : Sample time"""
self.Kp = P
self.Ki = I
self.Kd = D
self.dt = dt
self.heights = 0
if simple:
... | the_stack_v2_python_sparse | ros_radar_mine/neuro_learning/controller/pid/myPID.py | marina-go-al/blimp_snn | train | 0 | |
5d3d9db9b20a368869d6dff5d8433bc27781b601 | [
"self.url = url\nself.location = location\nself.geo = None\nself.produce = None",
"if self.url.startswith('file:'):\n with open(self.url[6:]) as jsonfile:\n json_data = json.load(jsonfile)\nelse:\n response = magtag.network.fetch(self.url)\n if response.status_code == 200:\n json_data = res... | <|body_start_0|>
self.url = url
self.location = location
self.geo = None
self.produce = None
<|end_body_0|>
<|body_start_1|>
if self.url.startswith('file:'):
with open(self.url[6:]) as jsonfile:
json_data = json.load(jsonfile)
else:
... | Class to generate seasonal produce lists from server-based JSON data. | Produce | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Produce:
"""Class to generate seasonal produce lists from server-based JSON data."""
def __init__(self, url, location):
"""Constructor"""
<|body_0|>
def fetch(self, magtag=None):
"""Retrieves current seasonal produce data from server, does some deserializing and ... | stack_v2_sparse_classes_10k_train_001708 | 8,879 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, url, location)"
},
{
"docstring": "Retrieves current seasonal produce data from server, does some deserializing and processing for later filtering. This is currently tied to a MagTag object -- would prefer to func... | 4 | stack_v2_sparse_classes_30k_train_005773 | Implement the Python class `Produce` described below.
Class description:
Class to generate seasonal produce lists from server-based JSON data.
Method signatures and docstrings:
- def __init__(self, url, location): Constructor
- def fetch(self, magtag=None): Retrieves current seasonal produce data from server, does so... | Implement the Python class `Produce` described below.
Class description:
Class to generate seasonal produce lists from server-based JSON data.
Method signatures and docstrings:
- def __init__(self, url, location): Constructor
- def fetch(self, magtag=None): Retrieves current seasonal produce data from server, does so... | 5eaa7a15a437c533b89f359a25983e24bb6b5438 | <|skeleton|>
class Produce:
"""Class to generate seasonal produce lists from server-based JSON data."""
def __init__(self, url, location):
"""Constructor"""
<|body_0|>
def fetch(self, magtag=None):
"""Retrieves current seasonal produce data from server, does some deserializing and ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Produce:
"""Class to generate seasonal produce lists from server-based JSON data."""
def __init__(self, url, location):
"""Constructor"""
self.url = url
self.location = location
self.geo = None
self.produce = None
def fetch(self, magtag=None):
"""Retri... | the_stack_v2_python_sparse | MagTag_Seasonal_Produce/produce.py | adafruit/Adafruit_Learning_System_Guides | train | 937 |
f69446230814e794529a3d5ced006360e74a44e6 | [
"VapiInterface.__init__(self, config, _InteropReportStub)\nself._VAPI_OPERATION_IDS = {}\nself._VAPI_OPERATION_IDS.update({'create_task': 'create$task'})",
"task_id = self._invoke('create$task', {'spec': spec})\ntask_svc = Tasks(self._config)\ntask_instance = Task(task_id, task_svc, type.ReferenceType(__name__, '... | <|body_start_0|>
VapiInterface.__init__(self, config, _InteropReportStub)
self._VAPI_OPERATION_IDS = {}
self._VAPI_OPERATION_IDS.update({'create_task': 'create$task'})
<|end_body_0|>
<|body_start_1|>
task_id = self._invoke('create$task', {'spec': spec})
task_svc = Tasks(self._co... | The ``InteropReport`` interface provides methods to report the interoperability between a vCenter Server release version and the other installed VMware products registered in the vCenter Server instance. | InteropReport | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InteropReport:
"""The ``InteropReport`` interface provides methods to report the interoperability between a vCenter Server release version and the other installed VMware products registered in the vCenter Server instance."""
def __init__(self, config):
""":type config: :class:`vmware... | stack_v2_sparse_classes_10k_train_001709 | 39,273 | permissive | [
{
"docstring": ":type config: :class:`vmware.vapi.bindings.stub.StubConfiguration` :param config: Configuration to be used for creating the stub.",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Creates interoperability report between a vCenter Server release ve... | 2 | stack_v2_sparse_classes_30k_train_002341 | Implement the Python class `InteropReport` described below.
Class description:
The ``InteropReport`` interface provides methods to report the interoperability between a vCenter Server release version and the other installed VMware products registered in the vCenter Server instance.
Method signatures and docstrings:
-... | Implement the Python class `InteropReport` described below.
Class description:
The ``InteropReport`` interface provides methods to report the interoperability between a vCenter Server release version and the other installed VMware products registered in the vCenter Server instance.
Method signatures and docstrings:
-... | c07e1be98615201139b26c28db3aa584c4254b66 | <|skeleton|>
class InteropReport:
"""The ``InteropReport`` interface provides methods to report the interoperability between a vCenter Server release version and the other installed VMware products registered in the vCenter Server instance."""
def __init__(self, config):
""":type config: :class:`vmware... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InteropReport:
"""The ``InteropReport`` interface provides methods to report the interoperability between a vCenter Server release version and the other installed VMware products registered in the vCenter Server instance."""
def __init__(self, config):
""":type config: :class:`vmware.vapi.binding... | the_stack_v2_python_sparse | com/vmware/vcenter/lcm/discovery_client.py | adammillerio/vsphere-automation-sdk-python | train | 0 |
fa7dfc1616def83f48d3f59eefd3bcaba1b41cfd | [
"value = None\nfor callback in self.callbacks:\n try:\n local_value = callback(*args, **kwargs)\n except Exception as e:\n ip = get_ipython()\n if ip is None:\n self.log.warning('Exception in callback %s: %s', callback, e, exc_info=True)\n else:\n ip.showtrace... | <|body_start_0|>
value = None
for callback in self.callbacks:
try:
local_value = callback(*args, **kwargs)
except Exception as e:
ip = get_ipython()
if ip is None:
self.log.warning('Exception in callback %s: %s',... | A structure for registering and running callbacks | CallbackDispatcher | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CallbackDispatcher:
"""A structure for registering and running callbacks"""
def __call__(self, *args, **kwargs):
"""Call all of the registered callbacks."""
<|body_0|>
def register_callback(self, callback, remove=False):
"""(Un)Register a callback Parameters ----... | stack_v2_sparse_classes_10k_train_001710 | 34,879 | permissive | [
{
"docstring": "Call all of the registered callbacks.",
"name": "__call__",
"signature": "def __call__(self, *args, **kwargs)"
},
{
"docstring": "(Un)Register a callback Parameters ---------- callback: method handle Method to be registered or unregistered. remove=False: bool Whether to unregiste... | 2 | stack_v2_sparse_classes_30k_train_006125 | Implement the Python class `CallbackDispatcher` described below.
Class description:
A structure for registering and running callbacks
Method signatures and docstrings:
- def __call__(self, *args, **kwargs): Call all of the registered callbacks.
- def register_callback(self, callback, remove=False): (Un)Register a cal... | Implement the Python class `CallbackDispatcher` described below.
Class description:
A structure for registering and running callbacks
Method signatures and docstrings:
- def __call__(self, *args, **kwargs): Call all of the registered callbacks.
- def register_callback(self, callback, remove=False): (Un)Register a cal... | f5042e35b945aded77b23470ead62d7eacefde92 | <|skeleton|>
class CallbackDispatcher:
"""A structure for registering and running callbacks"""
def __call__(self, *args, **kwargs):
"""Call all of the registered callbacks."""
<|body_0|>
def register_callback(self, callback, remove=False):
"""(Un)Register a callback Parameters ----... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CallbackDispatcher:
"""A structure for registering and running callbacks"""
def __call__(self, *args, **kwargs):
"""Call all of the registered callbacks."""
value = None
for callback in self.callbacks:
try:
local_value = callback(*args, **kwargs)
... | the_stack_v2_python_sparse | contrib/python/ipywidgets/py3/ipywidgets/widgets/widget.py | catboost/catboost | train | 8,012 |
1d83103e7ca98b2c2cab1e66dbf098a4dc62c3f0 | [
"num_lessons = len(lessons)\nfor index, lesson in enumerate(lessons):\n if index < num_lessons - 1 and lesson.completion_criteria is None:\n raise TrainerConfigError(f'A non-terminal lesson does not have a completion_criteria for {parameter_name}.')\n if index == num_lessons - 1 and lesson.completion_c... | <|body_start_0|>
num_lessons = len(lessons)
for index, lesson in enumerate(lessons):
if index < num_lessons - 1 and lesson.completion_criteria is None:
raise TrainerConfigError(f'A non-terminal lesson does not have a completion_criteria for {parameter_name}.')
if ... | EnvironmentParameterSettings is an ordered list of lessons for one environment parameter. | EnvironmentParameterSettings | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnvironmentParameterSettings:
"""EnvironmentParameterSettings is an ordered list of lessons for one environment parameter."""
def _check_lesson_chain(lessons, parameter_name):
"""Ensures that when using curriculum, all non-terminal lessons have a valid CompletionCriteria, and that th... | stack_v2_sparse_classes_10k_train_001711 | 33,986 | permissive | [
{
"docstring": "Ensures that when using curriculum, all non-terminal lessons have a valid CompletionCriteria, and that the terminal lesson does not contain a CompletionCriteria.",
"name": "_check_lesson_chain",
"signature": "def _check_lesson_chain(lessons, parameter_name)"
},
{
"docstring": "He... | 2 | stack_v2_sparse_classes_30k_train_002908 | Implement the Python class `EnvironmentParameterSettings` described below.
Class description:
EnvironmentParameterSettings is an ordered list of lessons for one environment parameter.
Method signatures and docstrings:
- def _check_lesson_chain(lessons, parameter_name): Ensures that when using curriculum, all non-term... | Implement the Python class `EnvironmentParameterSettings` described below.
Class description:
EnvironmentParameterSettings is an ordered list of lessons for one environment parameter.
Method signatures and docstrings:
- def _check_lesson_chain(lessons, parameter_name): Ensures that when using curriculum, all non-term... | 768405d0f80d30acb29e1f7c201a98ce67a668b3 | <|skeleton|>
class EnvironmentParameterSettings:
"""EnvironmentParameterSettings is an ordered list of lessons for one environment parameter."""
def _check_lesson_chain(lessons, parameter_name):
"""Ensures that when using curriculum, all non-terminal lessons have a valid CompletionCriteria, and that th... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EnvironmentParameterSettings:
"""EnvironmentParameterSettings is an ordered list of lessons for one environment parameter."""
def _check_lesson_chain(lessons, parameter_name):
"""Ensures that when using curriculum, all non-terminal lessons have a valid CompletionCriteria, and that the terminal le... | the_stack_v2_python_sparse | ml-agents/mlagents/trainers/settings.py | xogur6889/ml-agents | train | 2 |
f848cb7d3cfb3e50b0eed557413346816a3f221b | [
"def helper(nums, start, end):\n if start == end:\n return start\n count = 0\n mid = (start + end) // 2\n for num in nums:\n if num >= start and num <= mid:\n count += 1\n if count <= mid - start + 1:\n return helper(nums, mid + 1, end)\n else:\n return helpe... | <|body_start_0|>
def helper(nums, start, end):
if start == end:
return start
count = 0
mid = (start + end) // 2
for num in nums:
if num >= start and num <= mid:
count += 1
if count <= mid - start + 1:... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findDuplicate2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def helper(nums, start, end):
... | stack_v2_sparse_classes_10k_train_001712 | 968 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findDuplicate",
"signature": "def findDuplicate(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findDuplicate2",
"signature": "def findDuplicate2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004108 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums): :type nums: List[int] :rtype: int
- def findDuplicate2(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums): :type nums: List[int] :rtype: int
- def findDuplicate2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def findDu... | 0fc972e5cd2baf1b5ddf8b192962629f40bc3bf4 | <|skeleton|>
class Solution:
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findDuplicate2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
def helper(nums, start, end):
if start == end:
return start
count = 0
mid = (start + end) // 2
for num in nums:
if num >= start and n... | the_stack_v2_python_sparse | problems/287. Find the Duplicate Number.py | yukiii-zhong/Leetcode | train | 2 | |
8b6eec457c1d52828903130dddc183ebff086d99 | [
"try:\n prefix, token = header.split()\nexcept ValueError:\n raise authentication.AuthenticationError('Unable to split prefix and token from Authorization header.')\nif prefix.upper() != 'JWT':\n raise authentication.AuthenticationError(f\"Invalid Authorization header prefix '{prefix}'.\")\nreturn token",
... | <|body_start_0|>
try:
prefix, token = header.split()
except ValueError:
raise authentication.AuthenticationError('Unable to split prefix and token from Authorization header.')
if prefix.upper() != 'JWT':
raise authentication.AuthenticationError(f"Invalid Autho... | Custom Starlette authentication backend for JWT. | JWTAuthenticationBackend | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JWTAuthenticationBackend:
"""Custom Starlette authentication backend for JWT."""
def get_token_from_header(header: str) -> str:
"""Parse JWT token from header value."""
<|body_0|>
async def authenticate(self, request: Request) -> t.Optional[tuple[authentication.AuthCrede... | stack_v2_sparse_classes_10k_train_001713 | 1,656 | permissive | [
{
"docstring": "Parse JWT token from header value.",
"name": "get_token_from_header",
"signature": "def get_token_from_header(header: str) -> str"
},
{
"docstring": "Handles JWT authentication process.",
"name": "authenticate",
"signature": "async def authenticate(self, request: Request)... | 2 | stack_v2_sparse_classes_30k_train_003297 | Implement the Python class `JWTAuthenticationBackend` described below.
Class description:
Custom Starlette authentication backend for JWT.
Method signatures and docstrings:
- def get_token_from_header(header: str) -> str: Parse JWT token from header value.
- async def authenticate(self, request: Request) -> t.Optiona... | Implement the Python class `JWTAuthenticationBackend` described below.
Class description:
Custom Starlette authentication backend for JWT.
Method signatures and docstrings:
- def get_token_from_header(header: str) -> str: Parse JWT token from header value.
- async def authenticate(self, request: Request) -> t.Optiona... | 1b4b4fe6819352f1f072ce307eee892866a11dcf | <|skeleton|>
class JWTAuthenticationBackend:
"""Custom Starlette authentication backend for JWT."""
def get_token_from_header(header: str) -> str:
"""Parse JWT token from header value."""
<|body_0|>
async def authenticate(self, request: Request) -> t.Optional[tuple[authentication.AuthCrede... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class JWTAuthenticationBackend:
"""Custom Starlette authentication backend for JWT."""
def get_token_from_header(header: str) -> str:
"""Parse JWT token from header value."""
try:
prefix, token = header.split()
except ValueError:
raise authentication.Authenticati... | the_stack_v2_python_sparse | backend/authentication/backend.py | MrGrote/forms-backend | train | 0 |
16735da1a755908f562d3d59cf5ed009f837f213 | [
"dqrqsj = datetime.datetime.now().strftime('%Y%m%d%H:%M:%S')\ndqrq = dqrqsj[:8]\ndqsj = dqrqsj[8:]\nqtrqsj = (datetime.datetime.strptime(dqrqsj, '%Y%m%d%H:%M:%S') - datetime.timedelta(minutes=int(min))).strftime('%Y%m%d%H:%M:%S')\nqtrq = qtrqsj[:8]\nqtsj = qtrqsj[8:]\nxym_str_lst = sbxymlb.split(',')\njym_str_lst =... | <|body_start_0|>
dqrqsj = datetime.datetime.now().strftime('%Y%m%d%H:%M:%S')
dqrq = dqrqsj[:8]
dqsj = dqrqsj[8:]
qtrqsj = (datetime.datetime.strptime(dqrqsj, '%Y%m%d%H:%M:%S') - datetime.timedelta(minutes=int(min))).strftime('%Y%m%d%H:%M:%S')
qtrq = qtrqsj[:8]
qtsj = qtrq... | Business | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Business:
def get_failtrans(self, jymlb, sbxymlb, min):
"""获取交易失败笔数"""
<|body_0|>
def get_firstrans(self, jymlb):
"""获取业务第一笔交易"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dqrqsj = datetime.datetime.now().strftime('%Y%m%d%H:%M:%S')
dqrq =... | stack_v2_sparse_classes_10k_train_001714 | 16,132 | no_license | [
{
"docstring": "获取交易失败笔数",
"name": "get_failtrans",
"signature": "def get_failtrans(self, jymlb, sbxymlb, min)"
},
{
"docstring": "获取业务第一笔交易",
"name": "get_firstrans",
"signature": "def get_firstrans(self, jymlb)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000262 | Implement the Python class `Business` described below.
Class description:
Implement the Business class.
Method signatures and docstrings:
- def get_failtrans(self, jymlb, sbxymlb, min): 获取交易失败笔数
- def get_firstrans(self, jymlb): 获取业务第一笔交易 | Implement the Python class `Business` described below.
Class description:
Implement the Business class.
Method signatures and docstrings:
- def get_failtrans(self, jymlb, sbxymlb, min): 获取交易失败笔数
- def get_firstrans(self, jymlb): 获取业务第一笔交易
<|skeleton|>
class Business:
def get_failtrans(self, jymlb, sbxymlb, min)... | 68ddf3df6d2cd731e6634b09d27aff4c22debd8e | <|skeleton|>
class Business:
def get_failtrans(self, jymlb, sbxymlb, min):
"""获取交易失败笔数"""
<|body_0|>
def get_firstrans(self, jymlb):
"""获取业务第一笔交易"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Business:
def get_failtrans(self, jymlb, sbxymlb, min):
"""获取交易失败笔数"""
dqrqsj = datetime.datetime.now().strftime('%Y%m%d%H:%M:%S')
dqrq = dqrqsj[:8]
dqsj = dqrqsj[8:]
qtrqsj = (datetime.datetime.strptime(dqrqsj, '%Y%m%d%H:%M:%S') - datetime.timedelta(minutes=int(min))).... | the_stack_v2_python_sparse | zh_manage/apps/_init/oa/yw_jkgl/yw_jkgl_001/yw_jkgl_001.py | yizhong120110/CPOS | train | 0 | |
97dd1b37636d5a29cf4b624ffa5550946ac1e874 | [
"self._axis = axis\nself._title = title\nself._xlabel = x_label\nself._ylabel = y_label\nself.canvas = scene.SceneCanvas(keys='interactive', bgcolor=bgcolor, show=False, title=name, **cargs)\nif axis:\n grid = self.canvas.central_widget.add_grid(margin=10)\n grid.spacing = 0\n self._titleObj = scene.Label(... | <|body_start_0|>
self._axis = axis
self._title = title
self._xlabel = x_label
self._ylabel = y_label
self.canvas = scene.SceneCanvas(keys='interactive', bgcolor=bgcolor, show=False, title=name, **cargs)
if axis:
grid = self.canvas.central_widget.add_grid(margi... | Create a canvas with an embeded axis. | AxisCanvas | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AxisCanvas:
"""Create a canvas with an embeded axis."""
def __init__(self, axis=True, x_label='', x_heightMax=80, y_label='', y_widthMax=80, font_size=12, color='white', title='', axis_label_margin=50, tick_label_margin=5, name='', bgcolor=(0.9, 0.9, 0.9), cargs={}, xargs={}, yargs={}):
... | stack_v2_sparse_classes_10k_train_001715 | 11,761 | permissive | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self, axis=True, x_label='', x_heightMax=80, y_label='', y_widthMax=80, font_size=12, color='white', title='', axis_label_margin=50, tick_label_margin=5, name='', bgcolor=(0.9, 0.9, 0.9), cargs={}, xargs={}, yargs={})"
},
{
"... | 4 | stack_v2_sparse_classes_30k_train_006659 | Implement the Python class `AxisCanvas` described below.
Class description:
Create a canvas with an embeded axis.
Method signatures and docstrings:
- def __init__(self, axis=True, x_label='', x_heightMax=80, y_label='', y_widthMax=80, font_size=12, color='white', title='', axis_label_margin=50, tick_label_margin=5, n... | Implement the Python class `AxisCanvas` described below.
Class description:
Create a canvas with an embeded axis.
Method signatures and docstrings:
- def __init__(self, axis=True, x_label='', x_heightMax=80, y_label='', y_widthMax=80, font_size=12, color='white', title='', axis_label_margin=50, tick_label_margin=5, n... | b5f480a16555a10b0032465699a0c371e2be31db | <|skeleton|>
class AxisCanvas:
"""Create a canvas with an embeded axis."""
def __init__(self, axis=True, x_label='', x_heightMax=80, y_label='', y_widthMax=80, font_size=12, color='white', title='', axis_label_margin=50, tick_label_margin=5, name='', bgcolor=(0.9, 0.9, 0.9), cargs={}, xargs={}, yargs={}):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AxisCanvas:
"""Create a canvas with an embeded axis."""
def __init__(self, axis=True, x_label='', x_heightMax=80, y_label='', y_widthMax=80, font_size=12, color='white', title='', axis_label_margin=50, tick_label_margin=5, name='', bgcolor=(0.9, 0.9, 0.9), cargs={}, xargs={}, yargs={}):
"""Init."... | the_stack_v2_python_sparse | visbrain/ndviz/interface/uiInit.py | christian-oreilly/visbrain | train | 0 |
be2644616b6b0ede0bd3af743843ea8b722aeb0e | [
"if not root:\n return '_'\nelse:\n left_repr = f'({self.serialize(root.left)})' if root.left else '_'\n right_repr = f'({self.serialize(root.right)})' if root.right else '_'\n return f'{root.val} {left_repr} {right_repr}'",
"if data[0] == '_':\n return None\narr = data.split()\nrootVal = arr[0]\nd... | <|body_start_0|>
if not root:
return '_'
else:
left_repr = f'({self.serialize(root.left)})' if root.left else '_'
right_repr = f'({self.serialize(root.right)})' if root.right else '_'
return f'{root.val} {left_repr} {right_repr}'
<|end_body_0|>
<|body_sta... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
... | stack_v2_sparse_classes_10k_train_001716 | 1,743 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_002105 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | ec14ad04893073ff911b6d11aacc26b372766b6d | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
if not root:
return '_'
else:
left_repr = f'({self.serialize(root.left)})' if root.left else '_'
right_repr = f'({self.serialize(root.right)})' if root.right ... | the_stack_v2_python_sparse | problems/Medium/serialize-and-deserialize-binary-tree/sol.py | Zahidsqldba07/leetcode-3 | train | 0 | |
b01b756a452aeb8a72bf22532397daf9d4c3037c | [
"count = 0\nfor i in range(len(dominoes) - 1):\n for j in range(i + 1, len(dominoes)):\n if dominoes[i][0] == dominoes[j][0] and dominoes[i][1] == dominoes[j][1] or (dominoes[i][1] == dominoes[j][0] and dominoes[i][0] == dominoes[j][1]):\n count += 1\nreturn count",
"data = {}\nfor domino in ... | <|body_start_0|>
count = 0
for i in range(len(dominoes) - 1):
for j in range(i + 1, len(dominoes)):
if dominoes[i][0] == dominoes[j][0] and dominoes[i][1] == dominoes[j][1] or (dominoes[i][1] == dominoes[j][0] and dominoes[i][0] == dominoes[j][1]):
count +... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _numEquivDominoPairs(self, dominoes):
""":type dominoes: List[List[int]] :rtype: int"""
<|body_0|>
def numEquivDominoPairs(self, dominoes):
""":type dominoes: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_001717 | 1,904 | permissive | [
{
"docstring": ":type dominoes: List[List[int]] :rtype: int",
"name": "_numEquivDominoPairs",
"signature": "def _numEquivDominoPairs(self, dominoes)"
},
{
"docstring": ":type dominoes: List[List[int]] :rtype: int",
"name": "numEquivDominoPairs",
"signature": "def numEquivDominoPairs(self... | 2 | stack_v2_sparse_classes_30k_train_004899 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _numEquivDominoPairs(self, dominoes): :type dominoes: List[List[int]] :rtype: int
- def numEquivDominoPairs(self, dominoes): :type dominoes: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _numEquivDominoPairs(self, dominoes): :type dominoes: List[List[int]] :rtype: int
- def numEquivDominoPairs(self, dominoes): :type dominoes: List[List[int]] :rtype: int
<|sk... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _numEquivDominoPairs(self, dominoes):
""":type dominoes: List[List[int]] :rtype: int"""
<|body_0|>
def numEquivDominoPairs(self, dominoes):
""":type dominoes: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def _numEquivDominoPairs(self, dominoes):
""":type dominoes: List[List[int]] :rtype: int"""
count = 0
for i in range(len(dominoes) - 1):
for j in range(i + 1, len(dominoes)):
if dominoes[i][0] == dominoes[j][0] and dominoes[i][1] == dominoes[j][1] ... | the_stack_v2_python_sparse | 1128.number-of-equivalent-domino-pairs.py | windard/leeeeee | train | 0 | |
446f93db141f6f425732417fb84e211bbd69465d | [
"super().__init__()\nself.N = N\nself.dm = dm\nself.embedding = tf.keras.layers.Embedding(input_vocab, dm)\nself.positional_encoding = positional_encoding(max_seq_len, self.dm)\nself.blocks = [EncoderBlock(dm, h, hidden, drop_rate) for _ in range(N)]\nself.dropout = tf.keras.layers.Dropout(drop_rate)",
"seq_len =... | <|body_start_0|>
super().__init__()
self.N = N
self.dm = dm
self.embedding = tf.keras.layers.Embedding(input_vocab, dm)
self.positional_encoding = positional_encoding(max_seq_len, self.dm)
self.blocks = [EncoderBlock(dm, h, hidden, drop_rate) for _ in range(N)]
se... | Encoder class | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""Encoder class"""
def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1):
"""* N - the number of blocks in the encoder * dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layer... | stack_v2_sparse_classes_10k_train_001718 | 18,002 | no_license | [
{
"docstring": "* N - the number of blocks in the encoder * dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layer * input_vocab - the size of the input vocabulary * max_seq_len - the maximum sequence length possible * drop_rate - the dr... | 2 | stack_v2_sparse_classes_30k_train_004160 | Implement the Python class `Encoder` described below.
Class description:
Encoder class
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): * N - the number of blocks in the encoder * dm - the dimensionality of the model * h - the number of heads * hidden ... | Implement the Python class `Encoder` described below.
Class description:
Encoder class
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): * N - the number of blocks in the encoder * dm - the dimensionality of the model * h - the number of heads * hidden ... | 8ad4c2594ff78b345dbd92e9d54d2a143ac4071a | <|skeleton|>
class Encoder:
"""Encoder class"""
def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1):
"""* N - the number of blocks in the encoder * dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layer... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Encoder:
"""Encoder class"""
def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1):
"""* N - the number of blocks in the encoder * dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layer * input_voca... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/5-transformer.py | jorgezafra94/holbertonschool-machine_learning | train | 1 |
ea36ade8a33842c8dbd8e47540220a1fab72ce31 | [
"if not root:\n ans = ''\nelif not root.children:\n ans = f'{root.val}'\nelse:\n children = [self.serialize(child) for child in root.children if child]\n children_str = ' '.join(children)\n ans = f'{root.val}[{children_str}]'\nreturn ans",
"if not data:\n return None\nif '[' not in data:\n re... | <|body_start_0|>
if not root:
ans = ''
elif not root.children:
ans = f'{root.val}'
else:
children = [self.serialize(child) for child in root.children if child]
children_str = ' '.join(children)
ans = f'{root.val}[{children_str}]'
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_001719 | 1,909 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: 'Node') -> str"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def des... | 3 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | e00cf94c5b86c8cca27e3bee69ad21e727b7679b | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
if not root:
ans = ''
elif not root.children:
ans = f'{root.val}'
else:
children = [self.serialize(child) for child in root... | the_stack_v2_python_sparse | recursion/prob428.py | binchen15/leet-python | train | 1 | |
86f391950b29bb1345498ed8b89c11eaba63bc10 | [
"self.content_folder = content_folder\nsignature_path = os.path.join(self.content_folder, signature_filename)\nrootCA_cert_path = os.path.join(self.content_folder, root_cert)\nif os.path.exists(signature_path) and os.path.exists(rootCA_cert_path):\n self.signature = json.load(open(signature_path, 'rt'))\n for... | <|body_start_0|>
self.content_folder = content_folder
signature_path = os.path.join(self.content_folder, signature_filename)
rootCA_cert_path = os.path.join(self.content_folder, root_cert)
if os.path.exists(signature_path) and os.path.exists(rootCA_cert_path):
self.signature ... | SecurityContentManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SecurityContentManager:
def __init__(self, content_folder, signature_filename='signature.json', root_cert='rootCA.pem'):
"""Content manager used by SecurityContentService to load secure content. Args: content_folder (str): the folder path that includes signature file signature_filename (... | stack_v2_sparse_classes_10k_train_001720 | 5,241 | permissive | [
{
"docstring": "Content manager used by SecurityContentService to load secure content. Args: content_folder (str): the folder path that includes signature file signature_filename (str, optional): the signature file (signed dictionary). Defaults to \"signature.json\". root_cert (str, optional): root CA certifica... | 2 | null | Implement the Python class `SecurityContentManager` described below.
Class description:
Implement the SecurityContentManager class.
Method signatures and docstrings:
- def __init__(self, content_folder, signature_filename='signature.json', root_cert='rootCA.pem'): Content manager used by SecurityContentService to loa... | Implement the Python class `SecurityContentManager` described below.
Class description:
Implement the SecurityContentManager class.
Method signatures and docstrings:
- def __init__(self, content_folder, signature_filename='signature.json', root_cert='rootCA.pem'): Content manager used by SecurityContentService to loa... | 1433290c203bd23f34c29e11795ce592bc067888 | <|skeleton|>
class SecurityContentManager:
def __init__(self, content_folder, signature_filename='signature.json', root_cert='rootCA.pem'):
"""Content manager used by SecurityContentService to load secure content. Args: content_folder (str): the folder path that includes signature file signature_filename (... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SecurityContentManager:
def __init__(self, content_folder, signature_filename='signature.json', root_cert='rootCA.pem'):
"""Content manager used by SecurityContentService to load secure content. Args: content_folder (str): the folder path that includes signature file signature_filename (str, optional)... | the_stack_v2_python_sparse | nvflare/fuel/sec/security_content_service.py | NVIDIA/NVFlare | train | 442 | |
14093f241d4ba36355ea7f0a2ca34dcf95790402 | [
"l = 0\nr = len(nums) - 1\nwhile l <= r:\n m = l + (r - l) // 2\n if nums[m] == target:\n return True\n while l < m and nums[l] == nums[m]:\n l += 1\n if nums[l] == nums[m]:\n l = m + 1\n elif nums[l] < nums[m]:\n if nums[l] <= target < nums[m]:\n r = m - 1\n ... | <|body_start_0|>
l = 0
r = len(nums) - 1
while l <= r:
m = l + (r - l) // 2
if nums[m] == target:
return True
while l < m and nums[l] == nums[m]:
l += 1
if nums[l] == nums[m]:
l = m + 1
el... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def search(self, nums: List[int], target: int) -> bool:
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_10k_train_001721 | 2,053 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "search",
"signature": "def search(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "search",
"signature": "def search(self, nums: List[int], target: int) ->... | 2 | stack_v2_sparse_classes_30k_train_003008 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def search(self, nums: List[int], target: int) -> bool: :type nums: List[int] :type target: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def search(self, nums: List[int], target: int) -> bool: :type nums: List[int] :type target: ... | 2ecaeed38178819480388b5742bc2ea12009ae16 | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def search(self, nums: List[int], target: int) -> bool:
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
l = 0
r = len(nums) - 1
while l <= r:
m = l + (r - l) // 2
if nums[m] == target:
return True
while l < m and nums[l] == nums[m... | the_stack_v2_python_sparse | 81.search-in-rotated-sorted-array-ii.py | LouisYLWang/leetcode_python | train | 0 | |
0101cb4e170a8d168a24134fee231c0d44274d44 | [
"session = db_apis.get_session()\nwith session.begin():\n if not amps_data:\n db_lb = self.loadbalancer_repo.get(session, id=loadbalancer[constants.LOADBALANCER_ID])\n amps_data = db_lb.amphorae\n amps_data = [amp for amp in amps_data if amp.status == constants.AMPHORA_ALLOCATED]\napply_qos = Ap... | <|body_start_0|>
session = db_apis.get_session()
with session.begin():
if not amps_data:
db_lb = self.loadbalancer_repo.get(session, id=loadbalancer[constants.LOADBALANCER_ID])
amps_data = db_lb.amphorae
amps_data = [amp for amp in amps_data if amp... | Apply Quality of Services to the VIP | ApplyQos | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApplyQos:
"""Apply Quality of Services to the VIP"""
def _apply_qos_on_vrrp_ports(self, loadbalancer, amps_data, qos_policy_id, is_revert=False, request_qos_id=None):
"""Call network driver to apply QoS Policy on the vrrp ports."""
<|body_0|>
def execute(self, loadbalanc... | stack_v2_sparse_classes_10k_train_001722 | 44,034 | permissive | [
{
"docstring": "Call network driver to apply QoS Policy on the vrrp ports.",
"name": "_apply_qos_on_vrrp_ports",
"signature": "def _apply_qos_on_vrrp_ports(self, loadbalancer, amps_data, qos_policy_id, is_revert=False, request_qos_id=None)"
},
{
"docstring": "Apply qos policy on the vrrp ports w... | 3 | null | Implement the Python class `ApplyQos` described below.
Class description:
Apply Quality of Services to the VIP
Method signatures and docstrings:
- def _apply_qos_on_vrrp_ports(self, loadbalancer, amps_data, qos_policy_id, is_revert=False, request_qos_id=None): Call network driver to apply QoS Policy on the vrrp ports... | Implement the Python class `ApplyQos` described below.
Class description:
Apply Quality of Services to the VIP
Method signatures and docstrings:
- def _apply_qos_on_vrrp_ports(self, loadbalancer, amps_data, qos_policy_id, is_revert=False, request_qos_id=None): Call network driver to apply QoS Policy on the vrrp ports... | 0426285a41464a5015494584f109eed35a0d44db | <|skeleton|>
class ApplyQos:
"""Apply Quality of Services to the VIP"""
def _apply_qos_on_vrrp_ports(self, loadbalancer, amps_data, qos_policy_id, is_revert=False, request_qos_id=None):
"""Call network driver to apply QoS Policy on the vrrp ports."""
<|body_0|>
def execute(self, loadbalanc... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ApplyQos:
"""Apply Quality of Services to the VIP"""
def _apply_qos_on_vrrp_ports(self, loadbalancer, amps_data, qos_policy_id, is_revert=False, request_qos_id=None):
"""Call network driver to apply QoS Policy on the vrrp ports."""
session = db_apis.get_session()
with session.begi... | the_stack_v2_python_sparse | octavia/controller/worker/v2/tasks/network_tasks.py | openstack/octavia | train | 147 |
683bf0ec1107ab215d2def9d8ce9adf140861a08 | [
"prev = [-float('inf')]\ncurr_min = [float('inf')]\n\ndef inorder_traverse(node, prev, curr_min):\n if node:\n inorder_traverse(node.left, prev, curr_min)\n curr_min[0] = min(curr_min[0], node.val - prev[0])\n prev[0] = node.val\n inorder_traverse(node.right, prev, curr_min)\ninorder_... | <|body_start_0|>
prev = [-float('inf')]
curr_min = [float('inf')]
def inorder_traverse(node, prev, curr_min):
if node:
inorder_traverse(node.left, prev, curr_min)
curr_min[0] = min(curr_min[0], node.val - prev[0])
prev[0] = node.val
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDiffInBST(self, root: TreeNode) -> int:
"""Compare numbers in in-order traversal. Time: O(n) Space: O(1)"""
<|body_0|>
def minDiffInBST2(self, root: TreeNode) -> int:
"""Flatten tree then find minimum diff. Time: O(n) Space: O(n)"""
<|body_1|... | stack_v2_sparse_classes_10k_train_001723 | 1,365 | no_license | [
{
"docstring": "Compare numbers in in-order traversal. Time: O(n) Space: O(1)",
"name": "minDiffInBST",
"signature": "def minDiffInBST(self, root: TreeNode) -> int"
},
{
"docstring": "Flatten tree then find minimum diff. Time: O(n) Space: O(n)",
"name": "minDiffInBST2",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_003821 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDiffInBST(self, root: TreeNode) -> int: Compare numbers in in-order traversal. Time: O(n) Space: O(1)
- def minDiffInBST2(self, root: TreeNode) -> int: Flatten tree then f... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDiffInBST(self, root: TreeNode) -> int: Compare numbers in in-order traversal. Time: O(n) Space: O(1)
- def minDiffInBST2(self, root: TreeNode) -> int: Flatten tree then f... | c14d8829c95f61ff6691816e8c0de76b9319f389 | <|skeleton|>
class Solution:
def minDiffInBST(self, root: TreeNode) -> int:
"""Compare numbers in in-order traversal. Time: O(n) Space: O(1)"""
<|body_0|>
def minDiffInBST2(self, root: TreeNode) -> int:
"""Flatten tree then find minimum diff. Time: O(n) Space: O(n)"""
<|body_1|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def minDiffInBST(self, root: TreeNode) -> int:
"""Compare numbers in in-order traversal. Time: O(n) Space: O(1)"""
prev = [-float('inf')]
curr_min = [float('inf')]
def inorder_traverse(node, prev, curr_min):
if node:
inorder_traverse(node.... | the_stack_v2_python_sparse | easy/minimum-distance-between-bst-nodes/solution.py | hsuanhauliu/leetcode-solutions | train | 0 | |
127b536d18395e0b543d55cd05265cf700cf6b83 | [
"ENFORCER.enforce_call(action='identity:check_grant', build_target=functools.partial(_build_enforcement_target_attr, domain_id=domain_id, user_id=user_id, role_id=role_id))\nPROVIDERS.assignment_api.get_grant(domain_id=domain_id, user_id=user_id, role_id=role_id, inherited_to_projects=True)\nreturn (None, http_clie... | <|body_start_0|>
ENFORCER.enforce_call(action='identity:check_grant', build_target=functools.partial(_build_enforcement_target_attr, domain_id=domain_id, user_id=user_id, role_id=role_id))
PROVIDERS.assignment_api.get_grant(domain_id=domain_id, user_id=user_id, role_id=role_id, inherited_to_projects=Tru... | OSInheritDomainUserRolesResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OSInheritDomainUserRolesResource:
def get(self, domain_id, user_id, role_id):
"""Check for an inherited grant for a user on a domain. GET/HEAD /OS-INHERIT/domains/{domain_id}/users/{user_id}/roles /{role_id}/inherited_to_projects"""
<|body_0|>
def put(self, domain_id, user_i... | stack_v2_sparse_classes_10k_train_001724 | 19,022 | permissive | [
{
"docstring": "Check for an inherited grant for a user on a domain. GET/HEAD /OS-INHERIT/domains/{domain_id}/users/{user_id}/roles /{role_id}/inherited_to_projects",
"name": "get",
"signature": "def get(self, domain_id, user_id, role_id)"
},
{
"docstring": "Create an inherited grant for a user ... | 3 | stack_v2_sparse_classes_30k_train_004156 | Implement the Python class `OSInheritDomainUserRolesResource` described below.
Class description:
Implement the OSInheritDomainUserRolesResource class.
Method signatures and docstrings:
- def get(self, domain_id, user_id, role_id): Check for an inherited grant for a user on a domain. GET/HEAD /OS-INHERIT/domains/{dom... | Implement the Python class `OSInheritDomainUserRolesResource` described below.
Class description:
Implement the OSInheritDomainUserRolesResource class.
Method signatures and docstrings:
- def get(self, domain_id, user_id, role_id): Check for an inherited grant for a user on a domain. GET/HEAD /OS-INHERIT/domains/{dom... | 03a0a8146a78682ede9eca12a5a7fdacde2035c8 | <|skeleton|>
class OSInheritDomainUserRolesResource:
def get(self, domain_id, user_id, role_id):
"""Check for an inherited grant for a user on a domain. GET/HEAD /OS-INHERIT/domains/{domain_id}/users/{user_id}/roles /{role_id}/inherited_to_projects"""
<|body_0|>
def put(self, domain_id, user_i... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OSInheritDomainUserRolesResource:
def get(self, domain_id, user_id, role_id):
"""Check for an inherited grant for a user on a domain. GET/HEAD /OS-INHERIT/domains/{domain_id}/users/{user_id}/roles /{role_id}/inherited_to_projects"""
ENFORCER.enforce_call(action='identity:check_grant', build_ta... | the_stack_v2_python_sparse | keystone/api/os_inherit.py | sapcc/keystone | train | 0 | |
66f19c2bd040e0a7bfc6131cbf1b69063e33276b | [
"credentials = pika.PlainCredentials(username, password)\nparams = pika.ConnectionParameters(host, port, vhost, credentials, socket_timeout=3, retry_delay=3)\nconnection = pika.BlockingConnection(params)\nself.channel = connection.channel()",
"self.extra_callback = callback\nself.channel.queue_declare(queue=queue... | <|body_start_0|>
credentials = pika.PlainCredentials(username, password)
params = pika.ConnectionParameters(host, port, vhost, credentials, socket_timeout=3, retry_delay=3)
connection = pika.BlockingConnection(params)
self.channel = connection.channel()
<|end_body_0|>
<|body_start_1|>
... | Queue consumer. | Consumer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Consumer:
"""Queue consumer."""
def __init__(self, host, port, vhost, username, password):
"""Initialize LogConsumer."""
<|body_0|>
def consume(self, queue, callback, args={}):
"""Consuming listener."""
<|body_1|>
def callback(self, ch, method, props... | stack_v2_sparse_classes_10k_train_001725 | 1,991 | no_license | [
{
"docstring": "Initialize LogConsumer.",
"name": "__init__",
"signature": "def __init__(self, host, port, vhost, username, password)"
},
{
"docstring": "Consuming listener.",
"name": "consume",
"signature": "def consume(self, queue, callback, args={})"
},
{
"docstring": "Called ... | 3 | stack_v2_sparse_classes_30k_train_000396 | Implement the Python class `Consumer` described below.
Class description:
Queue consumer.
Method signatures and docstrings:
- def __init__(self, host, port, vhost, username, password): Initialize LogConsumer.
- def consume(self, queue, callback, args={}): Consuming listener.
- def callback(self, ch, method, props, bo... | Implement the Python class `Consumer` described below.
Class description:
Queue consumer.
Method signatures and docstrings:
- def __init__(self, host, port, vhost, username, password): Initialize LogConsumer.
- def consume(self, queue, callback, args={}): Consuming listener.
- def callback(self, ch, method, props, bo... | b1067b8b90a4d0e2269a7a57779f81dd4209100c | <|skeleton|>
class Consumer:
"""Queue consumer."""
def __init__(self, host, port, vhost, username, password):
"""Initialize LogConsumer."""
<|body_0|>
def consume(self, queue, callback, args={}):
"""Consuming listener."""
<|body_1|>
def callback(self, ch, method, props... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Consumer:
"""Queue consumer."""
def __init__(self, host, port, vhost, username, password):
"""Initialize LogConsumer."""
credentials = pika.PlainCredentials(username, password)
params = pika.ConnectionParameters(host, port, vhost, credentials, socket_timeout=3, retry_delay=3)
... | the_stack_v2_python_sparse | packages/amqp/consumer.py | michaelmob/it490-car-calendar | train | 0 |
a1d8254c5eac458e2824f9d6a472f098b9fcb162 | [
"add_furniture('invoice.csv', 'Elisa Miles', 'LR04', 'Leather Sofa', 25)\nadd_furniture('invoice.csv', 'Edward Data', 'KT78', 'Kitchen Table', 10)\nadd_furniture('invoice.csv', 'Alex Gonzales', 'BR02', 'Queen Mattress', 17)\nwith open('invoice.csv', 'r') as csvfile:\n rentals = []\n for row in csvfile:\n ... | <|body_start_0|>
add_furniture('invoice.csv', 'Elisa Miles', 'LR04', 'Leather Sofa', 25)
add_furniture('invoice.csv', 'Edward Data', 'KT78', 'Kitchen Table', 10)
add_furniture('invoice.csv', 'Alex Gonzales', 'BR02', 'Queen Mattress', 17)
with open('invoice.csv', 'r') as csvfile:
... | Class to test inventory module. | TestIventory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestIventory:
"""Class to test inventory module."""
def test_add_furniture(self):
"""Function to test add furniture functionality."""
<|body_0|>
def test_single_customer(self):
"""Tests single customer functionality."""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_10k_train_001726 | 1,649 | no_license | [
{
"docstring": "Function to test add furniture functionality.",
"name": "test_add_furniture",
"signature": "def test_add_furniture(self)"
},
{
"docstring": "Tests single customer functionality.",
"name": "test_single_customer",
"signature": "def test_single_customer(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003785 | Implement the Python class `TestIventory` described below.
Class description:
Class to test inventory module.
Method signatures and docstrings:
- def test_add_furniture(self): Function to test add furniture functionality.
- def test_single_customer(self): Tests single customer functionality. | Implement the Python class `TestIventory` described below.
Class description:
Class to test inventory module.
Method signatures and docstrings:
- def test_add_furniture(self): Function to test add furniture functionality.
- def test_single_customer(self): Tests single customer functionality.
<|skeleton|>
class TestI... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class TestIventory:
"""Class to test inventory module."""
def test_add_furniture(self):
"""Function to test add furniture functionality."""
<|body_0|>
def test_single_customer(self):
"""Tests single customer functionality."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestIventory:
"""Class to test inventory module."""
def test_add_furniture(self):
"""Function to test add furniture functionality."""
add_furniture('invoice.csv', 'Elisa Miles', 'LR04', 'Leather Sofa', 25)
add_furniture('invoice.csv', 'Edward Data', 'KT78', 'Kitchen Table', 10)
... | the_stack_v2_python_sparse | students/N0vA/lesson08/assignment/test_inventory.py | JavaRod/SP_Python220B_2019 | train | 1 |
bed877936807c4ef341ab4bd0bbac28b5373ace9 | [
"dup, missing = (-1, -1)\nfor n in nums:\n if nums[abs(n) - 1] < 0:\n dup = abs(n)\n else:\n nums[abs(n) - 1] *= -1\nfor i in xrange(len(nums)):\n if nums[i] > 0:\n missing = i + 1\n break\nreturn [dup, missing]",
"S = set()\ndup, missing = (-1, -1)\nfor n in nums:\n if n n... | <|body_start_0|>
dup, missing = (-1, -1)
for n in nums:
if nums[abs(n) - 1] < 0:
dup = abs(n)
else:
nums[abs(n) - 1] *= -1
for i in xrange(len(nums)):
if nums[i] > 0:
missing = i + 1
break
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findErrorNums(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def findErrorNumsFirstSolution(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dup, missing = (... | stack_v2_sparse_classes_10k_train_001727 | 987 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "findErrorNums",
"signature": "def findErrorNums(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "findErrorNumsFirstSolution",
"signature": "def findErrorNumsFirstSolution(self, nums)"
}... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findErrorNums(self, nums): :type nums: List[int] :rtype: List[int]
- def findErrorNumsFirstSolution(self, nums): :type nums: List[int] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findErrorNums(self, nums): :type nums: List[int] :rtype: List[int]
- def findErrorNumsFirstSolution(self, nums): :type nums: List[int] :rtype: List[int]
<|skeleton|>
class S... | 25e5caf324e25edfdf0a7a3be1e572f5d4c88837 | <|skeleton|>
class Solution:
def findErrorNums(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def findErrorNumsFirstSolution(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findErrorNums(self, nums):
""":type nums: List[int] :rtype: List[int]"""
dup, missing = (-1, -1)
for n in nums:
if nums[abs(n) - 1] < 0:
dup = abs(n)
else:
nums[abs(n) - 1] *= -1
for i in xrange(len(nums)):
... | the_stack_v2_python_sparse | Arrays/set_mismatch.py | msraju2009/CodingProblemsPractice | train | 0 | |
6fad8ed0e7549cf93a323465b60a264ab7cf7919 | [
"try:\n label = get_single_label(id, self.request.user.id)\n return label\nexcept IndexError:\n raise RequestObjectDoesNotExixts(code=409, msg=response_code[409])",
"try:\n label = self.get_object(id)\n return Response({'data': label, 'code': 200, 'msg': response_code[200]})\nexcept RequestObjectDo... | <|body_start_0|>
try:
label = get_single_label(id, self.request.user.id)
return label
except IndexError:
raise RequestObjectDoesNotExixts(code=409, msg=response_code[409])
<|end_body_0|>
<|body_start_1|>
try:
label = self.get_object(id)
... | EditLabel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditLabel:
def get_object(self, id=None):
"""param id: Label id returns: single label or raise error"""
<|body_0|>
def get(self, request, id=None):
"""param request, id: Http request contains user detail, id contains label id returns: single label or does not exist""... | stack_v2_sparse_classes_10k_train_001728 | 4,340 | no_license | [
{
"docstring": "param id: Label id returns: single label or raise error",
"name": "get_object",
"signature": "def get_object(self, id=None)"
},
{
"docstring": "param request, id: Http request contains user detail, id contains label id returns: single label or does not exist",
"name": "get",
... | 3 | stack_v2_sparse_classes_30k_train_006578 | Implement the Python class `EditLabel` described below.
Class description:
Implement the EditLabel class.
Method signatures and docstrings:
- def get_object(self, id=None): param id: Label id returns: single label or raise error
- def get(self, request, id=None): param request, id: Http request contains user detail, ... | Implement the Python class `EditLabel` described below.
Class description:
Implement the EditLabel class.
Method signatures and docstrings:
- def get_object(self, id=None): param id: Label id returns: single label or raise error
- def get(self, request, id=None): param request, id: Http request contains user detail, ... | 8513e544cc635c372998cb8ac57bd4c93c431a9a | <|skeleton|>
class EditLabel:
def get_object(self, id=None):
"""param id: Label id returns: single label or raise error"""
<|body_0|>
def get(self, request, id=None):
"""param request, id: Http request contains user detail, id contains label id returns: single label or does not exist""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EditLabel:
def get_object(self, id=None):
"""param id: Label id returns: single label or raise error"""
try:
label = get_single_label(id, self.request.user.id)
return label
except IndexError:
raise RequestObjectDoesNotExixts(code=409, msg=response_co... | the_stack_v2_python_sparse | fundoo/label/views.py | deep-sarkar/keep | train | 0 | |
2cc288720ee1001e678906c58328cb0fd5300a35 | [
"self.w = width\nself.h = height\nself.food = food\nself.score = 0\nself.snake = collections.deque([(0, 0)])\nself.delta = {'U': (-1, 0), 'L': (0, -1), 'R': (0, 1), 'D': (1, 0)}\nself.visited = set((0, 0))",
"x, y = self.snake[-1]\ndx, dy = self.delta[direction]\nnx, ny = (x + dx, y + dy)\nif nx < 0 or nx >= self... | <|body_start_0|>
self.w = width
self.h = height
self.food = food
self.score = 0
self.snake = collections.deque([(0, 0)])
self.delta = {'U': (-1, 0), 'L': (0, -1), 'R': (0, 1), 'D': (1, 0)}
self.visited = set((0, 0))
<|end_body_0|>
<|body_start_1|>
x, y = ... | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ... | stack_v2_sparse_classes_10k_train_001729 | 1,981 | no_license | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :type height: int :type food: List[List[int]]",
... | 2 | null | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E... | 6fec95b9b4d735727160905e754a698513bfb7d8 | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :... | the_stack_v2_python_sparse | leetcode/queue/design-snake-game.py | jwyx3/practices | train | 2 | |
4c53c4d7c9e361fa992b3742fe9c247df8d9524a | [
"new_x = 0\nold_x = x\nif x < 0:\n return False\nelif x % 10 == x:\n return True\nelse:\n while x > 0:\n rem = x % 10\n new_x = new_x * 10 + rem\n x = x // 10\n if new_x == old_x:\n return True\n else:\n return False",
"if x < 0:\n return False\nelif x % 10 == ... | <|body_start_0|>
new_x = 0
old_x = x
if x < 0:
return False
elif x % 10 == x:
return True
else:
while x > 0:
rem = x % 10
new_x = new_x * 10 + rem
x = x // 10
if new_x == old_x:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome_2(self, x):
""":type x: int :rtype: bool"""
<|body_0|>
def isPalindrome(self, x):
""":type x: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
new_x = 0
old_x = x
if x < 0:
retur... | stack_v2_sparse_classes_10k_train_001730 | 1,267 | no_license | [
{
"docstring": ":type x: int :rtype: bool",
"name": "isPalindrome_2",
"signature": "def isPalindrome_2(self, x)"
},
{
"docstring": ":type x: int :rtype: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005202 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome_2(self, x): :type x: int :rtype: bool
- def isPalindrome(self, x): :type x: int :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome_2(self, x): :type x: int :rtype: bool
- def isPalindrome(self, x): :type x: int :rtype: bool
<|skeleton|>
class Solution:
def isPalindrome_2(self, x):
... | ec48cbde4356208afac226d41752daffe674be2c | <|skeleton|>
class Solution:
def isPalindrome_2(self, x):
""":type x: int :rtype: bool"""
<|body_0|>
def isPalindrome(self, x):
""":type x: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindrome_2(self, x):
""":type x: int :rtype: bool"""
new_x = 0
old_x = x
if x < 0:
return False
elif x % 10 == x:
return True
else:
while x > 0:
rem = x % 10
new_x = new_x * 10... | the_stack_v2_python_sparse | B2BSWE/Primitives/isPalindromeNum.py | librar127/PythonDS | train | 0 | |
de6220be4044b22a681712b18ee242d493a00ff0 | [
"parameters_key = registry_key.GetSubkeyByName('Parameters')\nif not parameters_key:\n return None\nreturn self._GetValueFromKey(parameters_key, 'ServiceDll')",
"service_type = self._GetValueFromKey(registry_key, 'Type')\nstart_type = self._GetValueFromKey(registry_key, 'Start')\nif None in (service_type, star... | <|body_start_0|>
parameters_key = registry_key.GetSubkeyByName('Parameters')
if not parameters_key:
return None
return self._GetValueFromKey(parameters_key, 'ServiceDll')
<|end_body_0|>
<|body_start_1|>
service_type = self._GetValueFromKey(registry_key, 'Type')
start... | Plug-in to format the Services and Drivers keys having Type and Start. | ServicesPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServicesPlugin:
"""Plug-in to format the Services and Drivers keys having Type and Start."""
def _GetServiceDll(self, registry_key):
"""Retrieves the service DLL value. Obtains the service DLL for in the Parameters subkey of a Windows Registry service key. Args: registry_key (dfwinre... | stack_v2_sparse_classes_10k_train_001731 | 4,192 | permissive | [
{
"docstring": "Retrieves the service DLL value. Obtains the service DLL for in the Parameters subkey of a Windows Registry service key. Args: registry_key (dfwinreg.WinRegistryKey): Windows Registry key. Returns: str: path of the service DLL or None.",
"name": "_GetServiceDll",
"signature": "def _GetSe... | 2 | null | Implement the Python class `ServicesPlugin` described below.
Class description:
Plug-in to format the Services and Drivers keys having Type and Start.
Method signatures and docstrings:
- def _GetServiceDll(self, registry_key): Retrieves the service DLL value. Obtains the service DLL for in the Parameters subkey of a ... | Implement the Python class `ServicesPlugin` described below.
Class description:
Plug-in to format the Services and Drivers keys having Type and Start.
Method signatures and docstrings:
- def _GetServiceDll(self, registry_key): Retrieves the service DLL value. Obtains the service DLL for in the Parameters subkey of a ... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class ServicesPlugin:
"""Plug-in to format the Services and Drivers keys having Type and Start."""
def _GetServiceDll(self, registry_key):
"""Retrieves the service DLL value. Obtains the service DLL for in the Parameters subkey of a Windows Registry service key. Args: registry_key (dfwinre... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ServicesPlugin:
"""Plug-in to format the Services and Drivers keys having Type and Start."""
def _GetServiceDll(self, registry_key):
"""Retrieves the service DLL value. Obtains the service DLL for in the Parameters subkey of a Windows Registry service key. Args: registry_key (dfwinreg.WinRegistry... | the_stack_v2_python_sparse | plaso/parsers/winreg_plugins/services.py | log2timeline/plaso | train | 1,506 |
2002eebc1d20a261311cd136ba55595f420039e2 | [
"batch = batch.to(self.device)\nwavs, lens = batch.sig\nfeats = self.modules.compute_features(wavs)\nfeats = self.modules.mean_var_norm(feats, lens)\nembeddings = self.modules.embedding_model(feats)\noutputs = self.modules.classifier(embeddings)\nreturn outputs",
"predictions = self.compute_forward(batch, sb.Stag... | <|body_start_0|>
batch = batch.to(self.device)
wavs, lens = batch.sig
feats = self.modules.compute_features(wavs)
feats = self.modules.mean_var_norm(feats, lens)
embeddings = self.modules.embedding_model(feats)
outputs = self.modules.classifier(embeddings)
return ... | EmoIdBrain | [
"GPL-1.0-or-later",
"LicenseRef-scancode-other-permissive",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmoIdBrain:
def compute_forward(self, batch, stage):
"""Computation pipeline based on a encoder + emotion classifier."""
<|body_0|>
def fit_batch(self, batch):
"""Trains the parameters given a single batch in input"""
<|body_1|>
def compute_objectives(se... | stack_v2_sparse_classes_10k_train_001732 | 12,801 | permissive | [
{
"docstring": "Computation pipeline based on a encoder + emotion classifier.",
"name": "compute_forward",
"signature": "def compute_forward(self, batch, stage)"
},
{
"docstring": "Trains the parameters given a single batch in input",
"name": "fit_batch",
"signature": "def fit_batch(self... | 6 | stack_v2_sparse_classes_30k_train_002680 | Implement the Python class `EmoIdBrain` described below.
Class description:
Implement the EmoIdBrain class.
Method signatures and docstrings:
- def compute_forward(self, batch, stage): Computation pipeline based on a encoder + emotion classifier.
- def fit_batch(self, batch): Trains the parameters given a single batc... | Implement the Python class `EmoIdBrain` described below.
Class description:
Implement the EmoIdBrain class.
Method signatures and docstrings:
- def compute_forward(self, batch, stage): Computation pipeline based on a encoder + emotion classifier.
- def fit_batch(self, batch): Trains the parameters given a single batc... | d4c9a53773f13d5a2843f25bc7f89482936e2f17 | <|skeleton|>
class EmoIdBrain:
def compute_forward(self, batch, stage):
"""Computation pipeline based on a encoder + emotion classifier."""
<|body_0|>
def fit_batch(self, batch):
"""Trains the parameters given a single batch in input"""
<|body_1|>
def compute_objectives(se... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EmoIdBrain:
def compute_forward(self, batch, stage):
"""Computation pipeline based on a encoder + emotion classifier."""
batch = batch.to(self.device)
wavs, lens = batch.sig
feats = self.modules.compute_features(wavs)
feats = self.modules.mean_var_norm(feats, lens)
... | the_stack_v2_python_sparse | recipes/IEMOCAP/emotion_recognition/train.py | zycv/speechbrain | train | 2 | |
23721ffe77c1012c5535614b99606f88b78dbb7d | [
"assert False, logger.error('Joint generator not functional')\nself.config = config\nself.is_sub_model = is_sub_model\nself.step = 0\nself.stage = stage\nself.train = self.stage == 'train'\nself.teacher_forcing = teacher_forcing\nself.word_embedding = word_embedding\nassert self.stage in ['train', 'test', 'val', 'i... | <|body_start_0|>
assert False, logger.error('Joint generator not functional')
self.config = config
self.is_sub_model = is_sub_model
self.step = 0
self.stage = stage
self.train = self.stage == 'train'
self.teacher_forcing = teacher_forcing
self.word_embeddi... | @NOT FUNCTIONAL! @brief: The conditional generator. In the first edition, let's assume the image embedding vector is conditioned to generate the text, and the text vector is conditioned to generate the image (we have more options though) @components: def __init__ def build_models | joint_generator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class joint_generator:
"""@NOT FUNCTIONAL! @brief: The conditional generator. In the first edition, let's assume the image embedding vector is conditioned to generate the text, and the text vector is conditioned to generate the image (we have more options though) @components: def __init__ def build_mod... | stack_v2_sparse_classes_10k_train_001733 | 15,550 | no_license | [
{
"docstring": "@brief: The initialization of the model. we use a config file to store the information of configuration",
"name": "__init__",
"signature": "def __init__(self, config, stage='train', is_sub_model=True, teacher_forcing=True, word_embedding=None)"
},
{
"docstring": "@brief: build th... | 2 | stack_v2_sparse_classes_30k_train_000811 | Implement the Python class `joint_generator` described below.
Class description:
@NOT FUNCTIONAL! @brief: The conditional generator. In the first edition, let's assume the image embedding vector is conditioned to generate the text, and the text vector is conditioned to generate the image (we have more options though) ... | Implement the Python class `joint_generator` described below.
Class description:
@NOT FUNCTIONAL! @brief: The conditional generator. In the first edition, let's assume the image embedding vector is conditioned to generate the text, and the text vector is conditioned to generate the image (we have more options though) ... | 71bf42b89308b56113c12096d2280c02abad9e84 | <|skeleton|>
class joint_generator:
"""@NOT FUNCTIONAL! @brief: The conditional generator. In the first edition, let's assume the image embedding vector is conditioned to generate the text, and the text vector is conditioned to generate the image (we have more options though) @components: def __init__ def build_mod... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class joint_generator:
"""@NOT FUNCTIONAL! @brief: The conditional generator. In the first edition, let's assume the image embedding vector is conditioned to generate the text, and the text vector is conditioned to generate the image (we have more options though) @components: def __init__ def build_models"""
d... | the_stack_v2_python_sparse | model/network.py | WilsonWangTHU/gan_playground | train | 0 |
8cd8d517e5f6b5fce4b6888148192fc295cb9545 | [
"if n == 1 or n == 0 or n == -1:\n return x ** n\nhalf = self.myPow(x, n // 2)\nmod = n % 2\nreturn half * half * x ** mod",
"if x == 0:\n return 0\nif n < 0:\n x, n = (1 / x, -n)\nres = 1\nwhile n:\n if n & 1:\n res *= x\n x *= x\n n >>= 1\nreturn res"
] | <|body_start_0|>
if n == 1 or n == 0 or n == -1:
return x ** n
half = self.myPow(x, n // 2)
mod = n % 2
return half * half * x ** mod
<|end_body_0|>
<|body_start_1|>
if x == 0:
return 0
if n < 0:
x, n = (1 / x, -n)
res = 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def myPow(self, x: float, n: int) -> float:
"""二分递归相乘,不过仍然有大量重复运算 :param x: :param n: 指数;注意考虑 指数为负的情况 :return:"""
<|body_0|>
def myPow1(self, x: float, n: int) -> float:
""":param x: -100 < x < 100 注意分析 x=0 情况 :param n: 注意分析 负指数情况 :return:"""
<|body... | stack_v2_sparse_classes_10k_train_001734 | 1,071 | no_license | [
{
"docstring": "二分递归相乘,不过仍然有大量重复运算 :param x: :param n: 指数;注意考虑 指数为负的情况 :return:",
"name": "myPow",
"signature": "def myPow(self, x: float, n: int) -> float"
},
{
"docstring": ":param x: -100 < x < 100 注意分析 x=0 情况 :param n: 注意分析 负指数情况 :return:",
"name": "myPow1",
"signature": "def myPow1(... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myPow(self, x: float, n: int) -> float: 二分递归相乘,不过仍然有大量重复运算 :param x: :param n: 指数;注意考虑 指数为负的情况 :return:
- def myPow1(self, x: float, n: int) -> float: :param x: -100 < x < 10... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myPow(self, x: float, n: int) -> float: 二分递归相乘,不过仍然有大量重复运算 :param x: :param n: 指数;注意考虑 指数为负的情况 :return:
- def myPow1(self, x: float, n: int) -> float: :param x: -100 < x < 10... | 4ca0ec2ab9510b12b7e8c65af52dee719f099ea6 | <|skeleton|>
class Solution:
def myPow(self, x: float, n: int) -> float:
"""二分递归相乘,不过仍然有大量重复运算 :param x: :param n: 指数;注意考虑 指数为负的情况 :return:"""
<|body_0|>
def myPow1(self, x: float, n: int) -> float:
""":param x: -100 < x < 100 注意分析 x=0 情况 :param n: 注意分析 负指数情况 :return:"""
<|body... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def myPow(self, x: float, n: int) -> float:
"""二分递归相乘,不过仍然有大量重复运算 :param x: :param n: 指数;注意考虑 指数为负的情况 :return:"""
if n == 1 or n == 0 or n == -1:
return x ** n
half = self.myPow(x, n // 2)
mod = n % 2
return half * half * x ** mod
def myPow1(s... | the_stack_v2_python_sparse | offer/16-数值的整数次方.py | JDer-liuodngkai/LeetCode | train | 0 | |
fd5e98edce8e76879e9cb8791e16101cb4081d61 | [
"super(EnglishPunktTokenizer, self).__init__()\nself._sentence_tokenizer = punkt.PunktSentenceTokenizer()\nself._word_tokenizer = punkt.PunktWordTokenizer()",
"if text != '':\n return self._sentence_tokenizer.tokenize(text)\nreturn []",
"tokenized_sentences = []\nfor sentence in sentences:\n tokenized_sen... | <|body_start_0|>
super(EnglishPunktTokenizer, self).__init__()
self._sentence_tokenizer = punkt.PunktSentenceTokenizer()
self._word_tokenizer = punkt.PunktWordTokenizer()
<|end_body_0|>
<|body_start_1|>
if text != '':
return self._sentence_tokenizer.tokenize(text)
re... | Sentence and word tokenizer. Sentence and word tokenizer using the NLTK's C{punkt} module. | EnglishPunktTokenizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnglishPunktTokenizer:
"""Sentence and word tokenizer. Sentence and word tokenizer using the NLTK's C{punkt} module."""
def __init__(self):
"""Constructor."""
<|body_0|>
def tokenizeSentences(self, text):
"""Tokenizes a text into sentences. Args: text: The C{stri... | stack_v2_sparse_classes_10k_train_001735 | 1,670 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Tokenizes a text into sentences. Args: text: The C{string} text to tokenize. Returns: The ordered C{list} of every C{string} sentence of the C{text}.",
"name": "tokenizeSentences",
"si... | 3 | stack_v2_sparse_classes_30k_train_001681 | Implement the Python class `EnglishPunktTokenizer` described below.
Class description:
Sentence and word tokenizer. Sentence and word tokenizer using the NLTK's C{punkt} module.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def tokenizeSentences(self, text): Tokenizes a text into sentences. A... | Implement the Python class `EnglishPunktTokenizer` described below.
Class description:
Sentence and word tokenizer. Sentence and word tokenizer using the NLTK's C{punkt} module.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def tokenizeSentences(self, text): Tokenizes a text into sentences. A... | a66cf98b11260d2b74cd990f36f5dcde192b0346 | <|skeleton|>
class EnglishPunktTokenizer:
"""Sentence and word tokenizer. Sentence and word tokenizer using the NLTK's C{punkt} module."""
def __init__(self):
"""Constructor."""
<|body_0|>
def tokenizeSentences(self, text):
"""Tokenizes a text into sentences. Args: text: The C{stri... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EnglishPunktTokenizer:
"""Sentence and word tokenizer. Sentence and word tokenizer using the NLTK's C{punkt} module."""
def __init__(self):
"""Constructor."""
super(EnglishPunktTokenizer, self).__init__()
self._sentence_tokenizer = punkt.PunktSentenceTokenizer()
self._word... | the_stack_v2_python_sparse | src/keybench/main/nlp_tool/implementation/tokenizer/english_punkt_tokenizer.py | Archer-W/KeyBench | train | 0 |
8eb79998d207f97000902786ea60215a1f5151bd | [
"super().__init__()\nself.tanh = nn.Tanh()\nself.W = nn.Linear(enc_dim, att_dim, bias=False)\nself.V = nn.Linear(dec_dim, att_dim, bias=False)\nself.b = nn.Parameter(torch.Tensor(att_dim).normal_())\nself.v = nn.utils.weight_norm(nn.Linear(att_dim, 1))\nself.v.weight_g = nn.Parameter(torch.Tensor([1 / att_dim]).sqr... | <|body_start_0|>
super().__init__()
self.tanh = nn.Tanh()
self.W = nn.Linear(enc_dim, att_dim, bias=False)
self.V = nn.Linear(dec_dim, att_dim, bias=False)
self.b = nn.Parameter(torch.Tensor(att_dim).normal_())
self.v = nn.utils.weight_norm(nn.Linear(att_dim, 1))
... | Energy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Energy:
def __init__(self, enc_dim: int, dec_dim: int, att_dim: int, init_r: float=-4) -> None:
"""[Modified Bahdahnau attention] from "Online and Linear-Time Attention by Enforcing Monotonic Alignment" (ICML 2017) http://arxiv.org/abs/1704.00784 Used for Monotonic Attention and Chunk At... | stack_v2_sparse_classes_10k_train_001736 | 23,577 | no_license | [
{
"docstring": "[Modified Bahdahnau attention] from \"Online and Linear-Time Attention by Enforcing Monotonic Alignment\" (ICML 2017) http://arxiv.org/abs/1704.00784 Used for Monotonic Attention and Chunk Attention",
"name": "__init__",
"signature": "def __init__(self, enc_dim: int, dec_dim: int, att_di... | 2 | stack_v2_sparse_classes_30k_train_006048 | Implement the Python class `Energy` described below.
Class description:
Implement the Energy class.
Method signatures and docstrings:
- def __init__(self, enc_dim: int, dec_dim: int, att_dim: int, init_r: float=-4) -> None: [Modified Bahdahnau attention] from "Online and Linear-Time Attention by Enforcing Monotonic A... | Implement the Python class `Energy` described below.
Class description:
Implement the Energy class.
Method signatures and docstrings:
- def __init__(self, enc_dim: int, dec_dim: int, att_dim: int, init_r: float=-4) -> None: [Modified Bahdahnau attention] from "Online and Linear-Time Attention by Enforcing Monotonic A... | 9f9a55f8020ac05b7bb84746a62a83950fe833a2 | <|skeleton|>
class Energy:
def __init__(self, enc_dim: int, dec_dim: int, att_dim: int, init_r: float=-4) -> None:
"""[Modified Bahdahnau attention] from "Online and Linear-Time Attention by Enforcing Monotonic Alignment" (ICML 2017) http://arxiv.org/abs/1704.00784 Used for Monotonic Attention and Chunk At... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Energy:
def __init__(self, enc_dim: int, dec_dim: int, att_dim: int, init_r: float=-4) -> None:
"""[Modified Bahdahnau attention] from "Online and Linear-Time Attention by Enforcing Monotonic Alignment" (ICML 2017) http://arxiv.org/abs/1704.00784 Used for Monotonic Attention and Chunk Attention"""
... | the_stack_v2_python_sparse | stt/modules/attention.py | Chung-I/tsm-rnnt | train | 4 | |
a7836d8c1e912b8040e056c52ffc50134e34d83d | [
"selector = _get_selector(loop)\nif evt & self._READ:\n selector.add_reader(socket, lambda *args: f())\nif evt & self._WRITE:\n selector.add_writer(socket, lambda *args: f())",
"selector = _get_selector(loop)\nfor socket in sockets:\n selector.remove_reader(socket)\n selector.remove_writer(socket)"
] | <|body_start_0|>
selector = _get_selector(loop)
if evt & self._READ:
selector.add_reader(socket, lambda *args: f())
if evt & self._WRITE:
selector.add_writer(socket, lambda *args: f())
<|end_body_0|>
<|body_start_1|>
selector = _get_selector(loop)
for soc... | Poller returning asyncio.Future for poll results. | Poller | [
"BSD-3-Clause",
"LGPL-3.0-only",
"LicenseRef-scancode-zeromq-exception-lgpl-3.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Poller:
"""Poller returning asyncio.Future for poll results."""
def _watch_raw_socket(self, loop, socket, evt, f):
"""Schedule callback for a raw socket"""
<|body_0|>
def _unwatch_raw_sockets(self, loop, *sockets):
"""Unschedule callback for a raw socket"""
... | stack_v2_sparse_classes_10k_train_001737 | 6,271 | permissive | [
{
"docstring": "Schedule callback for a raw socket",
"name": "_watch_raw_socket",
"signature": "def _watch_raw_socket(self, loop, socket, evt, f)"
},
{
"docstring": "Unschedule callback for a raw socket",
"name": "_unwatch_raw_sockets",
"signature": "def _unwatch_raw_sockets(self, loop, ... | 2 | stack_v2_sparse_classes_30k_test_000163 | Implement the Python class `Poller` described below.
Class description:
Poller returning asyncio.Future for poll results.
Method signatures and docstrings:
- def _watch_raw_socket(self, loop, socket, evt, f): Schedule callback for a raw socket
- def _unwatch_raw_sockets(self, loop, *sockets): Unschedule callback for ... | Implement the Python class `Poller` described below.
Class description:
Poller returning asyncio.Future for poll results.
Method signatures and docstrings:
- def _watch_raw_socket(self, loop, socket, evt, f): Schedule callback for a raw socket
- def _unwatch_raw_sockets(self, loop, *sockets): Unschedule callback for ... | f5042e35b945aded77b23470ead62d7eacefde92 | <|skeleton|>
class Poller:
"""Poller returning asyncio.Future for poll results."""
def _watch_raw_socket(self, loop, socket, evt, f):
"""Schedule callback for a raw socket"""
<|body_0|>
def _unwatch_raw_sockets(self, loop, *sockets):
"""Unschedule callback for a raw socket"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Poller:
"""Poller returning asyncio.Future for poll results."""
def _watch_raw_socket(self, loop, socket, evt, f):
"""Schedule callback for a raw socket"""
selector = _get_selector(loop)
if evt & self._READ:
selector.add_reader(socket, lambda *args: f())
if evt... | the_stack_v2_python_sparse | contrib/python/pyzmq/py3/zmq/asyncio.py | catboost/catboost | train | 8,012 |
b3dba2e092cc0c1ebbaacd99286be1a6a7cbea57 | [
"self.enterTuangou(self.s_name)\nself.swipe_to_down(1)\nsleep(2)\nself.assertTrue(self.check_icon(self.s_name))",
"self.enterTuangou(self.s_name)\nself.swipe_to_down(1)\nself.enter_fist_goods_datil_page(self.s_name)\ns_goods_title = self.setCollected(self.s_name)\nself.press_back_by_keycode()\nself.press_back()\n... | <|body_start_0|>
self.enterTuangou(self.s_name)
self.swipe_to_down(1)
sleep(2)
self.assertTrue(self.check_icon(self.s_name))
<|end_body_0|>
<|body_start_1|>
self.enterTuangou(self.s_name)
self.swipe_to_down(1)
self.enter_fist_goods_datil_page(self.s_name)
... | TChaoJi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TChaoJi:
def test_goods_icon(self):
"""超级团_团购标签验证"""
<|body_0|>
def test_collect(self):
"""超级团_收藏功能"""
<|body_1|>
def test_customer_service(self):
"""超级团_发送客服消息验证"""
<|body_2|>
def test_separately_buy(self):
"""超级团_去参团_"""
... | stack_v2_sparse_classes_10k_train_001738 | 1,854 | no_license | [
{
"docstring": "超级团_团购标签验证",
"name": "test_goods_icon",
"signature": "def test_goods_icon(self)"
},
{
"docstring": "超级团_收藏功能",
"name": "test_collect",
"signature": "def test_collect(self)"
},
{
"docstring": "超级团_发送客服消息验证",
"name": "test_customer_service",
"signature": "de... | 4 | stack_v2_sparse_classes_30k_train_000428 | Implement the Python class `TChaoJi` described below.
Class description:
Implement the TChaoJi class.
Method signatures and docstrings:
- def test_goods_icon(self): 超级团_团购标签验证
- def test_collect(self): 超级团_收藏功能
- def test_customer_service(self): 超级团_发送客服消息验证
- def test_separately_buy(self): 超级团_去参团_ | Implement the Python class `TChaoJi` described below.
Class description:
Implement the TChaoJi class.
Method signatures and docstrings:
- def test_goods_icon(self): 超级团_团购标签验证
- def test_collect(self): 超级团_收藏功能
- def test_customer_service(self): 超级团_发送客服消息验证
- def test_separately_buy(self): 超级团_去参团_
<|skeleton|>
cla... | b2066139eb0723eff69d971589b283b4b776c84c | <|skeleton|>
class TChaoJi:
def test_goods_icon(self):
"""超级团_团购标签验证"""
<|body_0|>
def test_collect(self):
"""超级团_收藏功能"""
<|body_1|>
def test_customer_service(self):
"""超级团_发送客服消息验证"""
<|body_2|>
def test_separately_buy(self):
"""超级团_去参团_"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TChaoJi:
def test_goods_icon(self):
"""超级团_团购标签验证"""
self.enterTuangou(self.s_name)
self.swipe_to_down(1)
sleep(2)
self.assertTrue(self.check_icon(self.s_name))
def test_collect(self):
"""超级团_收藏功能"""
self.enterTuangou(self.s_name)
self.swipe... | the_stack_v2_python_sparse | TestCase/4_5/TC_tuan_gou/test_chao_ji.py | testerSunshine/auto_md | train | 4 | |
3e74461d17a4ee61e1e574f1a6e50d9bc040c547 | [
"self.token = token\nself.sentence = sentence\nself.event_domain = event_domain\nself.event_type = event_type\nself._allocate_arrays(params.get_int('max_sent_length'), params.get_int('cnn.neighbor_dist'), params.get_int('embedding.none_token_index'), params.get_string('cnn.int_type'), params.get_boolean('cnn.use_bi... | <|body_start_0|>
self.token = token
self.sentence = sentence
self.event_domain = event_domain
self.event_type = event_type
self._allocate_arrays(params.get_int('max_sent_length'), params.get_int('cnn.neighbor_dist'), params.get_int('embedding.none_token_index'), params.get_string... | EventTriggerExample | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventTriggerExample:
def __init__(self, token, sentence, event_domain, params, event_type=None):
"""We are given a token, sentence as context, and event_type (present during training) :type token: text.text_span.Token :type sentence: text.text_span.Sentence :type event_domain: event.even... | stack_v2_sparse_classes_10k_train_001739 | 17,179 | permissive | [
{
"docstring": "We are given a token, sentence as context, and event_type (present during training) :type token: text.text_span.Token :type sentence: text.text_span.Sentence :type event_domain: event.event_domain.EventDomain :type params: common.parameters.Parameters :type event_type: str",
"name": "__init_... | 2 | null | Implement the Python class `EventTriggerExample` described below.
Class description:
Implement the EventTriggerExample class.
Method signatures and docstrings:
- def __init__(self, token, sentence, event_domain, params, event_type=None): We are given a token, sentence as context, and event_type (present during traini... | Implement the Python class `EventTriggerExample` described below.
Class description:
Implement the EventTriggerExample class.
Method signatures and docstrings:
- def __init__(self, token, sentence, event_domain, params, event_type=None): We are given a token, sentence as context, and event_type (present during traini... | 3d5d7f8e17f7e77ecf94a6de58ac5859a03789ce | <|skeleton|>
class EventTriggerExample:
def __init__(self, token, sentence, event_domain, params, event_type=None):
"""We are given a token, sentence as context, and event_type (present during training) :type token: text.text_span.Token :type sentence: text.text_span.Sentence :type event_domain: event.even... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EventTriggerExample:
def __init__(self, token, sentence, event_domain, params, event_type=None):
"""We are given a token, sentence as context, and event_type (present during training) :type token: text.text_span.Token :type sentence: text.text_span.Sentence :type event_domain: event.event_domain.Event... | the_stack_v2_python_sparse | src/python/cyberlingo/event/event_trigger.py | BBN-E/Hume | train | 5 | |
59285e5510e2cefdddc5a6a1d28d19b35b5559c6 | [
"self.entity_description = description\nself._tc_object = tc_object\nself._update_devices = update_devices\nself._attr_name = f'{tc_object.name} {description.name}'",
"self._update_devices()\nsensor_type = self.entity_description.key\nif sensor_type == 'battery':\n self._attr_native_value = self._tc_object.bat... | <|body_start_0|>
self.entity_description = description
self._tc_object = tc_object
self._update_devices = update_devices
self._attr_name = f'{tc_object.name} {description.name}'
<|end_body_0|>
<|body_start_1|>
self._update_devices()
sensor_type = self.entity_description.... | Representation of a ThinkingCleaner Sensor. | ThinkingCleanerSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThinkingCleanerSensor:
"""Representation of a ThinkingCleaner Sensor."""
def __init__(self, tc_object, update_devices, description: SensorEntityDescription) -> None:
"""Initialize the ThinkingCleaner."""
<|body_0|>
def update(self) -> None:
"""Update the sensor."... | stack_v2_sparse_classes_10k_train_001740 | 3,910 | permissive | [
{
"docstring": "Initialize the ThinkingCleaner.",
"name": "__init__",
"signature": "def __init__(self, tc_object, update_devices, description: SensorEntityDescription) -> None"
},
{
"docstring": "Update the sensor.",
"name": "update",
"signature": "def update(self) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_train_001447 | Implement the Python class `ThinkingCleanerSensor` described below.
Class description:
Representation of a ThinkingCleaner Sensor.
Method signatures and docstrings:
- def __init__(self, tc_object, update_devices, description: SensorEntityDescription) -> None: Initialize the ThinkingCleaner.
- def update(self) -> None... | Implement the Python class `ThinkingCleanerSensor` described below.
Class description:
Representation of a ThinkingCleaner Sensor.
Method signatures and docstrings:
- def __init__(self, tc_object, update_devices, description: SensorEntityDescription) -> None: Initialize the ThinkingCleaner.
- def update(self) -> None... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ThinkingCleanerSensor:
"""Representation of a ThinkingCleaner Sensor."""
def __init__(self, tc_object, update_devices, description: SensorEntityDescription) -> None:
"""Initialize the ThinkingCleaner."""
<|body_0|>
def update(self) -> None:
"""Update the sensor."... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ThinkingCleanerSensor:
"""Representation of a ThinkingCleaner Sensor."""
def __init__(self, tc_object, update_devices, description: SensorEntityDescription) -> None:
"""Initialize the ThinkingCleaner."""
self.entity_description = description
self._tc_object = tc_object
sel... | the_stack_v2_python_sparse | homeassistant/components/thinkingcleaner/sensor.py | home-assistant/core | train | 35,501 |
bd292910056a20d98d07e88d59c6246ec78d3ab8 | [
"args = self.parser.parse_args()\ndata = self.build_data(args=args, collection='task')\nreturn data",
"args = self.parse_args(add_task_fields)\nname = args.pop('name')\ntarget = args.pop('target')\ntry:\n task_data_list = submit_task_task(target=target, name=name, options=args)\nexcept Exception as e:\n log... | <|body_start_0|>
args = self.parser.parse_args()
data = self.build_data(args=args, collection='task')
return data
<|end_body_0|>
<|body_start_1|>
args = self.parse_args(add_task_fields)
name = args.pop('name')
target = args.pop('target')
try:
task_dat... | ARLTask | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ARLTask:
def get(self):
"""任务信息查询"""
<|body_0|>
def post(self):
"""任务提交"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
args = self.parser.parse_args()
data = self.build_data(args=args, collection='task')
return data
<|end_body_0|>
... | stack_v2_sparse_classes_10k_train_001741 | 14,992 | no_license | [
{
"docstring": "任务信息查询",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "任务提交",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003231 | Implement the Python class `ARLTask` described below.
Class description:
Implement the ARLTask class.
Method signatures and docstrings:
- def get(self): 任务信息查询
- def post(self): 任务提交 | Implement the Python class `ARLTask` described below.
Class description:
Implement the ARLTask class.
Method signatures and docstrings:
- def get(self): 任务信息查询
- def post(self): 任务提交
<|skeleton|>
class ARLTask:
def get(self):
"""任务信息查询"""
<|body_0|>
def post(self):
"""任务提交"""
... | 5ca64806252b9e7e6d2b31a6bfaeecbfdc4baf06 | <|skeleton|>
class ARLTask:
def get(self):
"""任务信息查询"""
<|body_0|>
def post(self):
"""任务提交"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ARLTask:
def get(self):
"""任务信息查询"""
args = self.parser.parse_args()
data = self.build_data(args=args, collection='task')
return data
def post(self):
"""任务提交"""
args = self.parse_args(add_task_fields)
name = args.pop('name')
target = args.po... | the_stack_v2_python_sparse | app/routes/task.py | QmF0c3UK/ARL | train | 0 | |
68a410420663d7efb491778e748b31fdac7ce3fa | [
"filters = {}\nif hasattr(request, 'GET'):\n filters = request.GET.copy()\nfilters.update(kwargs)\nif 'community' in filters:\n try:\n community = Community.objects.get(uuid=uuid_from_uri(filters['community']))\n im = community.image_set.filter(is_active=True)\n wb = community.wordbox_set... | <|body_start_0|>
filters = {}
if hasattr(request, 'GET'):
filters = request.GET.copy()
filters.update(kwargs)
if 'community' in filters:
try:
community = Community.objects.get(uuid=uuid_from_uri(filters['community']))
im = community... | MediaResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MediaResource:
def obj_get_list(self, request=None, **kwargs):
"""A ORM-specific implementation of ``obj_get_list``. Takes an optional ``request`` object, whose ``GET`` dictionary can be used to narrow the query."""
<|body_0|>
def full_dehydrate(self, bundle):
"""Giv... | stack_v2_sparse_classes_10k_train_001742 | 30,895 | no_license | [
{
"docstring": "A ORM-specific implementation of ``obj_get_list``. Takes an optional ``request`` object, whose ``GET`` dictionary can be used to narrow the query.",
"name": "obj_get_list",
"signature": "def obj_get_list(self, request=None, **kwargs)"
},
{
"docstring": "Given a bundle with an obj... | 2 | stack_v2_sparse_classes_30k_train_006695 | Implement the Python class `MediaResource` described below.
Class description:
Implement the MediaResource class.
Method signatures and docstrings:
- def obj_get_list(self, request=None, **kwargs): A ORM-specific implementation of ``obj_get_list``. Takes an optional ``request`` object, whose ``GET`` dictionary can be... | Implement the Python class `MediaResource` described below.
Class description:
Implement the MediaResource class.
Method signatures and docstrings:
- def obj_get_list(self, request=None, **kwargs): A ORM-specific implementation of ``obj_get_list``. Takes an optional ``request`` object, whose ``GET`` dictionary can be... | 698e027b7f6f4db5c2e9b9a899ba74f4ad4daf8e | <|skeleton|>
class MediaResource:
def obj_get_list(self, request=None, **kwargs):
"""A ORM-specific implementation of ``obj_get_list``. Takes an optional ``request`` object, whose ``GET`` dictionary can be used to narrow the query."""
<|body_0|>
def full_dehydrate(self, bundle):
"""Giv... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MediaResource:
def obj_get_list(self, request=None, **kwargs):
"""A ORM-specific implementation of ``obj_get_list``. Takes an optional ``request`` object, whose ``GET`` dictionary can be used to narrow the query."""
filters = {}
if hasattr(request, 'GET'):
filters = request... | the_stack_v2_python_sparse | back-end/website/api/v1/media_resources.py | dchang00/keekaa-back-end | train | 0 | |
fdf8a45b3f361f4f1b0e262ccea0ee3a712a9582 | [
"headers = headers\npostdata = params\nresponse = requests.get(url, postdata, headers=headers, timeout=5)\ntry:\n if response.status_code == 200:\n return response.json()\n else:\n print(response.status_code)\n return\nexcept BaseException as e:\n print('httpGet failed, detail is:%s,%s... | <|body_start_0|>
headers = headers
postdata = params
response = requests.get(url, postdata, headers=headers, timeout=5)
try:
if response.status_code == 200:
return response.json()
else:
print(response.status_code)
re... | http通信器 | HttpCommunicator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpCommunicator:
"""http通信器"""
def http_get(self, url, params, headers):
"""http通信器get请求方法 :param url: 请求接口地址 字符串类型 例如:'https://api.huobi.pro/market/history/kline' :param params: 请求参数 字典类型 例如:{'symbol': 'btcusdt', 'period': '1min', 'size': 150} :param headers: 请求头信息 字典类型 例如:{'Conten... | stack_v2_sparse_classes_10k_train_001743 | 2,864 | no_license | [
{
"docstring": "http通信器get请求方法 :param url: 请求接口地址 字符串类型 例如:'https://api.huobi.pro/market/history/kline' :param params: 请求参数 字典类型 例如:{'symbol': 'btcusdt', 'period': '1min', 'size': 150} :param headers: 请求头信息 字典类型 例如:{'Content-type': 'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1;... | 2 | stack_v2_sparse_classes_30k_train_004250 | Implement the Python class `HttpCommunicator` described below.
Class description:
http通信器
Method signatures and docstrings:
- def http_get(self, url, params, headers): http通信器get请求方法 :param url: 请求接口地址 字符串类型 例如:'https://api.huobi.pro/market/history/kline' :param params: 请求参数 字典类型 例如:{'symbol': 'btcusdt', 'period': '1... | Implement the Python class `HttpCommunicator` described below.
Class description:
http通信器
Method signatures and docstrings:
- def http_get(self, url, params, headers): http通信器get请求方法 :param url: 请求接口地址 字符串类型 例如:'https://api.huobi.pro/market/history/kline' :param params: 请求参数 字典类型 例如:{'symbol': 'btcusdt', 'period': '1... | 1bc744a6d331b4b733f6b6658b8310eb0c30524e | <|skeleton|>
class HttpCommunicator:
"""http通信器"""
def http_get(self, url, params, headers):
"""http通信器get请求方法 :param url: 请求接口地址 字符串类型 例如:'https://api.huobi.pro/market/history/kline' :param params: 请求参数 字典类型 例如:{'symbol': 'btcusdt', 'period': '1min', 'size': 150} :param headers: 请求头信息 字典类型 例如:{'Conten... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HttpCommunicator:
"""http通信器"""
def http_get(self, url, params, headers):
"""http通信器get请求方法 :param url: 请求接口地址 字符串类型 例如:'https://api.huobi.pro/market/history/kline' :param params: 请求参数 字典类型 例如:{'symbol': 'btcusdt', 'period': '1min', 'size': 150} :param headers: 请求头信息 字典类型 例如:{'Content-type': 'app... | the_stack_v2_python_sparse | investment/api/communicators.py | cliicy/vtrade | train | 0 |
99a2270d59587fcadbf077e9d9ffb83da95939d9 | [
"super().__init__()\nself.l_length = l_length\nself.min_value = min_value\nself.max_value = max_value\nself.distinct_elements = distinct_elements\nself.worst_case = worst_case\nself._construct()",
"new_element = random.randint(a=self.min_value, b=self.max_value)\nwhile new_element in already_used:\n new_elemen... | <|body_start_0|>
super().__init__()
self.l_length = l_length
self.min_value = min_value
self.max_value = max_value
self.distinct_elements = distinct_elements
self.worst_case = worst_case
self._construct()
<|end_body_0|>
<|body_start_1|>
new_element = rand... | InputList | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InputList:
def __init__(self, l_length: int=100, min_value: int=0, max_value: int=10000, distinct_elements: bool=True, worst_case: bool=False):
"""Object of input list for algorithms Parameters ---------- l_length (int): Length of the input list min_value (int): Minimal value of the elem... | stack_v2_sparse_classes_10k_train_001744 | 3,885 | permissive | [
{
"docstring": "Object of input list for algorithms Parameters ---------- l_length (int): Length of the input list min_value (int): Minimal value of the elements of the list max_value (int): Maximal value of the elements of the list distinct_elements (bool): distinct elements in the list worst_case (bool): in t... | 3 | stack_v2_sparse_classes_30k_train_000075 | Implement the Python class `InputList` described below.
Class description:
Implement the InputList class.
Method signatures and docstrings:
- def __init__(self, l_length: int=100, min_value: int=0, max_value: int=10000, distinct_elements: bool=True, worst_case: bool=False): Object of input list for algorithms Paramet... | Implement the Python class `InputList` described below.
Class description:
Implement the InputList class.
Method signatures and docstrings:
- def __init__(self, l_length: int=100, min_value: int=0, max_value: int=10000, distinct_elements: bool=True, worst_case: bool=False): Object of input list for algorithms Paramet... | 20d8df6172906337f81583dabb841d66b8f31857 | <|skeleton|>
class InputList:
def __init__(self, l_length: int=100, min_value: int=0, max_value: int=10000, distinct_elements: bool=True, worst_case: bool=False):
"""Object of input list for algorithms Parameters ---------- l_length (int): Length of the input list min_value (int): Minimal value of the elem... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InputList:
def __init__(self, l_length: int=100, min_value: int=0, max_value: int=10000, distinct_elements: bool=True, worst_case: bool=False):
"""Object of input list for algorithms Parameters ---------- l_length (int): Length of the input list min_value (int): Minimal value of the elements of the li... | the_stack_v2_python_sparse | new_algs/Sequence+algorithms/Selection+algorithm/inputs.py | coolsnake/JupyterNotebook | train | 0 | |
6640f260e798560bc00fd29d4fe7c8c85ec54676 | [
"if data is None:\n if lambtha <= 0:\n raise ValueError('lambtha must be a positive value')\n else:\n self.lambtha = float(lambtha)\nelse:\n if type(data) is not list:\n raise TypeError('data must be a list')\n if len(data) < 2:\n raise ValueError('data must contain multiple ... | <|body_start_0|>
if data is None:
if lambtha <= 0:
raise ValueError('lambtha must be a positive value')
else:
self.lambtha = float(lambtha)
else:
if type(data) is not list:
raise TypeError('data must be a list')
... | Represents an exponential distribution | Exponential | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Exponential:
"""Represents an exponential distribution"""
def __init__(self, data=None, lambtha=1.0):
"""Class constructor - data is a list of the data to be used to estimate the distribution - lambtha is the expected number of occurences in a given time frame"""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_001745 | 1,434 | no_license | [
{
"docstring": "Class constructor - data is a list of the data to be used to estimate the distribution - lambtha is the expected number of occurences in a given time frame",
"name": "__init__",
"signature": "def __init__(self, data=None, lambtha=1.0)"
},
{
"docstring": "Calculates the value of t... | 3 | stack_v2_sparse_classes_30k_train_000743 | Implement the Python class `Exponential` described below.
Class description:
Represents an exponential distribution
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): Class constructor - data is a list of the data to be used to estimate the distribution - lambtha is the expected number of... | Implement the Python class `Exponential` described below.
Class description:
Represents an exponential distribution
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): Class constructor - data is a list of the data to be used to estimate the distribution - lambtha is the expected number of... | 161e33b23d398d7d01ad0d7740b78dda3f27e787 | <|skeleton|>
class Exponential:
"""Represents an exponential distribution"""
def __init__(self, data=None, lambtha=1.0):
"""Class constructor - data is a list of the data to be used to estimate the distribution - lambtha is the expected number of occurences in a given time frame"""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Exponential:
"""Represents an exponential distribution"""
def __init__(self, data=None, lambtha=1.0):
"""Class constructor - data is a list of the data to be used to estimate the distribution - lambtha is the expected number of occurences in a given time frame"""
if data is None:
... | the_stack_v2_python_sparse | math/0x03-probability/exponential.py | felipeserna/holbertonschool-machine_learning | train | 0 |
c3b402ab320a620a5e212fab6370f331aaf11275 | [
"m, n, p = (len(s1), len(s2), len(s3))\nif m + n != p:\n return False\ndp = [[False for j in range(n + 1)] for i in range(m + 1)]\ndp[0][0] = True\nfor j in range(1, n + 1):\n dp[0][j] = dp[0][j - 1] and s3[j - 1] == s2[j - 1]\nfor i in range(1, m + 1):\n dp[i][0] = dp[i - 1][0] and s3[i - 1] == s1[i - 1]\... | <|body_start_0|>
m, n, p = (len(s1), len(s2), len(s3))
if m + n != p:
return False
dp = [[False for j in range(n + 1)] for i in range(m + 1)]
dp[0][0] = True
for j in range(1, n + 1):
dp[0][j] = dp[0][j - 1] and s3[j - 1] == s2[j - 1]
for i in rang... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isInterleave(self, s1, s2, s3):
""":type s1: str :type s2: str :type s3: str :rtype: bool"""
<|body_0|>
def isInterleave2(self, s1, s2, s3):
""":type s1: str :type s2: str :type s3: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_10k_train_001746 | 3,558 | no_license | [
{
"docstring": ":type s1: str :type s2: str :type s3: str :rtype: bool",
"name": "isInterleave",
"signature": "def isInterleave(self, s1, s2, s3)"
},
{
"docstring": ":type s1: str :type s2: str :type s3: str :rtype: bool",
"name": "isInterleave2",
"signature": "def isInterleave2(self, s1... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isInterleave(self, s1, s2, s3): :type s1: str :type s2: str :type s3: str :rtype: bool
- def isInterleave2(self, s1, s2, s3): :type s1: str :type s2: str :type s3: str :rtype... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isInterleave(self, s1, s2, s3): :type s1: str :type s2: str :type s3: str :rtype: bool
- def isInterleave2(self, s1, s2, s3): :type s1: str :type s2: str :type s3: str :rtype... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def isInterleave(self, s1, s2, s3):
""":type s1: str :type s2: str :type s3: str :rtype: bool"""
<|body_0|>
def isInterleave2(self, s1, s2, s3):
""":type s1: str :type s2: str :type s3: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isInterleave(self, s1, s2, s3):
""":type s1: str :type s2: str :type s3: str :rtype: bool"""
m, n, p = (len(s1), len(s2), len(s3))
if m + n != p:
return False
dp = [[False for j in range(n + 1)] for i in range(m + 1)]
dp[0][0] = True
fo... | the_stack_v2_python_sparse | code97InterleavingString.py | cybelewang/leetcode-python | train | 0 | |
189aee25ee4d4969761b4e74750b80f6f3901232 | [
"def visit(s1, s2):\n n = len(s1)\n m = len(s2)\n if n != m:\n return False\n if s1 == s2:\n return True\n if sorted(s1) != sorted(s2):\n return False\n if n < 4:\n return True\n for i in range(1, n):\n if visit(s1[:i], s2[:i]) and visit(s1[i:], s2[i:]) or (vi... | <|body_start_0|>
def visit(s1, s2):
n = len(s1)
m = len(s2)
if n != m:
return False
if s1 == s2:
return True
if sorted(s1) != sorted(s2):
return False
if n < 4:
return True
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isScramble(self, s1: str, s2: str) -> bool:
"""Simply testing that both strings contain the same strings does not work: Counter example: "abcde" and "caebd". "ab" is in the inverted order "ba" but separated by "e" which is before "d" => There are two crossed inversions and ... | stack_v2_sparse_classes_10k_train_001747 | 2,808 | no_license | [
{
"docstring": "Simply testing that both strings contain the same strings does not work: Counter example: \"abcde\" and \"caebd\". \"ab\" is in the inverted order \"ba\" but separated by \"e\" which is before \"d\" => There are two crossed inversions and this is not valid (inversions cut the space) Algorithm 1 ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isScramble(self, s1: str, s2: str) -> bool: Simply testing that both strings contain the same strings does not work: Counter example: "abcde" and "caebd". "ab" is in the inve... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isScramble(self, s1: str, s2: str) -> bool: Simply testing that both strings contain the same strings does not work: Counter example: "abcde" and "caebd". "ab" is in the inve... | 3ffcfee5cedf421d5de6d0dec4ba53b0eecbbff8 | <|skeleton|>
class Solution:
def isScramble(self, s1: str, s2: str) -> bool:
"""Simply testing that both strings contain the same strings does not work: Counter example: "abcde" and "caebd". "ab" is in the inverted order "ba" but separated by "e" which is before "d" => There are two crossed inversions and ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isScramble(self, s1: str, s2: str) -> bool:
"""Simply testing that both strings contain the same strings does not work: Counter example: "abcde" and "caebd". "ab" is in the inverted order "ba" but separated by "e" which is before "d" => There are two crossed inversions and this is not va... | the_stack_v2_python_sparse | backtrack/ScrambleStrings.py | QuentinDuval/PythonExperiments | train | 3 | |
405a13e4ad05b1b056f040b468fc2c955e395d52 | [
"super(OidcAuthorizationCode, self).__init__(auth_url=auth_url, identity_provider=identity_provider, protocol=protocol, client_id=client_id, client_secret=client_secret, access_token_endpoint=access_token_endpoint, grant_type=grant_type, access_token_type=access_token_type)\nself.redirect_uri = redirect_uri\nself.c... | <|body_start_0|>
super(OidcAuthorizationCode, self).__init__(auth_url=auth_url, identity_provider=identity_provider, protocol=protocol, client_id=client_id, client_secret=client_secret, access_token_endpoint=access_token_endpoint, grant_type=grant_type, access_token_type=access_token_type)
self.redirect... | Implementation for OpenID Connect Authorization Code. | OidcAuthorizationCode | [
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OidcAuthorizationCode:
"""Implementation for OpenID Connect Authorization Code."""
def __init__(self, auth_url, identity_provider, protocol, client_id, client_secret, access_token_endpoint, grant_type='authorization_code', access_token_type='access_token', redirect_uri=None, code=None):
... | stack_v2_sparse_classes_10k_train_001748 | 11,519 | permissive | [
{
"docstring": "The OpenID Authorization Code plugin expects the following. :param redirect_uri: OpenID Connect Client Redirect URL :type redirect_uri: string :param code: OAuth 2.0 Authorization Code :type code: string",
"name": "__init__",
"signature": "def __init__(self, auth_url, identity_provider, ... | 2 | stack_v2_sparse_classes_30k_train_005647 | Implement the Python class `OidcAuthorizationCode` described below.
Class description:
Implementation for OpenID Connect Authorization Code.
Method signatures and docstrings:
- def __init__(self, auth_url, identity_provider, protocol, client_id, client_secret, access_token_endpoint, grant_type='authorization_code', a... | Implement the Python class `OidcAuthorizationCode` described below.
Class description:
Implementation for OpenID Connect Authorization Code.
Method signatures and docstrings:
- def __init__(self, auth_url, identity_provider, protocol, client_id, client_secret, access_token_endpoint, grant_type='authorization_code', a... | 37b99242ac9810a01ab969d3d3874fa07b8fcee3 | <|skeleton|>
class OidcAuthorizationCode:
"""Implementation for OpenID Connect Authorization Code."""
def __init__(self, auth_url, identity_provider, protocol, client_id, client_secret, access_token_endpoint, grant_type='authorization_code', access_token_type='access_token', redirect_uri=None, code=None):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OidcAuthorizationCode:
"""Implementation for OpenID Connect Authorization Code."""
def __init__(self, auth_url, identity_provider, protocol, client_id, client_secret, access_token_endpoint, grant_type='authorization_code', access_token_type='access_token', redirect_uri=None, code=None):
"""The Op... | the_stack_v2_python_sparse | python_scripts/lib/keystoneauth1-2.7.0/build/lib/keystoneauth1/identity/v3/oidc.py | rkaggrawal/PythonScripts | train | 0 |
2bc64af81aca855540ffd89a0cbec8f5befad1db | [
"self.w, self.n = (w, len(w))\nfor i in range(1, self.n):\n self.w[i] += self.w[i - 1]",
"i, j, r = (0, self.n - 1, random.randint(1, self.w[-1]))\nwhile i <= j:\n m = (i + j) // 2\n if r == self.w[m]:\n return m\n elif r < self.w[m]:\n j = m - 1\n else:\n i = m + 1\nreturn i"
... | <|body_start_0|>
self.w, self.n = (w, len(w))
for i in range(1, self.n):
self.w[i] += self.w[i - 1]
<|end_body_0|>
<|body_start_1|>
i, j, r = (0, self.n - 1, random.randint(1, self.w[-1]))
while i <= j:
m = (i + j) // 2
if r == self.w[m]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.w, self.n = (w, len(w))
for i in range(1, self.n):
self.w[i] += self.w[... | stack_v2_sparse_classes_10k_train_001749 | 695 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|... | 12f62a218e827e6be2578b206dee9ce256da8d3d | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, w):
""":type w: List[int]"""
self.w, self.n = (w, len(w))
for i in range(1, self.n):
self.w[i] += self.w[i - 1]
def pickIndex(self):
""":rtype: int"""
i, j, r = (0, self.n - 1, random.randint(1, self.w[-1]))
while i ... | the_stack_v2_python_sparse | Python3/0528_Random_Pick_With_Weight.py | kiranani/playground | train | 0 | |
b5e866617391bcc0108a073895f42f5cb6ef2f8b | [
"Frame.__init__(self, master)\nself.grid()\nself.create_widgets()",
"self.button1 = Button(self, text='This is the first button')\nself.button1.grid()\nself.button2 = Button(self)\nself.button2.grid()\nself.button2.configure(text='This is the second button')\nself.button3 = Button(self)\nself.button3.grid()\nself... | <|body_start_0|>
Frame.__init__(self, master)
self.grid()
self.create_widgets()
<|end_body_0|>
<|body_start_1|>
self.button1 = Button(self, text='This is the first button')
self.button1.grid()
self.button2 = Button(self)
self.button2.grid()
self.button2.c... | A GUI application with three buttons. | Application | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""A GUI application with three buttons."""
def __init__(self, master):
"""Initialize the Frame"""
<|body_0|>
def create_widgets(self):
"""create 3 buttons"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Frame.__init__(self, master)... | stack_v2_sparse_classes_10k_train_001750 | 828 | no_license | [
{
"docstring": "Initialize the Frame",
"name": "__init__",
"signature": "def __init__(self, master)"
},
{
"docstring": "create 3 buttons",
"name": "create_widgets",
"signature": "def create_widgets(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003202 | Implement the Python class `Application` described below.
Class description:
A GUI application with three buttons.
Method signatures and docstrings:
- def __init__(self, master): Initialize the Frame
- def create_widgets(self): create 3 buttons | Implement the Python class `Application` described below.
Class description:
A GUI application with three buttons.
Method signatures and docstrings:
- def __init__(self, master): Initialize the Frame
- def create_widgets(self): create 3 buttons
<|skeleton|>
class Application:
"""A GUI application with three butt... | b737076a68246f71f3dffe86f1805e5682d4481f | <|skeleton|>
class Application:
"""A GUI application with three buttons."""
def __init__(self, master):
"""Initialize the Frame"""
<|body_0|>
def create_widgets(self):
"""create 3 buttons"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Application:
"""A GUI application with three buttons."""
def __init__(self, master):
"""Initialize the Frame"""
Frame.__init__(self, master)
self.grid()
self.create_widgets()
def create_widgets(self):
"""create 3 buttons"""
self.button1 = Button(self, ... | the_stack_v2_python_sparse | three_buttons.py | tannce/IntroLab2015 | train | 0 |
484d834f1066b5fbf67d373aa2266dc9afe32dcc | [
"self.name = name\nself.filepath = path\nself.numparam = numparam\nself.pre_exec_callback = pre_exec_callback\nself.post_exec_callback = post_exec_callback\nself.cwd = cwd\nif sys.version_info[0] == 2 and sys.platform == 'win32':\n self.filepath = self.filepath.encode(sys.getfilesystemencoding())",
"if len(arg... | <|body_start_0|>
self.name = name
self.filepath = path
self.numparam = numparam
self.pre_exec_callback = pre_exec_callback
self.post_exec_callback = post_exec_callback
self.cwd = cwd
if sys.version_info[0] == 2 and sys.platform == 'win32':
self.filepat... | Hook by executable file Implements standard githooks(5) [0]: [0] http://www.kernel.org/pub/software/scm/git/docs/githooks.html | ShellHook | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShellHook:
"""Hook by executable file Implements standard githooks(5) [0]: [0] http://www.kernel.org/pub/software/scm/git/docs/githooks.html"""
def __init__(self, name, path, numparam, pre_exec_callback=None, post_exec_callback=None, cwd=None):
"""Setup shell hook definition :param n... | stack_v2_sparse_classes_10k_train_001751 | 5,353 | permissive | [
{
"docstring": "Setup shell hook definition :param name: name of hook for error messages :param path: absolute path to executable file :param numparam: number of requirements parameters :param pre_exec_callback: closure for setup before execution Defaults to None. Takes in the variable argument list from the ex... | 2 | null | Implement the Python class `ShellHook` described below.
Class description:
Hook by executable file Implements standard githooks(5) [0]: [0] http://www.kernel.org/pub/software/scm/git/docs/githooks.html
Method signatures and docstrings:
- def __init__(self, name, path, numparam, pre_exec_callback=None, post_exec_callb... | Implement the Python class `ShellHook` described below.
Class description:
Hook by executable file Implements standard githooks(5) [0]: [0] http://www.kernel.org/pub/software/scm/git/docs/githooks.html
Method signatures and docstrings:
- def __init__(self, name, path, numparam, pre_exec_callback=None, post_exec_callb... | d59c99dcdcd280d7eec36a693dd80f8c8c831ea2 | <|skeleton|>
class ShellHook:
"""Hook by executable file Implements standard githooks(5) [0]: [0] http://www.kernel.org/pub/software/scm/git/docs/githooks.html"""
def __init__(self, name, path, numparam, pre_exec_callback=None, post_exec_callback=None, cwd=None):
"""Setup shell hook definition :param n... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ShellHook:
"""Hook by executable file Implements standard githooks(5) [0]: [0] http://www.kernel.org/pub/software/scm/git/docs/githooks.html"""
def __init__(self, name, path, numparam, pre_exec_callback=None, post_exec_callback=None, cwd=None):
"""Setup shell hook definition :param name: name of ... | the_stack_v2_python_sparse | modules/dbnd/src/dbnd/_vendor/dulwich/hooks.py | databand-ai/dbnd | train | 257 |
9c9b7fd6797f4b3c2983da347ecf42400b01ef90 | [
"super().__init__()\nself.beta = beta\nself.threshold_input = threshold_input\nself.threshold_target = threshold_target\nself.reduce_fn = reduce_fn\nself.recall = Recall(threshold_input=None, threshold_target=None, dim=dim, reduce_fn=None)\nself.precision = Precision(threshold_input=None, threshold_target=None, dim... | <|body_start_0|>
super().__init__()
self.beta = beta
self.threshold_input = threshold_input
self.threshold_target = threshold_target
self.reduce_fn = reduce_fn
self.recall = Recall(threshold_input=None, threshold_target=None, dim=dim, reduce_fn=None)
self.precisio... | FScore | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FScore:
def __init__(self, threshold_input: Optional[float]=0.5, threshold_target: Optional[float]=0.5, beta: float=1.0, dim: Optional[int]=-1, reduce_fn: Optional[Callable]=torch.mean):
"""FScore metric. (micro). >>> 'FScore = 2 * precision * recall / (recall + precision)' :param thresh... | stack_v2_sparse_classes_10k_train_001752 | 2,150 | permissive | [
{
"docstring": "FScore metric. (micro). >>> 'FScore = 2 * precision * recall / (recall + precision)' :param threshold_input: The threshold value for binarize input vectors. (default: 0.5) :param threshold_target: The threshold value for binarize target vectors. (default: 0.5) :param beta: The beta fscore parame... | 2 | stack_v2_sparse_classes_30k_train_006485 | Implement the Python class `FScore` described below.
Class description:
Implement the FScore class.
Method signatures and docstrings:
- def __init__(self, threshold_input: Optional[float]=0.5, threshold_target: Optional[float]=0.5, beta: float=1.0, dim: Optional[int]=-1, reduce_fn: Optional[Callable]=torch.mean): FSc... | Implement the Python class `FScore` described below.
Class description:
Implement the FScore class.
Method signatures and docstrings:
- def __init__(self, threshold_input: Optional[float]=0.5, threshold_target: Optional[float]=0.5, beta: float=1.0, dim: Optional[int]=-1, reduce_fn: Optional[Callable]=torch.mean): FSc... | 91aa907a3f820e53902578c3d0110fe9a01c88e7 | <|skeleton|>
class FScore:
def __init__(self, threshold_input: Optional[float]=0.5, threshold_target: Optional[float]=0.5, beta: float=1.0, dim: Optional[int]=-1, reduce_fn: Optional[Callable]=torch.mean):
"""FScore metric. (micro). >>> 'FScore = 2 * precision * recall / (recall + precision)' :param thresh... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FScore:
def __init__(self, threshold_input: Optional[float]=0.5, threshold_target: Optional[float]=0.5, beta: float=1.0, dim: Optional[int]=-1, reduce_fn: Optional[Callable]=torch.mean):
"""FScore metric. (micro). >>> 'FScore = 2 * precision * recall / (recall + precision)' :param threshold_input: The... | the_stack_v2_python_sparse | mlu/metrics/classification/fscore.py | Labbeti/MLU | train | 2 | |
90dc6be698ff696618077f385a3f3ab30313a263 | [
"super(GetConnTests, self).setUp()\nconn = get_conn(verify=False)\nindex_name = settings.ELASTICSEARCH_INDEX\nconn.indices.delete(index_name)\nfrom search import indexing_api\nindexing_api._CONN = None\nindexing_api._CONN_VERIFIED = False",
"with self.assertRaises(ReindexException) as ex:\n get_conn()\nassert ... | <|body_start_0|>
super(GetConnTests, self).setUp()
conn = get_conn(verify=False)
index_name = settings.ELASTICSEARCH_INDEX
conn.indices.delete(index_name)
from search import indexing_api
indexing_api._CONN = None
indexing_api._CONN_VERIFIED = False
<|end_body_0|>
... | Tests for get_conn | GetConnTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetConnTests:
"""Tests for get_conn"""
def setUp(self):
"""Start without any index"""
<|body_0|>
def test_no_index(self):
"""Test that an error is raised if we don't have an index"""
<|body_1|>
def test_no_mapping(self):
"""Test that error is... | stack_v2_sparse_classes_10k_train_001753 | 14,428 | no_license | [
{
"docstring": "Start without any index",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that an error is raised if we don't have an index",
"name": "test_no_index",
"signature": "def test_no_index(self)"
},
{
"docstring": "Test that error is raised if we... | 3 | stack_v2_sparse_classes_30k_train_001256 | Implement the Python class `GetConnTests` described below.
Class description:
Tests for get_conn
Method signatures and docstrings:
- def setUp(self): Start without any index
- def test_no_index(self): Test that an error is raised if we don't have an index
- def test_no_mapping(self): Test that error is raised if we d... | Implement the Python class `GetConnTests` described below.
Class description:
Tests for get_conn
Method signatures and docstrings:
- def setUp(self): Start without any index
- def test_no_index(self): Test that an error is raised if we don't have an index
- def test_no_mapping(self): Test that error is raised if we d... | 3c166bc52dfe8d7aa04f922134f4f6deeff49eb6 | <|skeleton|>
class GetConnTests:
"""Tests for get_conn"""
def setUp(self):
"""Start without any index"""
<|body_0|>
def test_no_index(self):
"""Test that an error is raised if we don't have an index"""
<|body_1|>
def test_no_mapping(self):
"""Test that error is... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GetConnTests:
"""Tests for get_conn"""
def setUp(self):
"""Start without any index"""
super(GetConnTests, self).setUp()
conn = get_conn(verify=False)
index_name = settings.ELASTICSEARCH_INDEX
conn.indices.delete(index_name)
from search import indexing_api
... | the_stack_v2_python_sparse | search/indexing_api_test.py | avontd2868/micromasters | train | 0 |
7f91ea3c98907597d5448f682966786f1d91b46c | [
"super().__init__(cookie)\nsymbols, count = self._parse_cookie()\nself._symbols = symbols\nself._count = count",
"symbols = re.split('([=:&])', self._value)\nlast = (len(symbols) - 3) // 4\ncount = last + 1\nreturn (symbols, count)",
"replacement = copy(self._symbols)\ncurrent = index * 4 + 2\nreplacement[curre... | <|body_start_0|>
super().__init__(cookie)
symbols, count = self._parse_cookie()
self._symbols = symbols
self._count = count
<|end_body_0|>
<|body_start_1|>
symbols = re.split('([=:&])', self._value)
last = (len(symbols) - 3) // 4
count = last + 1
return (... | This is for complex cookie. They are cookie strings that contain list of key/value pairs delimited by &, :, and =. String are decomposed into key/value pairs. Values can be replaced with payloads within a re-created cookie string. | ComplexCookie | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComplexCookie:
"""This is for complex cookie. They are cookie strings that contain list of key/value pairs delimited by &, :, and =. String are decomposed into key/value pairs. Values can be replaced with payloads within a re-created cookie string."""
def __init__(self, cookie):
"""S... | stack_v2_sparse_classes_10k_train_001754 | 3,236 | permissive | [
{
"docstring": "Sets the string, parses the cookie into tokens, and sets the value count.",
"name": "__init__",
"signature": "def __init__(self, cookie)"
},
{
"docstring": "Parse the cookie into a set of tokens to specify key/value pairs and delimiters. Cookie strings are decomposed by =, then :... | 4 | stack_v2_sparse_classes_30k_train_001788 | Implement the Python class `ComplexCookie` described below.
Class description:
This is for complex cookie. They are cookie strings that contain list of key/value pairs delimited by &, :, and =. String are decomposed into key/value pairs. Values can be replaced with payloads within a re-created cookie string.
Method s... | Implement the Python class `ComplexCookie` described below.
Class description:
This is for complex cookie. They are cookie strings that contain list of key/value pairs delimited by &, :, and =. String are decomposed into key/value pairs. Values can be replaced with payloads within a re-created cookie string.
Method s... | 4483b301034a096b716646a470a6642b3df8ce61 | <|skeleton|>
class ComplexCookie:
"""This is for complex cookie. They are cookie strings that contain list of key/value pairs delimited by &, :, and =. String are decomposed into key/value pairs. Values can be replaced with payloads within a re-created cookie string."""
def __init__(self, cookie):
"""S... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ComplexCookie:
"""This is for complex cookie. They are cookie strings that contain list of key/value pairs delimited by &, :, and =. String are decomposed into key/value pairs. Values can be replaced with payloads within a re-created cookie string."""
def __init__(self, cookie):
"""Sets the strin... | the_stack_v2_python_sparse | ava/parsers/cookie.py | indeedsecurity/ava-ce | train | 3 |
1fb1a16900058a227a6153d65b24965d0bb68ee6 | [
"if token.start_pos_del is not None and token.end_pos_del is not None:\n position = f'{token.start_pos_del}_{token.end_pos_del}'\nelse:\n position = token.start_pos_del\nif token.inserted_sequence1 is not None and token.inserted_sequence2 is not None:\n sequence = f'{token.inserted_sequence1}_{token.insert... | <|body_start_0|>
if token.start_pos_del is not None and token.end_pos_del is not None:
position = f'{token.start_pos_del}_{token.end_pos_del}'
else:
position = token.start_pos_del
if token.inserted_sequence1 is not None and token.inserted_sequence2 is not None:
... | The DelIns Validator Base class. | DelInsBase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DelInsBase:
"""The DelIns Validator Base class."""
def concise_description(self, transcript, token) -> str:
"""Return a HGVS description of the identified variation. :param str transcript: Transcript accession :param Token token: Classification token :return: HGVS expression"""
... | stack_v2_sparse_classes_10k_train_001755 | 1,722 | permissive | [
{
"docstring": "Return a HGVS description of the identified variation. :param str transcript: Transcript accession :param Token token: Classification token :return: HGVS expression",
"name": "concise_description",
"signature": "def concise_description(self, transcript, token) -> str"
},
{
"docst... | 2 | stack_v2_sparse_classes_30k_train_002958 | Implement the Python class `DelInsBase` described below.
Class description:
The DelIns Validator Base class.
Method signatures and docstrings:
- def concise_description(self, transcript, token) -> str: Return a HGVS description of the identified variation. :param str transcript: Transcript accession :param Token toke... | Implement the Python class `DelInsBase` described below.
Class description:
The DelIns Validator Base class.
Method signatures and docstrings:
- def concise_description(self, transcript, token) -> str: Return a HGVS description of the identified variation. :param str transcript: Transcript accession :param Token toke... | d41e9ee786b14f47d17ea8e458eed08ec00ba339 | <|skeleton|>
class DelInsBase:
"""The DelIns Validator Base class."""
def concise_description(self, transcript, token) -> str:
"""Return a HGVS description of the identified variation. :param str transcript: Transcript accession :param Token token: Classification token :return: HGVS expression"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DelInsBase:
"""The DelIns Validator Base class."""
def concise_description(self, transcript, token) -> str:
"""Return a HGVS description of the identified variation. :param str transcript: Transcript accession :param Token token: Classification token :return: HGVS expression"""
if token.s... | the_stack_v2_python_sparse | variation/validators/delins_base.py | richardhj/vicc-variation-normalization | train | 0 |
24bf71d6df01f84a552941ec49922db3d9449c11 | [
"EasyFrame.__init__(self, title='Temperature Converter')\nself.model = model\nself.celsiusScale = self.addScale(label='Celsius', row=0, column=0, from_=-273.15, to=100.0, resolution=0.01, length=250, tickinterval=0, command=self.computeFahr)\nself.celsiusScale.set(model.getCelsius())\nself.fahrScale = self.addScale... | <|body_start_0|>
EasyFrame.__init__(self, title='Temperature Converter')
self.model = model
self.celsiusScale = self.addScale(label='Celsius', row=0, column=0, from_=-273.15, to=100.0, resolution=0.01, length=250, tickinterval=0, command=self.computeFahr)
self.celsiusScale.set(model.getC... | A termperature conversion program. Uses sliding scales. | ThermometerView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThermometerView:
"""A termperature conversion program. Uses sliding scales."""
def __init__(self, model):
"""Sets up the view. The model comes in as an argument."""
<|body_0|>
def computeFahr(self, degreesCelsius):
"""Inputs the Celsius degrees and outputs the Fa... | stack_v2_sparse_classes_10k_train_001756 | 2,218 | no_license | [
{
"docstring": "Sets up the view. The model comes in as an argument.",
"name": "__init__",
"signature": "def __init__(self, model)"
},
{
"docstring": "Inputs the Celsius degrees and outputs the Fahrenheit degrees.",
"name": "computeFahr",
"signature": "def computeFahr(self, degreesCelsiu... | 3 | null | Implement the Python class `ThermometerView` described below.
Class description:
A termperature conversion program. Uses sliding scales.
Method signatures and docstrings:
- def __init__(self, model): Sets up the view. The model comes in as an argument.
- def computeFahr(self, degreesCelsius): Inputs the Celsius degre... | Implement the Python class `ThermometerView` described below.
Class description:
A termperature conversion program. Uses sliding scales.
Method signatures and docstrings:
- def __init__(self, model): Sets up the view. The model comes in as an argument.
- def computeFahr(self, degreesCelsius): Inputs the Celsius degre... | eca69d000dc77681a30734b073b2383c97ccc02e | <|skeleton|>
class ThermometerView:
"""A termperature conversion program. Uses sliding scales."""
def __init__(self, model):
"""Sets up the view. The model comes in as an argument."""
<|body_0|>
def computeFahr(self, degreesCelsius):
"""Inputs the Celsius degrees and outputs the Fa... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ThermometerView:
"""A termperature conversion program. Uses sliding scales."""
def __init__(self, model):
"""Sets up the view. The model comes in as an argument."""
EasyFrame.__init__(self, title='Temperature Converter')
self.model = model
self.celsiusScale = self.addScale... | the_stack_v2_python_sparse | gui/breezy/thermometerview2.py | lforet/robomow | train | 11 |
546da4336aab8bb0e83a3be2303b77c6baa21bcd | [
"if kw.get('purity', False):\n raise NotImplementedError('Purity benchmarking is not implemented for 2QB RB. Set \"purity=False.\"')\nself.max_clifford_idx = max_clifford_idx\ntqc.gate_decomposition = rb.get_clifford_decomposition(kw.get('gate_decomposition', 'HZ'))\nif kw.get('interleaved_gate', None) is not No... | <|body_start_0|>
if kw.get('purity', False):
raise NotImplementedError('Purity benchmarking is not implemented for 2QB RB. Set "purity=False."')
self.max_clifford_idx = max_clifford_idx
tqc.gate_decomposition = rb.get_clifford_decomposition(kw.get('gate_decomposition', 'HZ'))
... | Class for running the two-qubit randomized benchmarking experiment on several pairs of qubits in parallel. Attributes in addition to the ones created by the base class: max_clifford_idx: Int, size of the 2QB Clifford group | TwoQubitRandomizedBenchmarking | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoQubitRandomizedBenchmarking:
"""Class for running the two-qubit randomized benchmarking experiment on several pairs of qubits in parallel. Attributes in addition to the ones created by the base class: max_clifford_idx: Int, size of the 2QB Clifford group"""
def __init__(self, task_list, s... | stack_v2_sparse_classes_10k_train_001757 | 38,263 | permissive | [
{
"docstring": "Each task in task_list corresponds to a qubit pair, which is specified with the keys 'qb_1' and 'qb2.' Args: nr_seeds (int): the number of times the Clifford group should be sampled for each Clifford sequence length. cliffords (list/array): integers specifying the number of cliffords to apply. m... | 3 | stack_v2_sparse_classes_30k_train_003790 | Implement the Python class `TwoQubitRandomizedBenchmarking` described below.
Class description:
Class for running the two-qubit randomized benchmarking experiment on several pairs of qubits in parallel. Attributes in addition to the ones created by the base class: max_clifford_idx: Int, size of the 2QB Clifford group
... | Implement the Python class `TwoQubitRandomizedBenchmarking` described below.
Class description:
Class for running the two-qubit randomized benchmarking experiment on several pairs of qubits in parallel. Attributes in addition to the ones created by the base class: max_clifford_idx: Int, size of the 2QB Clifford group
... | bc6733d774fe31a23f4c7e73e5eb0beed8d30e7d | <|skeleton|>
class TwoQubitRandomizedBenchmarking:
"""Class for running the two-qubit randomized benchmarking experiment on several pairs of qubits in parallel. Attributes in addition to the ones created by the base class: max_clifford_idx: Int, size of the 2QB Clifford group"""
def __init__(self, task_list, s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TwoQubitRandomizedBenchmarking:
"""Class for running the two-qubit randomized benchmarking experiment on several pairs of qubits in parallel. Attributes in addition to the ones created by the base class: max_clifford_idx: Int, size of the 2QB Clifford group"""
def __init__(self, task_list, sweep_points=N... | the_stack_v2_python_sparse | pycqed/measurement/benchmarking/randomized_benchmarking.py | QudevETH/PycQED_py3 | train | 8 |
08f536014ddb6a1457d9dcd8a51983cf5316ecbe | [
"super(Decoder, self).__init__()\nself.N = N\nself.dm = dm\nself.embedding = tf.keras.layers.Embedding(target_vocab, dm)\nself.positional_encoding = positional_encoding(max_seq_len, dm)\nself.blocks = [DecoderBlock(dm, h, hidden, drop_rate) for _ in range(N)]\nself.dropout = tf.keras.layers.Dropout(drop_rate)",
"... | <|body_start_0|>
super(Decoder, self).__init__()
self.N = N
self.dm = dm
self.embedding = tf.keras.layers.Embedding(target_vocab, dm)
self.positional_encoding = positional_encoding(max_seq_len, dm)
self.blocks = [DecoderBlock(dm, h, hidden, drop_rate) for _ in range(N)]
... | Decoder class | Decoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""Decoder class"""
def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1):
"""Class constructor :param N: number of blocks in the encoder :param dm: dimensionality of the model :param h: number of heads :param hidden: number of hidden units in the fu... | stack_v2_sparse_classes_10k_train_001758 | 2,482 | no_license | [
{
"docstring": "Class constructor :param N: number of blocks in the encoder :param dm: dimensionality of the model :param h: number of heads :param hidden: number of hidden units in the fully connected layer :param target_vocab: size of the target vocabulary :param max_seq_len: maximum sequence length possible ... | 2 | stack_v2_sparse_classes_30k_train_001452 | Implement the Python class `Decoder` described below.
Class description:
Decoder class
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1): Class constructor :param N: number of blocks in the encoder :param dm: dimensionality of the model :param h: number... | Implement the Python class `Decoder` described below.
Class description:
Decoder class
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1): Class constructor :param N: number of blocks in the encoder :param dm: dimensionality of the model :param h: number... | f83a60babb1d2a510a4a0e0f58aa3880fd9f93a7 | <|skeleton|>
class Decoder:
"""Decoder class"""
def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1):
"""Class constructor :param N: number of blocks in the encoder :param dm: dimensionality of the model :param h: number of heads :param hidden: number of hidden units in the fu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Decoder:
"""Decoder class"""
def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1):
"""Class constructor :param N: number of blocks in the encoder :param dm: dimensionality of the model :param h: number of heads :param hidden: number of hidden units in the fully connected... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/10-transformer_decoder.py | jalondono/holbertonschool-machine_learning | train | 2 |
f44b0c8b93a32cde2118a066c67f5afc252dcf27 | [
"def recursive(i, j):\n if i > j:\n return 0\n count = Counter(s[i:j + 1])\n for m in range(i, j + 1):\n if count[s[m]] >= k:\n continue\n n = m + 1\n while n <= j and count[s[n]] < k:\n n += 1\n return max(recursive(i, m - 1), recursive(n, j))\n ... | <|body_start_0|>
def recursive(i, j):
if i > j:
return 0
count = Counter(s[i:j + 1])
for m in range(i, j + 1):
if count[s[m]] >= k:
continue
n = m + 1
while n <= j and count[s[n]] < k:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestSubstring(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_0|>
def longestSubstring(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def recursive(i, j):
... | stack_v2_sparse_classes_10k_train_001759 | 1,891 | no_license | [
{
"docstring": ":type s: str :type k: int :rtype: int",
"name": "longestSubstring",
"signature": "def longestSubstring(self, s, k)"
},
{
"docstring": ":type s: str :type k: int :rtype: int",
"name": "longestSubstring",
"signature": "def longestSubstring(self, s, k)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002284 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestSubstring(self, s, k): :type s: str :type k: int :rtype: int
- def longestSubstring(self, s, k): :type s: str :type k: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestSubstring(self, s, k): :type s: str :type k: int :rtype: int
- def longestSubstring(self, s, k): :type s: str :type k: int :rtype: int
<|skeleton|>
class Solution:
... | 63b7eedc720c1ce14880b80744dcd5ef7107065c | <|skeleton|>
class Solution:
def longestSubstring(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_0|>
def longestSubstring(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def longestSubstring(self, s, k):
""":type s: str :type k: int :rtype: int"""
def recursive(i, j):
if i > j:
return 0
count = Counter(s[i:j + 1])
for m in range(i, j + 1):
if count[s[m]] >= k:
con... | the_stack_v2_python_sparse | problems/longestSubstring.py | joddiy/leetcode | train | 1 | |
2352f1cbefac384a41208cf7efbce5751aaf459a | [
"args = self.args\nif args and (not args[0] in [\"'\", ',', ':']):\n args = ' %s' % args.strip()\nself.args = args",
"if not self.args:\n msg = 'What do you want to do?'\n self.caller.msg(msg)\nelse:\n msg = '%s%s' % (getNameAnsi(self.caller), self.args)\n self.caller.location.msg_contents(text=(ms... | <|body_start_0|>
args = self.args
if args and (not args[0] in ["'", ',', ':']):
args = ' %s' % args.strip()
self.args = args
<|end_body_0|>
<|body_start_1|>
if not self.args:
msg = 'What do you want to do?'
self.caller.msg(msg)
else:
... | strike a pose Usage: pose <pose text> pose's <pose text> Example: pose is standing by the wall, smiling. -> others will see: Tom is standing by the wall, smiling. Describe an action being taken. The pose text will automatically begin with your name. | CmdPose | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CmdPose:
"""strike a pose Usage: pose <pose text> pose's <pose text> Example: pose is standing by the wall, smiling. -> others will see: Tom is standing by the wall, smiling. Describe an action being taken. The pose text will automatically begin with your name."""
def parse(self):
""... | stack_v2_sparse_classes_10k_train_001760 | 11,105 | no_license | [
{
"docstring": "Custom parse the cases where the emote starts with some special letter, such as 's, at which we don't want to separate the caller's name and the emote with a space.",
"name": "parse",
"signature": "def parse(self)"
},
{
"docstring": "Hook function",
"name": "func",
"signa... | 2 | stack_v2_sparse_classes_30k_test_000096 | Implement the Python class `CmdPose` described below.
Class description:
strike a pose Usage: pose <pose text> pose's <pose text> Example: pose is standing by the wall, smiling. -> others will see: Tom is standing by the wall, smiling. Describe an action being taken. The pose text will automatically begin with your na... | Implement the Python class `CmdPose` described below.
Class description:
strike a pose Usage: pose <pose text> pose's <pose text> Example: pose is standing by the wall, smiling. -> others will see: Tom is standing by the wall, smiling. Describe an action being taken. The pose text will automatically begin with your na... | 1a315ddab39d8cf093185acaaf68590288bbf3c1 | <|skeleton|>
class CmdPose:
"""strike a pose Usage: pose <pose text> pose's <pose text> Example: pose is standing by the wall, smiling. -> others will see: Tom is standing by the wall, smiling. Describe an action being taken. The pose text will automatically begin with your name."""
def parse(self):
""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CmdPose:
"""strike a pose Usage: pose <pose text> pose's <pose text> Example: pose is standing by the wall, smiling. -> others will see: Tom is standing by the wall, smiling. Describe an action being taken. The pose text will automatically begin with your name."""
def parse(self):
"""Custom parse... | the_stack_v2_python_sparse | tekmunkey/evennia_overrides/command_overrides.py | DamnedScholar/evennia-testbox | train | 0 |
5bc4154f720b08151cfc6b91599c80d2148c1af7 | [
"self.voltage_input = VoltageInput(analog_pin)\nself.voltage = 0.0\nself.ambient_light = self.light_extremely_dark\nself.measure_light()",
"self.voltage = self.voltage_input.voltage\nif self.voltage < self.extremely_dark_max_voltage:\n self.ambient_light = self.light_extremely_dark\nelif self.voltage < self.ve... | <|body_start_0|>
self.voltage_input = VoltageInput(analog_pin)
self.voltage = 0.0
self.ambient_light = self.light_extremely_dark
self.measure_light()
<|end_body_0|>
<|body_start_1|>
self.voltage = self.voltage_input.voltage
if self.voltage < self.extremely_dark_max_volta... | DarknessSensor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DarknessSensor:
def __init__(self, analog_pin):
"""Setting up the default values of the sensor reading"""
<|body_0|>
def measure_light(self):
"""Measuring the values of the light needed based on the voltage"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_001761 | 4,115 | no_license | [
{
"docstring": "Setting up the default values of the sensor reading",
"name": "__init__",
"signature": "def __init__(self, analog_pin)"
},
{
"docstring": "Measuring the values of the light needed based on the voltage",
"name": "measure_light",
"signature": "def measure_light(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001553 | Implement the Python class `DarknessSensor` described below.
Class description:
Implement the DarknessSensor class.
Method signatures and docstrings:
- def __init__(self, analog_pin): Setting up the default values of the sensor reading
- def measure_light(self): Measuring the values of the light needed based on the v... | Implement the Python class `DarknessSensor` described below.
Class description:
Implement the DarknessSensor class.
Method signatures and docstrings:
- def __init__(self, analog_pin): Setting up the default values of the sensor reading
- def measure_light(self): Measuring the values of the light needed based on the v... | 21bc5a9daaf33074c40f6c926effb78d6f67665f | <|skeleton|>
class DarknessSensor:
def __init__(self, analog_pin):
"""Setting up the default values of the sensor reading"""
<|body_0|>
def measure_light(self):
"""Measuring the values of the light needed based on the voltage"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DarknessSensor:
def __init__(self, analog_pin):
"""Setting up the default values of the sensor reading"""
self.voltage_input = VoltageInput(analog_pin)
self.voltage = 0.0
self.ambient_light = self.light_extremely_dark
self.measure_light()
def measure_light(self):
... | the_stack_v2_python_sparse | Group Project/Code/Clients/LightSensor/light_sensor.py | omar-mohamed/Iot-Smart-Home | train | 1 | |
bfaa39515669ff0833ec5609af7d06af9bdae15d | [
"for i in range(1, len(nums) + 1):\n idx = 0\n while idx <= len(nums) - i:\n if sum(nums[idx:idx + i]) >= s:\n return i\n idx += 1\nreturn 0",
"num_sum = 0\nmin_length = float('inf')\nstart = 0\nfor idx, val in enumerate(nums):\n num_sum += val\n if num_sum >= s:\n min_... | <|body_start_0|>
for i in range(1, len(nums) + 1):
idx = 0
while idx <= len(nums) - i:
if sum(nums[idx:idx + i]) >= s:
return i
idx += 1
return 0
<|end_body_0|>
<|body_start_1|>
num_sum = 0
min_length = float('i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minSubArrayLen_1(self, s, nums):
""":type s: int :type nums: List[int] :rtype: int"""
<|body_0|>
def minSubArrayLen_2(self, s, nums):
""":type s: int :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for... | stack_v2_sparse_classes_10k_train_001762 | 1,205 | no_license | [
{
"docstring": ":type s: int :type nums: List[int] :rtype: int",
"name": "minSubArrayLen_1",
"signature": "def minSubArrayLen_1(self, s, nums)"
},
{
"docstring": ":type s: int :type nums: List[int] :rtype: int",
"name": "minSubArrayLen_2",
"signature": "def minSubArrayLen_2(self, s, nums... | 2 | stack_v2_sparse_classes_30k_train_005380 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minSubArrayLen_1(self, s, nums): :type s: int :type nums: List[int] :rtype: int
- def minSubArrayLen_2(self, s, nums): :type s: int :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minSubArrayLen_1(self, s, nums): :type s: int :type nums: List[int] :rtype: int
- def minSubArrayLen_2(self, s, nums): :type s: int :type nums: List[int] :rtype: int
<|skele... | f0fa1f0af9613914c12f45a218500a75f9ba3c1a | <|skeleton|>
class Solution:
def minSubArrayLen_1(self, s, nums):
""":type s: int :type nums: List[int] :rtype: int"""
<|body_0|>
def minSubArrayLen_2(self, s, nums):
""":type s: int :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def minSubArrayLen_1(self, s, nums):
""":type s: int :type nums: List[int] :rtype: int"""
for i in range(1, len(nums) + 1):
idx = 0
while idx <= len(nums) - i:
if sum(nums[idx:idx + i]) >= s:
return i
idx += ... | the_stack_v2_python_sparse | Array_and_String/Minimum_Size_Subarray_Sum.py | ncturoger/LeetCodePractice | train | 0 | |
c7f88a6aea530ddce980a1920194f6cf1ace4630 | [
"N = len(nums)\nsums = list(accumulate(nums))\nans = 0\nf, t = (0, 0)\nfor i in range(N - 2):\n while f <= i or (f < N - 1 and sums[i] > sums[f] - sums[i]):\n f += 1\n while t < f or (t < N - 1 and sums[t] - sums[i] <= sums[-1] - sums[t]):\n t += 1\n ans = (ans + t - f) % (10 ** 9 + 7)\nretur... | <|body_start_0|>
N = len(nums)
sums = list(accumulate(nums))
ans = 0
f, t = (0, 0)
for i in range(N - 2):
while f <= i or (f < N - 1 and sums[i] > sums[f] - sums[i]):
f += 1
while t < f or (t < N - 1 and sums[t] - sums[i] <= sums[-1] - sums... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def waysToSplit(self, nums: List[int]) -> int:
"""1번 방법을 two pointer 문제로 풀어서 계산량을 줄임. i를 키우면 l이 커지고, m이 작아짐. j를 키우면 m이 커지고, r이 작아짐. i를 키우면서 j의 범위 f, t을 구함 i를 키우면 f를 키워야만 하고, t도 더 커질 수 있다. O(N) / O(N)"""
<|body_0|>
def waysToSplit1(self, nums: List[int]) -> int:
... | stack_v2_sparse_classes_10k_train_001763 | 1,569 | no_license | [
{
"docstring": "1번 방법을 two pointer 문제로 풀어서 계산량을 줄임. i를 키우면 l이 커지고, m이 작아짐. j를 키우면 m이 커지고, r이 작아짐. i를 키우면서 j의 범위 f, t을 구함 i를 키우면 f를 키워야만 하고, t도 더 커질 수 있다. O(N) / O(N)",
"name": "waysToSplit",
"signature": "def waysToSplit(self, nums: List[int]) -> int"
},
{
"docstring": "Prefix sum으로 2개의 포인트를 결정하... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def waysToSplit(self, nums: List[int]) -> int: 1번 방법을 two pointer 문제로 풀어서 계산량을 줄임. i를 키우면 l이 커지고, m이 작아짐. j를 키우면 m이 커지고, r이 작아짐. i를 키우면서 j의 범위 f, t을 구함 i를 키우면 f를 키워야만 하고, t도 더 커질... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def waysToSplit(self, nums: List[int]) -> int: 1번 방법을 two pointer 문제로 풀어서 계산량을 줄임. i를 키우면 l이 커지고, m이 작아짐. j를 키우면 m이 커지고, r이 작아짐. i를 키우면서 j의 범위 f, t을 구함 i를 키우면 f를 키워야만 하고, t도 더 커질... | c26aef2a59e5cc2d9b0658b9c7386a43267ff8a1 | <|skeleton|>
class Solution:
def waysToSplit(self, nums: List[int]) -> int:
"""1번 방법을 two pointer 문제로 풀어서 계산량을 줄임. i를 키우면 l이 커지고, m이 작아짐. j를 키우면 m이 커지고, r이 작아짐. i를 키우면서 j의 범위 f, t을 구함 i를 키우면 f를 키워야만 하고, t도 더 커질 수 있다. O(N) / O(N)"""
<|body_0|>
def waysToSplit1(self, nums: List[int]) -> int:
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def waysToSplit(self, nums: List[int]) -> int:
"""1번 방법을 two pointer 문제로 풀어서 계산량을 줄임. i를 키우면 l이 커지고, m이 작아짐. j를 키우면 m이 커지고, r이 작아짐. i를 키우면서 j의 범위 f, t을 구함 i를 키우면 f를 키워야만 하고, t도 더 커질 수 있다. O(N) / O(N)"""
N = len(nums)
sums = list(accumulate(nums))
ans = 0
f, t ... | the_stack_v2_python_sparse | Leetcode/1712.py | hanwgyu/algorithm_problem_solving | train | 5 | |
af75b471a6427d070f98b39082caf128095ef1f9 | [
"version = versionutils.convert_version_to_tuple(cls.VERSION)\nif not hasattr(objects, cls.obj_name()):\n setattr(objects, cls.obj_name(), cls)\nelse:\n curr_version = versionutils.convert_version_to_tuple(getattr(objects, cls.obj_name()).VERSION)\n if version >= curr_version:\n setattr(objects, cls... | <|body_start_0|>
version = versionutils.convert_version_to_tuple(cls.VERSION)
if not hasattr(objects, cls.obj_name()):
setattr(objects, cls.obj_name(), cls)
else:
curr_version = versionutils.convert_version_to_tuple(getattr(objects, cls.obj_name()).VERSION)
if... | SenlinObjectRegistry | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SenlinObjectRegistry:
def registration_hook(self, cls, index):
"""Callback for object registration. When an object is registered, this function will be called for maintaining senlin.objects.$OBJECT as the highest-versioned implementation of a given object."""
<|body_0|>
def ... | stack_v2_sparse_classes_10k_train_001764 | 5,694 | permissive | [
{
"docstring": "Callback for object registration. When an object is registered, this function will be called for maintaining senlin.objects.$OBJECT as the highest-versioned implementation of a given object.",
"name": "registration_hook",
"signature": "def registration_hook(self, cls, index)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_003277 | Implement the Python class `SenlinObjectRegistry` described below.
Class description:
Implement the SenlinObjectRegistry class.
Method signatures and docstrings:
- def registration_hook(self, cls, index): Callback for object registration. When an object is registered, this function will be called for maintaining senl... | Implement the Python class `SenlinObjectRegistry` described below.
Class description:
Implement the SenlinObjectRegistry class.
Method signatures and docstrings:
- def registration_hook(self, cls, index): Callback for object registration. When an object is registered, this function will be called for maintaining senl... | 4125b34e0a0dfeb77b8e62f169b41e8b584bb60e | <|skeleton|>
class SenlinObjectRegistry:
def registration_hook(self, cls, index):
"""Callback for object registration. When an object is registered, this function will be called for maintaining senlin.objects.$OBJECT as the highest-versioned implementation of a given object."""
<|body_0|>
def ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SenlinObjectRegistry:
def registration_hook(self, cls, index):
"""Callback for object registration. When an object is registered, this function will be called for maintaining senlin.objects.$OBJECT as the highest-versioned implementation of a given object."""
version = versionutils.convert_ver... | the_stack_v2_python_sparse | senlin/objects/base.py | openstack/senlin | train | 47 | |
efb30f71a35b22c65e349cd4db58afa9b7ad2099 | [
"actions = super(NagiosContactGroupAdmin, self).get_actions(request)\ndel actions['delete_selected']\nreturn actions",
"for contact in queryset:\n if contact.delete():\n messages.info(request, _(u'Deleted contact: %s ' % contact))\n else:\n messages.warning(request, _(u'Contact %s can not be d... | <|body_start_0|>
actions = super(NagiosContactGroupAdmin, self).get_actions(request)
del actions['delete_selected']
return actions
<|end_body_0|>
<|body_start_1|>
for contact in queryset:
if contact.delete():
messages.info(request, _(u'Deleted contact: %s ' %... | NagiosContactGroupAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NagiosContactGroupAdmin:
def get_actions(self, request):
"""Disable delete_selected action to control the delete operation, even in querysets"""
<|body_0|>
def delete_contact(self, request, queryset):
"""Check if there are checks active for a contact, before delete i... | stack_v2_sparse_classes_10k_train_001765 | 7,219 | no_license | [
{
"docstring": "Disable delete_selected action to control the delete operation, even in querysets",
"name": "get_actions",
"signature": "def get_actions(self, request)"
},
{
"docstring": "Check if there are checks active for a contact, before delete it",
"name": "delete_contact",
"signat... | 2 | stack_v2_sparse_classes_30k_train_005600 | Implement the Python class `NagiosContactGroupAdmin` described below.
Class description:
Implement the NagiosContactGroupAdmin class.
Method signatures and docstrings:
- def get_actions(self, request): Disable delete_selected action to control the delete operation, even in querysets
- def delete_contact(self, request... | Implement the Python class `NagiosContactGroupAdmin` described below.
Class description:
Implement the NagiosContactGroupAdmin class.
Method signatures and docstrings:
- def get_actions(self, request): Disable delete_selected action to control the delete operation, even in querysets
- def delete_contact(self, request... | 494fcc0a3c0fa1098a6a4d1eb0019be4c5646354 | <|skeleton|>
class NagiosContactGroupAdmin:
def get_actions(self, request):
"""Disable delete_selected action to control the delete operation, even in querysets"""
<|body_0|>
def delete_contact(self, request, queryset):
"""Check if there are checks active for a contact, before delete i... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NagiosContactGroupAdmin:
def get_actions(self, request):
"""Disable delete_selected action to control the delete operation, even in querysets"""
actions = super(NagiosContactGroupAdmin, self).get_actions(request)
del actions['delete_selected']
return actions
def delete_con... | the_stack_v2_python_sparse | arritranco/monitoring/nagios/admin.py | tic-ull/arritranco | train | 3 | |
e9560d463e5144538e379603b5e3d8e3baa7d891 | [
"grid = gd.makeGrid(grid_type, **grid_kwargs)\nprint('Reading input from {0}'.format(filename))\nmgnr = f2py_mg.f2py_manager(path.join(fortran_source_path, 'mod_topo_io.f90'), func_name='read_topo')\ndata = mgnr.run_current_function_or_subroutine(filename, *grid.get_grid_dimensions())\nreturn np.fliplr(np.rot90(dat... | <|body_start_0|>
grid = gd.makeGrid(grid_type, **grid_kwargs)
print('Reading input from {0}'.format(filename))
mgnr = f2py_mg.f2py_manager(path.join(fortran_source_path, 'mod_topo_io.f90'), func_name='read_topo')
data = mgnr.run_current_function_or_subroutine(filename, *grid.get_grid_dim... | Class to read and write unformatted fortran files using f2py. Public methods: As for parent class | F2PyFortranFileIOHelper | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class F2PyFortranFileIOHelper:
"""Class to read and write unformatted fortran files using f2py. Public methods: As for parent class"""
def load_field(self, filename, unmask=True, timeslice=None, fieldname=None, check_for_grid_info=False, grid_info=None, grid_type='HD', **grid_kwargs):
"""L... | stack_v2_sparse_classes_10k_train_001766 | 23,117 | permissive | [
{
"docstring": "Load a field from a unformatted fortran file using f2py Arguments: filename: string; full path of the file to load grid_type: string; keyword specifying what type of grid to use **grid_kwargs: keyword dictionary; keyword arguments giving parameters of the grid fieldname, timeslice, unmask, check... | 2 | stack_v2_sparse_classes_30k_train_004329 | Implement the Python class `F2PyFortranFileIOHelper` described below.
Class description:
Class to read and write unformatted fortran files using f2py. Public methods: As for parent class
Method signatures and docstrings:
- def load_field(self, filename, unmask=True, timeslice=None, fieldname=None, check_for_grid_info... | Implement the Python class `F2PyFortranFileIOHelper` described below.
Class description:
Class to read and write unformatted fortran files using f2py. Public methods: As for parent class
Method signatures and docstrings:
- def load_field(self, filename, unmask=True, timeslice=None, fieldname=None, check_for_grid_info... | 08b627238c4bfa39026820c6116c1ed71f453b22 | <|skeleton|>
class F2PyFortranFileIOHelper:
"""Class to read and write unformatted fortran files using f2py. Public methods: As for parent class"""
def load_field(self, filename, unmask=True, timeslice=None, fieldname=None, check_for_grid_info=False, grid_info=None, grid_type='HD', **grid_kwargs):
"""L... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class F2PyFortranFileIOHelper:
"""Class to read and write unformatted fortran files using f2py. Public methods: As for parent class"""
def load_field(self, filename, unmask=True, timeslice=None, fieldname=None, check_for_grid_info=False, grid_info=None, grid_type='HD', **grid_kwargs):
"""Load a field f... | the_stack_v2_python_sparse | Dynamic_HD_Scripts/Dynamic_HD_Scripts/base/iohelper.py | ThomasRiddick/DynamicHD | train | 1 |
a0971427722cdcd71c00580730cc43f25105c5f4 | [
"self.rects = rects\nacc = 0\nself.ranges = []\nfor x1, y1, x2, y2 in rects:\n area = (x2 - x1 + 1) * (y2 - y1 + 1)\n acc += area\n self.ranges.append(acc)",
"idx = bisect.bisect_left(self.ranges, random.randint(1, self.ranges[-1]))\nx1, y1, x2, y2 = self.rects[idx]\nreturn [random.randint(x1, x2), rando... | <|body_start_0|>
self.rects = rects
acc = 0
self.ranges = []
for x1, y1, x2, y2 in rects:
area = (x2 - x1 + 1) * (y2 - y1 + 1)
acc += area
self.ranges.append(acc)
<|end_body_0|>
<|body_start_1|>
idx = bisect.bisect_left(self.ranges, random.ran... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.rects = rects
acc = 0
self.ranges = []
for x1, y1, x... | stack_v2_sparse_classes_10k_train_001767 | 711 | permissive | [
{
"docstring": ":type rects: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, rects)"
},
{
"docstring": ":rtype: List[int]",
"name": "pick",
"signature": "def pick(self)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]]
- def pick(self): :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]]
- def pick(self): :rtype: List[int]
<|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: ... | 3719f5cb059eefd66b83eb8ae990652f4b7fd124 | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
self.rects = rects
acc = 0
self.ranges = []
for x1, y1, x2, y2 in rects:
area = (x2 - x1 + 1) * (y2 - y1 + 1)
acc += area
self.ranges.append(acc)
def pick(se... | the_stack_v2_python_sparse | Python3/0497-Random-Point-in-Non-Overlapping-Rectangles/soln.py | wyaadarsh/LeetCode-Solutions | train | 0 | |
a5ede93dd30265c32154896e8ac3a08ee7105073 | [
"if not root:\n return 0\nvalues = self.dfs(root)\nreturn max(values[0], values[1])",
"if not node:\n return (0, 0)\nleft = self.dfs(node.left)\nright = self.dfs(node.right)\nrob_node = left[1] + right[1] + node.val\nnot_rob = max(left[0], left[1]) + max(right[0], right[1])\nreturn (rob_node, not_rob)"
] | <|body_start_0|>
if not root:
return 0
values = self.dfs(root)
return max(values[0], values[1])
<|end_body_0|>
<|body_start_1|>
if not node:
return (0, 0)
left = self.dfs(node.left)
right = self.dfs(node.right)
rob_node = left[1] + right[1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def dfs(self, node):
"""return val: tuple(int, int) val[0]: How many value do I earn while roobing the node val[1]: Not rob node"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_10k_train_001768 | 876 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "rob",
"signature": "def rob(self, root)"
},
{
"docstring": "return val: tuple(int, int) val[0]: How many value do I earn while roobing the node val[1]: Not rob node",
"name": "dfs",
"signature": "def dfs(self, node)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, root): :type root: TreeNode :rtype: int
- def dfs(self, node): return val: tuple(int, int) val[0]: How many value do I earn while roobing the node val[1]: Not rob n... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, root): :type root: TreeNode :rtype: int
- def dfs(self, node): return val: tuple(int, int) val[0]: How many value do I earn while roobing the node val[1]: Not rob n... | 1a3c1f4d6e9d3444039f087763b93241f4ba7892 | <|skeleton|>
class Solution:
def rob(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def dfs(self, node):
"""return val: tuple(int, int) val[0]: How many value do I earn while roobing the node val[1]: Not rob node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def rob(self, root):
""":type root: TreeNode :rtype: int"""
if not root:
return 0
values = self.dfs(root)
return max(values[0], values[1])
def dfs(self, node):
"""return val: tuple(int, int) val[0]: How many value do I earn while roobing the n... | the_stack_v2_python_sparse | Algorithm/337_House_Rob_III.py | Gi1ia/TechNoteBook | train | 7 | |
6732325006f21a58628517b3b5fb88d4d2bf10fe | [
"self.dirname = Path(dirname).absolute()\nself.basename = basename\nif not self.dirname.is_dir():\n raise ValueError('dirname must be a directory')",
"all_filenames = self.dirname.glob('*')\nd = {}\nfor v in all_filenames:\n split_fn = v.name\n m = glob.re.search('^(\\\\w+)\\\\.%s\\\\.(\\\\d+)$' % typest... | <|body_start_0|>
self.dirname = Path(dirname).absolute()
self.basename = basename
if not self.dirname.is_dir():
raise ValueError('dirname must be a directory')
<|end_body_0|>
<|body_start_1|>
all_filenames = self.dirname.glob('*')
d = {}
for v in all_filename... | Simple class to interpret user's requests into KlustaKwik filenames | FilenameParser | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilenameParser:
"""Simple class to interpret user's requests into KlustaKwik filenames"""
def __init__(self, dirname, basename=None):
"""Initialize a new parser for a directory containing files dirname: directory containing files basename: basename in KlustaKwik format spec If basena... | stack_v2_sparse_classes_10k_train_001769 | 17,008 | permissive | [
{
"docstring": "Initialize a new parser for a directory containing files dirname: directory containing files basename: basename in KlustaKwik format spec If basename is left None, then files with any basename in the directory will be used. An error is raised if files with multiple basenames exist in the directo... | 2 | stack_v2_sparse_classes_30k_train_000947 | Implement the Python class `FilenameParser` described below.
Class description:
Simple class to interpret user's requests into KlustaKwik filenames
Method signatures and docstrings:
- def __init__(self, dirname, basename=None): Initialize a new parser for a directory containing files dirname: directory containing fil... | Implement the Python class `FilenameParser` described below.
Class description:
Simple class to interpret user's requests into KlustaKwik filenames
Method signatures and docstrings:
- def __init__(self, dirname, basename=None): Initialize a new parser for a directory containing files dirname: directory containing fil... | 354c8d9d5fbc4daad3547773d2f281f8c163d208 | <|skeleton|>
class FilenameParser:
"""Simple class to interpret user's requests into KlustaKwik filenames"""
def __init__(self, dirname, basename=None):
"""Initialize a new parser for a directory containing files dirname: directory containing files basename: basename in KlustaKwik format spec If basena... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FilenameParser:
"""Simple class to interpret user's requests into KlustaKwik filenames"""
def __init__(self, dirname, basename=None):
"""Initialize a new parser for a directory containing files dirname: directory containing files basename: basename in KlustaKwik format spec If basename is left No... | the_stack_v2_python_sparse | neo/io/klustakwikio.py | NeuralEnsemble/python-neo | train | 265 |
57fc989759ace50a652736d8baa6b2121d64dd5d | [
"m = len(matrix)\nn = len(matrix[0])\nif m == 0 or n == 0:\n return matrix\nres = []\nfor i in range(m):\n tmp = []\n for j in range(i + 1):\n tmp.append(matrix[i - j][j])\n if i % 2 == 0:\n res += tmp\n else:\n res += tmp[::-1]",
"if not matrix:\n return []\nm = len(matrix)... | <|body_start_0|>
m = len(matrix)
n = len(matrix[0])
if m == 0 or n == 0:
return matrix
res = []
for i in range(m):
tmp = []
for j in range(i + 1):
tmp.append(matrix[i - j][j])
if i % 2 == 0:
res += tm... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDiagonalOrder(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int]"""
<|body_0|>
def findDiagonalOrder(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int]"""
<|body_1|>
def findDiagonalOrder(self, matrix):
... | stack_v2_sparse_classes_10k_train_001770 | 2,124 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :rtype: List[int]",
"name": "findDiagonalOrder",
"signature": "def findDiagonalOrder(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: List[int]",
"name": "findDiagonalOrder",
"signature": "def findDiagonalOrder(self, ma... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDiagonalOrder(self, matrix): :type matrix: List[List[int]] :rtype: List[int]
- def findDiagonalOrder(self, matrix): :type matrix: List[List[int]] :rtype: List[int]
- def ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDiagonalOrder(self, matrix): :type matrix: List[List[int]] :rtype: List[int]
- def findDiagonalOrder(self, matrix): :type matrix: List[List[int]] :rtype: List[int]
- def ... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def findDiagonalOrder(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int]"""
<|body_0|>
def findDiagonalOrder(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int]"""
<|body_1|>
def findDiagonalOrder(self, matrix):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findDiagonalOrder(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int]"""
m = len(matrix)
n = len(matrix[0])
if m == 0 or n == 0:
return matrix
res = []
for i in range(m):
tmp = []
for j in range(i +... | the_stack_v2_python_sparse | 0498_Diagonal_Traverse.py | bingli8802/leetcode | train | 0 | |
e8554fad1c7997a78c3e31e3a08ccda16f32c8e7 | [
"self.ground_filter_offset = config.ground_filter_offset\nself.offset_filter_distance = config.offset_filter_distance\nself.std_dev_multiplier = config.std_dev_multiplier\nself.kitti_utils = kitti_utils",
"slice_filter = self.kitti_utils.create_slice_filter(point_cloud, area_extents, ground_plane, self.ground_fil... | <|body_start_0|>
self.ground_filter_offset = config.ground_filter_offset
self.offset_filter_distance = config.offset_filter_distance
self.std_dev_multiplier = config.std_dev_multiplier
self.kitti_utils = kitti_utils
<|end_body_0|>
<|body_start_1|>
slice_filter = self.kitti_utils... | BevHeightPriors | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BevHeightPriors:
def __init__(self, config, kitti_utils):
"""BEV maps created using gaussian height priors. Args: config: bev_generator protobuf config kitti_utils: KittiUtils object"""
<|body_0|>
def generate_bev(self, source, point_cloud, ground_plane, area_extents, voxel_... | stack_v2_sparse_classes_10k_train_001771 | 4,840 | no_license | [
{
"docstring": "BEV maps created using gaussian height priors. Args: config: bev_generator protobuf config kitti_utils: KittiUtils object",
"name": "__init__",
"signature": "def __init__(self, config, kitti_utils)"
},
{
"docstring": "Generates the BEV maps dictionary. One height map is created f... | 2 | stack_v2_sparse_classes_30k_train_005326 | Implement the Python class `BevHeightPriors` described below.
Class description:
Implement the BevHeightPriors class.
Method signatures and docstrings:
- def __init__(self, config, kitti_utils): BEV maps created using gaussian height priors. Args: config: bev_generator protobuf config kitti_utils: KittiUtils object
-... | Implement the Python class `BevHeightPriors` described below.
Class description:
Implement the BevHeightPriors class.
Method signatures and docstrings:
- def __init__(self, config, kitti_utils): BEV maps created using gaussian height priors. Args: config: bev_generator protobuf config kitti_utils: KittiUtils object
-... | ac8256bd76fe4b81cfc48dc4c0b9d9dc92bc61c6 | <|skeleton|>
class BevHeightPriors:
def __init__(self, config, kitti_utils):
"""BEV maps created using gaussian height priors. Args: config: bev_generator protobuf config kitti_utils: KittiUtils object"""
<|body_0|>
def generate_bev(self, source, point_cloud, ground_plane, area_extents, voxel_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BevHeightPriors:
def __init__(self, config, kitti_utils):
"""BEV maps created using gaussian height priors. Args: config: bev_generator protobuf config kitti_utils: KittiUtils object"""
self.ground_filter_offset = config.ground_filter_offset
self.offset_filter_distance = config.offset_... | the_stack_v2_python_sparse | mlod/core/bev_generators/bev_height_priors.py | songsanling/MLOD | train | 0 | |
30c24fb676cec8aeeef58435c14141f1c5ea1bf6 | [
"creds = self.os_primary.credentials\nuser_id = creds.user_id\nusername = creds.username\npassword = creds.password\nuser_domain_id = creds.user_domain_id\nsubject_token, token_body = self.non_admin_token.get_token(user_id=user_id, username=username, user_domain_id=user_domain_id, password=password, auth_data=True)... | <|body_start_0|>
creds = self.os_primary.credentials
user_id = creds.user_id
username = creds.username
password = creds.password
user_domain_id = creds.user_domain_id
subject_token, token_body = self.non_admin_token.get_token(user_id=user_id, username=username, user_domai... | Test identity tokens | TokensV3Test | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TokensV3Test:
"""Test identity tokens"""
def test_validate_token(self):
"""Test validating token for user"""
<|body_0|>
def test_create_token(self):
"""Test creating token for user"""
<|body_1|>
def test_token_auth_creation_existence_deletion(self):
... | stack_v2_sparse_classes_10k_train_001772 | 6,688 | permissive | [
{
"docstring": "Test validating token for user",
"name": "test_validate_token",
"signature": "def test_validate_token(self)"
},
{
"docstring": "Test creating token for user",
"name": "test_create_token",
"signature": "def test_create_token(self)"
},
{
"docstring": "Test auth/chec... | 3 | stack_v2_sparse_classes_30k_test_000186 | Implement the Python class `TokensV3Test` described below.
Class description:
Test identity tokens
Method signatures and docstrings:
- def test_validate_token(self): Test validating token for user
- def test_create_token(self): Test creating token for user
- def test_token_auth_creation_existence_deletion(self): Test... | Implement the Python class `TokensV3Test` described below.
Class description:
Test identity tokens
Method signatures and docstrings:
- def test_validate_token(self): Test validating token for user
- def test_create_token(self): Test creating token for user
- def test_token_auth_creation_existence_deletion(self): Test... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class TokensV3Test:
"""Test identity tokens"""
def test_validate_token(self):
"""Test validating token for user"""
<|body_0|>
def test_create_token(self):
"""Test creating token for user"""
<|body_1|>
def test_token_auth_creation_existence_deletion(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TokensV3Test:
"""Test identity tokens"""
def test_validate_token(self):
"""Test validating token for user"""
creds = self.os_primary.credentials
user_id = creds.user_id
username = creds.username
password = creds.password
user_domain_id = creds.user_domain_i... | the_stack_v2_python_sparse | tempest/api/identity/v3/test_tokens.py | openstack/tempest | train | 270 |
365a2f472d9aca3aa563288bafbac59cafe06ad5 | [
"cache_blog_recent_post = cache.get('pythonizame_recent_playlist')\nif cache_blog_recent_post:\n queryset = cache_blog_recent_post\nelse:\n queryset = PlayList.objects.filter(status=1).order_by('-timestamp')[:5]\n cache.set('pythonizame_recent_playlist', queryset, 60 * 5)\nreturn queryset",
"if 'q' in re... | <|body_start_0|>
cache_blog_recent_post = cache.get('pythonizame_recent_playlist')
if cache_blog_recent_post:
queryset = cache_blog_recent_post
else:
queryset = PlayList.objects.filter(status=1).order_by('-timestamp')[:5]
cache.set('pythonizame_recent_playlist... | IndexView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IndexView:
def get_recent_playlist():
"""Obtenemos las últimas 5 publicaciones :return:"""
<|body_0|>
def get(self, request):
"""Devolvemos consulta de publicaciones al usuario"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cache_blog_recent_post =... | stack_v2_sparse_classes_10k_train_001773 | 5,054 | permissive | [
{
"docstring": "Obtenemos las últimas 5 publicaciones :return:",
"name": "get_recent_playlist",
"signature": "def get_recent_playlist()"
},
{
"docstring": "Devolvemos consulta de publicaciones al usuario",
"name": "get",
"signature": "def get(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004159 | Implement the Python class `IndexView` described below.
Class description:
Implement the IndexView class.
Method signatures and docstrings:
- def get_recent_playlist(): Obtenemos las últimas 5 publicaciones :return:
- def get(self, request): Devolvemos consulta de publicaciones al usuario | Implement the Python class `IndexView` described below.
Class description:
Implement the IndexView class.
Method signatures and docstrings:
- def get_recent_playlist(): Obtenemos las últimas 5 publicaciones :return:
- def get(self, request): Devolvemos consulta de publicaciones al usuario
<|skeleton|>
class IndexVie... | 6483aa90859fc1bfbc01540efe4ffcf6fe87e450 | <|skeleton|>
class IndexView:
def get_recent_playlist():
"""Obtenemos las últimas 5 publicaciones :return:"""
<|body_0|>
def get(self, request):
"""Devolvemos consulta de publicaciones al usuario"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IndexView:
def get_recent_playlist():
"""Obtenemos las últimas 5 publicaciones :return:"""
cache_blog_recent_post = cache.get('pythonizame_recent_playlist')
if cache_blog_recent_post:
queryset = cache_blog_recent_post
else:
queryset = PlayList.objects.fi... | the_stack_v2_python_sparse | pythonizame/apps/videos/views.py | fabianfalon/pythonizame | train | 0 | |
793e9053b218a4c4ece4d609e02a50cd685bfa1b | [
"super(PositionalEncoding, self).__init__()\nself.d_model = d_model\nself.xscale = math.sqrt(self.d_model)\nself.dropout = nn.Dropout(p=dropout)\nself.pe = None\nself.extend_pe(torch.tensor(0.0).expand(1, max_len))",
"if self.pe is not None:\n if self.pe.size(1) >= x.size(1):\n if self.pe.dtype != x.dty... | <|body_start_0|>
super(PositionalEncoding, self).__init__()
self.d_model = d_model
self.xscale = math.sqrt(self.d_model)
self.dropout = nn.Dropout(p=dropout)
self.pe = None
self.extend_pe(torch.tensor(0.0).expand(1, max_len))
<|end_body_0|>
<|body_start_1|>
if se... | Positional encoding. Args: d_model: Embedding dimension. dropout: Dropout rate. max_len: Maximum input length. | PositionalEncoding | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionalEncoding:
"""Positional encoding. Args: d_model: Embedding dimension. dropout: Dropout rate. max_len: Maximum input length."""
def __init__(self, d_model: int, dropout: float=0.1, max_len: int=5000) -> None:
"""Construct an PositionalEncoding object."""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_001774 | 33,189 | permissive | [
{
"docstring": "Construct an PositionalEncoding object.",
"name": "__init__",
"signature": "def __init__(self, d_model: int, dropout: float=0.1, max_len: int=5000) -> None"
},
{
"docstring": "Reset the positional encodings.",
"name": "extend_pe",
"signature": "def extend_pe(self, x: Tens... | 3 | stack_v2_sparse_classes_30k_train_005954 | Implement the Python class `PositionalEncoding` described below.
Class description:
Positional encoding. Args: d_model: Embedding dimension. dropout: Dropout rate. max_len: Maximum input length.
Method signatures and docstrings:
- def __init__(self, d_model: int, dropout: float=0.1, max_len: int=5000) -> None: Constr... | Implement the Python class `PositionalEncoding` described below.
Class description:
Positional encoding. Args: d_model: Embedding dimension. dropout: Dropout rate. max_len: Maximum input length.
Method signatures and docstrings:
- def __init__(self, d_model: int, dropout: float=0.1, max_len: int=5000) -> None: Constr... | 2dda31e14039a79b77c89bcd3bb96d52cbf60c8a | <|skeleton|>
class PositionalEncoding:
"""Positional encoding. Args: d_model: Embedding dimension. dropout: Dropout rate. max_len: Maximum input length."""
def __init__(self, d_model: int, dropout: float=0.1, max_len: int=5000) -> None:
"""Construct an PositionalEncoding object."""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PositionalEncoding:
"""Positional encoding. Args: d_model: Embedding dimension. dropout: Dropout rate. max_len: Maximum input length."""
def __init__(self, d_model: int, dropout: float=0.1, max_len: int=5000) -> None:
"""Construct an PositionalEncoding object."""
super(PositionalEncoding,... | the_stack_v2_python_sparse | snowfall/models/transformer.py | csukuangfj/snowfall | train | 0 |
318b2e93ae4383e9492397a8596f33a0287dfee9 | [
"sum = 0\nif not root:\n return 0\nif root.left and (not root.left.left) and (not root.left.right):\n sum += root.left.val\nsum += self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)\nreturn sum",
"res = 0\nif not root:\n return res\nstack = [root]\nwhile stack:\n node = stack.pop(0)\n ... | <|body_start_0|>
sum = 0
if not root:
return 0
if root.left and (not root.left.left) and (not root.left.right):
sum += root.left.val
sum += self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)
return sum
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sumOfLeftLeaves(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def sumOfLeftLeaves2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sum = 0
if not root:
... | stack_v2_sparse_classes_10k_train_001775 | 1,046 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "sumOfLeftLeaves",
"signature": "def sumOfLeftLeaves(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "sumOfLeftLeaves2",
"signature": "def sumOfLeftLeaves2(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007003 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumOfLeftLeaves(self, root): :type root: TreeNode :rtype: int
- def sumOfLeftLeaves2(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumOfLeftLeaves(self, root): :type root: TreeNode :rtype: int
- def sumOfLeftLeaves2(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def sumO... | 88a822c48ef50187507d0f75ce65ecc39e849839 | <|skeleton|>
class Solution:
def sumOfLeftLeaves(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def sumOfLeftLeaves2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def sumOfLeftLeaves(self, root):
""":type root: TreeNode :rtype: int"""
sum = 0
if not root:
return 0
if root.left and (not root.left.left) and (not root.left.right):
sum += root.left.val
sum += self.sumOfLeftLeaves(root.left) + self.su... | the_stack_v2_python_sparse | bwu/binary_tree/404-sum-of-left-leaves.py | captainhcg/leetcode-in-py-and-go | train | 1 | |
e125e655a8febcb816ca069eaaa3bbd2076ae4e7 | [
"super(TasNet, self).__init__()\nassert sr * 4 % L == 0\nself.N = N\nself.stride = W\nself.out_channels = 1\nself.C = 4\nself.encoder = Encoder(self.N, L, W, args.filters, args.num_mels, sr)\nself.decoder = Decoder(self.N, L, W, args.filters)\nself.dropout = nn.Dropout2d(args.dropout)\nself.mask = MaskingModule(not... | <|body_start_0|>
super(TasNet, self).__init__()
assert sr * 4 % L == 0
self.N = N
self.stride = W
self.out_channels = 1
self.C = 4
self.encoder = Encoder(self.N, L, W, args.filters, args.num_mels, sr)
self.decoder = Decoder(self.N, L, W, args.filters)
... | One stage of encoder->mask->decoder for a single sampling rate | TasNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TasNet:
"""One stage of encoder->mask->decoder for a single sampling rate"""
def __init__(self, independent_params, N, L, W, B, H, sr, partial_input, args):
"""Arguments: independent_params {bool} -- False if you want to use the generated weights N {int} -- Dimension of the latent ma... | stack_v2_sparse_classes_10k_train_001776 | 37,269 | no_license | [
{
"docstring": "Arguments: independent_params {bool} -- False if you want to use the generated weights N {int} -- Dimension of the latent matrix L {int} -- Dimension of the latent representation W {int} -- Kernel size of the en/decoder transfomation B {int} -- Dimension of the bottleneck convolution in the mask... | 3 | stack_v2_sparse_classes_30k_train_002873 | Implement the Python class `TasNet` described below.
Class description:
One stage of encoder->mask->decoder for a single sampling rate
Method signatures and docstrings:
- def __init__(self, independent_params, N, L, W, B, H, sr, partial_input, args): Arguments: independent_params {bool} -- False if you want to use th... | Implement the Python class `TasNet` described below.
Class description:
One stage of encoder->mask->decoder for a single sampling rate
Method signatures and docstrings:
- def __init__(self, independent_params, N, L, W, B, H, sr, partial_input, args): Arguments: independent_params {bool} -- False if you want to use th... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class TasNet:
"""One stage of encoder->mask->decoder for a single sampling rate"""
def __init__(self, independent_params, N, L, W, B, H, sr, partial_input, args):
"""Arguments: independent_params {bool} -- False if you want to use the generated weights N {int} -- Dimension of the latent ma... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TasNet:
"""One stage of encoder->mask->decoder for a single sampling rate"""
def __init__(self, independent_params, N, L, W, B, H, sr, partial_input, args):
"""Arguments: independent_params {bool} -- False if you want to use the generated weights N {int} -- Dimension of the latent matrix L {int} ... | the_stack_v2_python_sparse | generated/test_pfnet_research_meta_tasnet.py | jansel/pytorch-jit-paritybench | train | 35 |
cda08493ccfbf66bbfcc9defb44c5d87f3fce4fc | [
"conus_latitudes_deg, conus_longitudes_deg = conus_boundary.read_from_netcdf()\nthese_flags = conus_boundary.find_points_in_conus(conus_latitudes_deg=conus_latitudes_deg, conus_longitudes_deg=conus_longitudes_deg, query_latitudes_deg=QUERY_LATITUDES_DEG, query_longitudes_deg=QUERY_LONGITUDES_DEG, use_shortcuts=Fals... | <|body_start_0|>
conus_latitudes_deg, conus_longitudes_deg = conus_boundary.read_from_netcdf()
these_flags = conus_boundary.find_points_in_conus(conus_latitudes_deg=conus_latitudes_deg, conus_longitudes_deg=conus_longitudes_deg, query_latitudes_deg=QUERY_LATITUDES_DEG, query_longitudes_deg=QUERY_LONGITU... | Each method is a unit test for conus_boundary.py. | ConusBoundaryTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConusBoundaryTests:
"""Each method is a unit test for conus_boundary.py."""
def test_find_points_in_conus_no_shortcuts(self):
"""Ensures correct output from find_points_in_conus. In this case, does not use shortcuts."""
<|body_0|>
def test_find_points_in_conus_with_short... | stack_v2_sparse_classes_10k_train_001777 | 2,046 | permissive | [
{
"docstring": "Ensures correct output from find_points_in_conus. In this case, does not use shortcuts.",
"name": "test_find_points_in_conus_no_shortcuts",
"signature": "def test_find_points_in_conus_no_shortcuts(self)"
},
{
"docstring": "Ensures correct output from find_points_in_conus. In this... | 2 | stack_v2_sparse_classes_30k_val_000374 | Implement the Python class `ConusBoundaryTests` described below.
Class description:
Each method is a unit test for conus_boundary.py.
Method signatures and docstrings:
- def test_find_points_in_conus_no_shortcuts(self): Ensures correct output from find_points_in_conus. In this case, does not use shortcuts.
- def test... | Implement the Python class `ConusBoundaryTests` described below.
Class description:
Each method is a unit test for conus_boundary.py.
Method signatures and docstrings:
- def test_find_points_in_conus_no_shortcuts(self): Ensures correct output from find_points_in_conus. In this case, does not use shortcuts.
- def test... | 1835a71ababb7ad7e47bfa19e62948d466559d56 | <|skeleton|>
class ConusBoundaryTests:
"""Each method is a unit test for conus_boundary.py."""
def test_find_points_in_conus_no_shortcuts(self):
"""Ensures correct output from find_points_in_conus. In this case, does not use shortcuts."""
<|body_0|>
def test_find_points_in_conus_with_short... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConusBoundaryTests:
"""Each method is a unit test for conus_boundary.py."""
def test_find_points_in_conus_no_shortcuts(self):
"""Ensures correct output from find_points_in_conus. In this case, does not use shortcuts."""
conus_latitudes_deg, conus_longitudes_deg = conus_boundary.read_from_... | the_stack_v2_python_sparse | gewittergefahr/gg_utils/conus_boundary_test.py | thunderhoser/GewitterGefahr | train | 29 |
61f9948d1b883fbfedb6da7fe5a350094cdf5242 | [
"self.adder = Adder()\nself.subtracter = Subtracter()\nself.multiplier = Multiplier()\nself.divider = Divider()\nself.calculator = Calculator(self.adder, self.subtracter, self.multiplier, self.divider)",
"self.calculator.enter_number(0)\nwith self.assertRaises(InsufficientOperands):\n self.calculator.add()",
... | <|body_start_0|>
self.adder = Adder()
self.subtracter = Subtracter()
self.multiplier = Multiplier()
self.divider = Divider()
self.calculator = Calculator(self.adder, self.subtracter, self.multiplier, self.divider)
<|end_body_0|>
<|body_start_1|>
self.calculator.enter_num... | Class for testing the Calculator | CalculatorTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CalculatorTests:
"""Class for testing the Calculator"""
def setUp(self):
"""Configure a new Adder, Subtractor, Multiplier, and Divider to instantiate a calculator"""
<|body_0|>
def test_insufficient_operands(self):
"""At least two operands are needed."""
... | stack_v2_sparse_classes_10k_train_001778 | 3,649 | no_license | [
{
"docstring": "Configure a new Adder, Subtractor, Multiplier, and Divider to instantiate a calculator",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "At least two operands are needed.",
"name": "test_insufficient_operands",
"signature": "def test_insufficient_operan... | 6 | null | Implement the Python class `CalculatorTests` described below.
Class description:
Class for testing the Calculator
Method signatures and docstrings:
- def setUp(self): Configure a new Adder, Subtractor, Multiplier, and Divider to instantiate a calculator
- def test_insufficient_operands(self): At least two operands ar... | Implement the Python class `CalculatorTests` described below.
Class description:
Class for testing the Calculator
Method signatures and docstrings:
- def setUp(self): Configure a new Adder, Subtractor, Multiplier, and Divider to instantiate a calculator
- def test_insufficient_operands(self): At least two operands ar... | b1fea0309b3495b3e1dc167d7029bc9e4b6f00f1 | <|skeleton|>
class CalculatorTests:
"""Class for testing the Calculator"""
def setUp(self):
"""Configure a new Adder, Subtractor, Multiplier, and Divider to instantiate a calculator"""
<|body_0|>
def test_insufficient_operands(self):
"""At least two operands are needed."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CalculatorTests:
"""Class for testing the Calculator"""
def setUp(self):
"""Configure a new Adder, Subtractor, Multiplier, and Divider to instantiate a calculator"""
self.adder = Adder()
self.subtracter = Subtracter()
self.multiplier = Multiplier()
self.divider = D... | the_stack_v2_python_sparse | students/roy_t/lesson06/unittest_calculator.py | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | train | 4 |
513458306708ce9e8fb57f5bdc8e099adfab2629 | [
"Parametre.__init__(self, 'joueur', 'player')\nself.schema = '<nom_joueur>'\nself.aide_courte = 'banni définitivement un joueur'\nself.aide_longue = 'Cette commande permet de bannir définitivement un joueur. Toutefois, si le joueur est déjà banni, utiliser cette commande une nouvelle fois permet de lever le banniss... | <|body_start_0|>
Parametre.__init__(self, 'joueur', 'player')
self.schema = '<nom_joueur>'
self.aide_courte = 'banni définitivement un joueur'
self.aide_longue = 'Cette commande permet de bannir définitivement un joueur. Toutefois, si le joueur est déjà banni, utiliser cette commande une... | Commande 'bannir joueur'. | PrmJoueur | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmJoueur:
"""Commande 'bannir joueur'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Parametre.__... | stack_v2_sparse_classes_10k_train_001779 | 3,253 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Interprétation du paramètre",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001231 | Implement the Python class `PrmJoueur` described below.
Class description:
Commande 'bannir joueur'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre | Implement the Python class `PrmJoueur` described below.
Class description:
Commande 'bannir joueur'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre
<|skeleton|>
class PrmJoueur:
"""Commande 'bannir jo... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmJoueur:
"""Commande 'bannir joueur'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PrmJoueur:
"""Commande 'bannir joueur'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'joueur', 'player')
self.schema = '<nom_joueur>'
self.aide_courte = 'banni définitivement un joueur'
self.aide_longue = 'Cette commande permet de... | the_stack_v2_python_sparse | src/primaires/joueur/commandes/bannir/joueur.py | vincent-lg/tsunami | train | 5 |
d0b554282c62bd19c811832d5841482acabd6817 | [
"self._parent = parent\nself.window = gtk.Dialog(flags=gtk.DIALOG_MODAL)\nself.window.set_transient_for(self._parent.window.builder.get_object('main_window'))\nself.window.set_position(gtk.WIN_POS_CENTER_ON_PARENT)\nself.buttons = []\nfor name, icon, dialog_class in loaders.iter_loaders():\n bt = gtk.Button(name... | <|body_start_0|>
self._parent = parent
self.window = gtk.Dialog(flags=gtk.DIALOG_MODAL)
self.window.set_transient_for(self._parent.window.builder.get_object('main_window'))
self.window.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
self.buttons = []
for name, icon, dialog_cla... | rief dialog class showing buttons calling the appropriate loaders | loader_dialog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class loader_dialog:
"""rief dialog class showing buttons calling the appropriate loaders"""
def __init__(self, parent):
"""rief constructor \\param parent - gtk_view class instance"""
<|body_0|>
def button_clicked(self, button, dialog_class):
"""rief executed when ... | stack_v2_sparse_classes_10k_train_001780 | 1,726 | no_license | [
{
"docstring": "\brief constructor \\\\param parent - gtk_view class instance",
"name": "__init__",
"signature": "def __init__(self, parent)"
},
{
"docstring": "\brief executed when dialog button is clicked \\\\param button \\\\param dialog_class - dialog class given from",
"name": "button_c... | 3 | stack_v2_sparse_classes_30k_train_006921 | Implement the Python class `loader_dialog` described below.
Class description:
rief dialog class showing buttons calling the appropriate loaders
Method signatures and docstrings:
- def __init__(self, parent): rief constructor \\param parent - gtk_view class instance
- def button_clicked(self, button, dialog_class):... | Implement the Python class `loader_dialog` described below.
Class description:
rief dialog class showing buttons calling the appropriate loaders
Method signatures and docstrings:
- def __init__(self, parent): rief constructor \\param parent - gtk_view class instance
- def button_clicked(self, button, dialog_class):... | eb151afa9ee939ed7943da9eeed1e976ac816fec | <|skeleton|>
class loader_dialog:
"""rief dialog class showing buttons calling the appropriate loaders"""
def __init__(self, parent):
"""rief constructor \\param parent - gtk_view class instance"""
<|body_0|>
def button_clicked(self, button, dialog_class):
"""rief executed when ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class loader_dialog:
"""rief dialog class showing buttons calling the appropriate loaders"""
def __init__(self, parent):
"""rief constructor \\param parent - gtk_view class instance"""
self._parent = parent
self.window = gtk.Dialog(flags=gtk.DIALOG_MODAL)
self.window.set_trans... | the_stack_v2_python_sparse | src/loader_dialog.py | s9gf4ult/track-deal | train | 1 |
0f1cfd488184dd04d0106156c487fc44df5925ef | [
"n = len(words[0])\n\ndef iter_prefix(prefix):\n l = len(prefix)\n for word in words:\n if word[:l] == prefix:\n yield word\n\ndef backtrack(path, sqr):\n if len(path) == n:\n sqr.append(path[:])\n return\n i = len(path)\n prefix = ''.join([w[i] for w in path])\n fo... | <|body_start_0|>
n = len(words[0])
def iter_prefix(prefix):
l = len(prefix)
for word in words:
if word[:l] == prefix:
yield word
def backtrack(path, sqr):
if len(path) == n:
sqr.append(path[:])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordSquares(self, words: List[str]) -> List[List[str]]:
"""time O(N*L^(N*L)) space O(L)"""
<|body_0|>
def wordSquares(self, words: List[str]) -> List[List[str]]:
"""time O(N*26^L) space O(N*L)"""
<|body_1|>
def wordSquares(self, words: List... | stack_v2_sparse_classes_10k_train_001781 | 4,307 | no_license | [
{
"docstring": "time O(N*L^(N*L)) space O(L)",
"name": "wordSquares",
"signature": "def wordSquares(self, words: List[str]) -> List[List[str]]"
},
{
"docstring": "time O(N*26^L) space O(N*L)",
"name": "wordSquares",
"signature": "def wordSquares(self, words: List[str]) -> List[List[str]]... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordSquares(self, words: List[str]) -> List[List[str]]: time O(N*L^(N*L)) space O(L)
- def wordSquares(self, words: List[str]) -> List[List[str]]: time O(N*26^L) space O(N*L)... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordSquares(self, words: List[str]) -> List[List[str]]: time O(N*L^(N*L)) space O(L)
- def wordSquares(self, words: List[str]) -> List[List[str]]: time O(N*26^L) space O(N*L)... | 6ff1941ff213a843013100ac7033e2d4f90fbd6a | <|skeleton|>
class Solution:
def wordSquares(self, words: List[str]) -> List[List[str]]:
"""time O(N*L^(N*L)) space O(L)"""
<|body_0|>
def wordSquares(self, words: List[str]) -> List[List[str]]:
"""time O(N*26^L) space O(N*L)"""
<|body_1|>
def wordSquares(self, words: List... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def wordSquares(self, words: List[str]) -> List[List[str]]:
"""time O(N*L^(N*L)) space O(L)"""
n = len(words[0])
def iter_prefix(prefix):
l = len(prefix)
for word in words:
if word[:l] == prefix:
yield word
... | the_stack_v2_python_sparse | Leetcode 0425. Word Squares.py | Chaoran-sjsu/leetcode | train | 0 | |
3f62fb6b54a88cda376cdbe83dcf2c24e444bd61 | [
"super().__init__()\nself.num_blocks = num_blocks\nself.num_classes = num_classes\nblocks = []\nfor i in range(self.num_blocks):\n subsample = i == 0\n blocks.append(ResNetBlock(c_in=64 if not subsample else 32, act_fn=nn.ReLU(), subsample=subsample, c_out=64))\nself.blocks = nn.Sequential(*blocks)\nself.outp... | <|body_start_0|>
super().__init__()
self.num_blocks = num_blocks
self.num_classes = num_classes
blocks = []
for i in range(self.num_blocks):
subsample = i == 0
blocks.append(ResNetBlock(c_in=64 if not subsample else 32, act_fn=nn.ReLU(), subsample=subsampl... | ResNet decoder model | Resnet_Decoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Resnet_Decoder:
"""ResNet decoder model"""
def __init__(self, num_blocks, num_classes):
"""Decoder module of the network Inputs: num_block - Number of ResNet blocks. num_classes - Number of classes of images."""
<|body_0|>
def forward(self, encoded_batch, thetas):
... | stack_v2_sparse_classes_10k_train_001782 | 17,101 | no_license | [
{
"docstring": "Decoder module of the network Inputs: num_block - Number of ResNet blocks. num_classes - Number of classes of images.",
"name": "__init__",
"signature": "def __init__(self, num_blocks, num_classes)"
},
{
"docstring": "Forward pass of the decoder. Inputs: encoded_batch - Input bat... | 2 | stack_v2_sparse_classes_30k_train_002228 | Implement the Python class `Resnet_Decoder` described below.
Class description:
ResNet decoder model
Method signatures and docstrings:
- def __init__(self, num_blocks, num_classes): Decoder module of the network Inputs: num_block - Number of ResNet blocks. num_classes - Number of classes of images.
- def forward(self... | Implement the Python class `Resnet_Decoder` described below.
Class description:
ResNet decoder model
Method signatures and docstrings:
- def __init__(self, num_blocks, num_classes): Decoder module of the network Inputs: num_block - Number of ResNet blocks. num_classes - Number of classes of images.
- def forward(self... | 0b65d43a9bb5e70d7e4e3fcd322b47b173e16fa6 | <|skeleton|>
class Resnet_Decoder:
"""ResNet decoder model"""
def __init__(self, num_blocks, num_classes):
"""Decoder module of the network Inputs: num_block - Number of ResNet blocks. num_classes - Number of classes of images."""
<|body_0|>
def forward(self, encoded_batch, thetas):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Resnet_Decoder:
"""ResNet decoder model"""
def __init__(self, num_blocks, num_classes):
"""Decoder module of the network Inputs: num_block - Number of ResNet blocks. num_classes - Number of classes of images."""
super().__init__()
self.num_blocks = num_blocks
self.num_clas... | the_stack_v2_python_sparse | models/resnet/complex_resnet.py | RamonDijkstra/AI-FACT | train | 0 |
f1a89d5c246a0afb97410897c8cd8c574eeb1d02 | [
"self.type = sensor_type\nself.serial = serial\nself.mgr = mgr\nself._attr_name = f'{mgr.name(serial)} {SENSOR_TYPES[sensor_type]}'\nself._attr_native_unit_of_measurement = UnitOfTemperature.FAHRENHEIT\nself._attr_unique_id = f'{serial}-{sensor_type}'\nself._attr_device_class = SensorDeviceClass.TEMPERATURE\nself.u... | <|body_start_0|>
self.type = sensor_type
self.serial = serial
self.mgr = mgr
self._attr_name = f'{mgr.name(serial)} {SENSOR_TYPES[sensor_type]}'
self._attr_native_unit_of_measurement = UnitOfTemperature.FAHRENHEIT
self._attr_unique_id = f'{serial}-{sensor_type}'
s... | Implementation of a thermoworks smoke sensor. | ThermoworksSmokeSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThermoworksSmokeSensor:
"""Implementation of a thermoworks smoke sensor."""
def __init__(self, sensor_type, serial, mgr):
"""Initialize the sensor."""
<|body_0|>
def update_unit(self):
"""Set the units from the data."""
<|body_1|>
def update(self) ->... | stack_v2_sparse_classes_10k_train_001783 | 5,552 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, sensor_type, serial, mgr)"
},
{
"docstring": "Set the units from the data.",
"name": "update_unit",
"signature": "def update_unit(self)"
},
{
"docstring": "Get the monitored data from fi... | 3 | null | Implement the Python class `ThermoworksSmokeSensor` described below.
Class description:
Implementation of a thermoworks smoke sensor.
Method signatures and docstrings:
- def __init__(self, sensor_type, serial, mgr): Initialize the sensor.
- def update_unit(self): Set the units from the data.
- def update(self) -> Non... | Implement the Python class `ThermoworksSmokeSensor` described below.
Class description:
Implementation of a thermoworks smoke sensor.
Method signatures and docstrings:
- def __init__(self, sensor_type, serial, mgr): Initialize the sensor.
- def update_unit(self): Set the units from the data.
- def update(self) -> Non... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ThermoworksSmokeSensor:
"""Implementation of a thermoworks smoke sensor."""
def __init__(self, sensor_type, serial, mgr):
"""Initialize the sensor."""
<|body_0|>
def update_unit(self):
"""Set the units from the data."""
<|body_1|>
def update(self) ->... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ThermoworksSmokeSensor:
"""Implementation of a thermoworks smoke sensor."""
def __init__(self, sensor_type, serial, mgr):
"""Initialize the sensor."""
self.type = sensor_type
self.serial = serial
self.mgr = mgr
self._attr_name = f'{mgr.name(serial)} {SENSOR_TYPES[s... | the_stack_v2_python_sparse | homeassistant/components/thermoworks_smoke/sensor.py | home-assistant/core | train | 35,501 |
ea1d26246f8b62aa32ba472c0cb190c7434f78c0 | [
"@lru_cache(None)\ndef dp(i, j):\n if i == len(nums1) or j == len(nums2):\n return 0\n if nums1[i] == nums2[j]:\n return 1 + dp(i + 1, j + 1)\n return 0\nreturn max((dp(i, j) for i in range(len(nums1)) for j in range(len(nums2))))",
"dp = [[0] * (len(nums2) + 1) for _ in range(len(nums1) + ... | <|body_start_0|>
@lru_cache(None)
def dp(i, j):
if i == len(nums1) or j == len(nums2):
return 0
if nums1[i] == nums2[j]:
return 1 + dp(i + 1, j + 1)
return 0
return max((dp(i, j) for i in range(len(nums1)) for j in range(len(num... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
"""09/03/2020 01:25 DP with recursion Time complexity: O(n^2) Space complexity: O(n^2)"""
<|body_0|>
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
"""08/12/2021 01:32 DP bot... | stack_v2_sparse_classes_10k_train_001784 | 7,237 | no_license | [
{
"docstring": "09/03/2020 01:25 DP with recursion Time complexity: O(n^2) Space complexity: O(n^2)",
"name": "findLength",
"signature": "def findLength(self, nums1: List[int], nums2: List[int]) -> int"
},
{
"docstring": "08/12/2021 01:32 DP bottom up",
"name": "findLength",
"signature":... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLength(self, nums1: List[int], nums2: List[int]) -> int: 09/03/2020 01:25 DP with recursion Time complexity: O(n^2) Space complexity: O(n^2)
- def findLength(self, nums1:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLength(self, nums1: List[int], nums2: List[int]) -> int: 09/03/2020 01:25 DP with recursion Time complexity: O(n^2) Space complexity: O(n^2)
- def findLength(self, nums1:... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
"""09/03/2020 01:25 DP with recursion Time complexity: O(n^2) Space complexity: O(n^2)"""
<|body_0|>
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
"""08/12/2021 01:32 DP bot... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
"""09/03/2020 01:25 DP with recursion Time complexity: O(n^2) Space complexity: O(n^2)"""
@lru_cache(None)
def dp(i, j):
if i == len(nums1) or j == len(nums2):
return 0
if... | the_stack_v2_python_sparse | leetcode/solved/718_Maximum_Length_of_Repeated_Subarray/solution.py | sungminoh/algorithms | train | 0 | |
b1393f51b2a1d4ac04f47d516bc774a4187db7e8 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn TargetedManagedAppConfiguration()",
"from .managed_app_configuration import ManagedAppConfiguration\nfrom .managed_app_policy_deployment_summary import ManagedAppPolicyDeploymentSummary\nfrom .managed_mobile_app import ManagedMobileApp... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return TargetedManagedAppConfiguration()
<|end_body_0|>
<|body_start_1|>
from .managed_app_configuration import ManagedAppConfiguration
from .managed_app_policy_deployment_summary import Manage... | Configuration used to deliver a set of custom settings as-is to all users in the targeted security group | TargetedManagedAppConfiguration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TargetedManagedAppConfiguration:
"""Configuration used to deliver a set of custom settings as-is to all users in the targeted security group"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TargetedManagedAppConfiguration:
"""Creates a new instance of t... | stack_v2_sparse_classes_10k_train_001785 | 4,444 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: TargetedManagedAppConfiguration",
"name": "create_from_discriminator_value",
"signature": "def create_from_d... | 3 | stack_v2_sparse_classes_30k_val_000159 | Implement the Python class `TargetedManagedAppConfiguration` described below.
Class description:
Configuration used to deliver a set of custom settings as-is to all users in the targeted security group
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Tar... | Implement the Python class `TargetedManagedAppConfiguration` described below.
Class description:
Configuration used to deliver a set of custom settings as-is to all users in the targeted security group
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Tar... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class TargetedManagedAppConfiguration:
"""Configuration used to deliver a set of custom settings as-is to all users in the targeted security group"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TargetedManagedAppConfiguration:
"""Creates a new instance of t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TargetedManagedAppConfiguration:
"""Configuration used to deliver a set of custom settings as-is to all users in the targeted security group"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TargetedManagedAppConfiguration:
"""Creates a new instance of the appropriat... | the_stack_v2_python_sparse | msgraph/generated/models/targeted_managed_app_configuration.py | microsoftgraph/msgraph-sdk-python | train | 135 |
2623fb0a574a519ca52d50df8f17aee09572fbac | [
"self._directive: dict[str, Any] = request[API_DIRECTIVE]\nself.namespace: str = self._directive[API_HEADER]['namespace']\nself.name: str = self._directive[API_HEADER]['name']\nself.payload: dict[str, Any] = self._directive[API_PAYLOAD]\nself.has_endpoint: bool = API_ENDPOINT in self._directive\nself.instance = Non... | <|body_start_0|>
self._directive: dict[str, Any] = request[API_DIRECTIVE]
self.namespace: str = self._directive[API_HEADER]['namespace']
self.name: str = self._directive[API_HEADER]['name']
self.payload: dict[str, Any] = self._directive[API_PAYLOAD]
self.has_endpoint: bool = API_... | An incoming Alexa directive. | AlexaDirective | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlexaDirective:
"""An incoming Alexa directive."""
def __init__(self, request: dict[str, Any]) -> None:
"""Initialize a directive."""
<|body_0|>
def load_entity(self, hass: HomeAssistant, config: AbstractConfig) -> None:
"""Set attributes related to the entity fo... | stack_v2_sparse_classes_10k_train_001786 | 17,851 | permissive | [
{
"docstring": "Initialize a directive.",
"name": "__init__",
"signature": "def __init__(self, request: dict[str, Any]) -> None"
},
{
"docstring": "Set attributes related to the entity for this request. Sets these attributes when self.has_endpoint is True: - entity - entity_id - endpoint - insta... | 4 | null | Implement the Python class `AlexaDirective` described below.
Class description:
An incoming Alexa directive.
Method signatures and docstrings:
- def __init__(self, request: dict[str, Any]) -> None: Initialize a directive.
- def load_entity(self, hass: HomeAssistant, config: AbstractConfig) -> None: Set attributes rel... | Implement the Python class `AlexaDirective` described below.
Class description:
An incoming Alexa directive.
Method signatures and docstrings:
- def __init__(self, request: dict[str, Any]) -> None: Initialize a directive.
- def load_entity(self, hass: HomeAssistant, config: AbstractConfig) -> None: Set attributes rel... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class AlexaDirective:
"""An incoming Alexa directive."""
def __init__(self, request: dict[str, Any]) -> None:
"""Initialize a directive."""
<|body_0|>
def load_entity(self, hass: HomeAssistant, config: AbstractConfig) -> None:
"""Set attributes related to the entity fo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AlexaDirective:
"""An incoming Alexa directive."""
def __init__(self, request: dict[str, Any]) -> None:
"""Initialize a directive."""
self._directive: dict[str, Any] = request[API_DIRECTIVE]
self.namespace: str = self._directive[API_HEADER]['namespace']
self.name: str = se... | the_stack_v2_python_sparse | homeassistant/components/alexa/state_report.py | home-assistant/core | train | 35,501 |
f3a47549ddced74d1722e2481f073dcab4de5db0 | [
"self.host = host\nself.port = 0\nself.db = db\nself.user = ''\nself.password = ''\nself.sql = ''",
"self.conn = connect(host=self.host, port=self.port, db=self.db, user=self.user, password=self.password)\nself.cursor = self.conn.cursor()\nself.sql = 'SELECT * FROM {}'.format(table_name)\nself.cursor.execute(self... | <|body_start_0|>
self.host = host
self.port = 0
self.db = db
self.user = ''
self.password = ''
self.sql = ''
<|end_body_0|>
<|body_start_1|>
self.conn = connect(host=self.host, port=self.port, db=self.db, user=self.user, password=self.password)
self.curso... | SQLController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SQLController:
def __init__(self, host='', port=0, db='', user='', password=''):
"""Input parameters are host (string), port (integer), db (string), user (string), and password(can be left blank) (string)"""
<|body_0|>
def select_all(self, table_name=''):
"""Method f... | stack_v2_sparse_classes_10k_train_001787 | 4,703 | no_license | [
{
"docstring": "Input parameters are host (string), port (integer), db (string), user (string), and password(can be left blank) (string)",
"name": "__init__",
"signature": "def __init__(self, host='', port=0, db='', user='', password='')"
},
{
"docstring": "Method for retrieving all values Input... | 4 | null | Implement the Python class `SQLController` described below.
Class description:
Implement the SQLController class.
Method signatures and docstrings:
- def __init__(self, host='', port=0, db='', user='', password=''): Input parameters are host (string), port (integer), db (string), user (string), and password(can be le... | Implement the Python class `SQLController` described below.
Class description:
Implement the SQLController class.
Method signatures and docstrings:
- def __init__(self, host='', port=0, db='', user='', password=''): Input parameters are host (string), port (integer), db (string), user (string), and password(can be le... | 2a5f3d29c7529bc917d4ff9be03af30ec23948a5 | <|skeleton|>
class SQLController:
def __init__(self, host='', port=0, db='', user='', password=''):
"""Input parameters are host (string), port (integer), db (string), user (string), and password(can be left blank) (string)"""
<|body_0|>
def select_all(self, table_name=''):
"""Method f... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SQLController:
def __init__(self, host='', port=0, db='', user='', password=''):
"""Input parameters are host (string), port (integer), db (string), user (string), and password(can be left blank) (string)"""
self.host = host
self.port = 0
self.db = db
self.user = ''
... | the_stack_v2_python_sparse | pyth3/mysql/py_my_basic.py | babywyrm/sysadmin | train | 10 | |
681963173f6c7101b5c9e3661089209d7d53d3aa | [
"if root is None:\n return 0\nlength1 = None\nlength2 = None\nif root.left is not None:\n length1 = self.maxPathSum(root.left)\nif root.right is not None:\n length2 = self.maxPathSum(root.right)\nlength3 = root.val + max(self.max_path(root.left), 0) + max(self.max_path(root.right), 0)\npool = []\nif length... | <|body_start_0|>
if root is None:
return 0
length1 = None
length2 = None
if root.left is not None:
length1 = self.maxPathSum(root.left)
if root.right is not None:
length2 = self.maxPathSum(root.right)
length3 = root.val + max(self.max_p... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxPathSum(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def max_path(self, root):
"""以root为根节点的树的最大的路径长度 :param root: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root is None:
return 0
... | stack_v2_sparse_classes_10k_train_001788 | 2,367 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "maxPathSum",
"signature": "def maxPathSum(self, root)"
},
{
"docstring": "以root为根节点的树的最大的路径长度 :param root: :return:",
"name": "max_path",
"signature": "def max_path(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxPathSum(self, root): :type root: TreeNode :rtype: int
- def max_path(self, root): 以root为根节点的树的最大的路径长度 :param root: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxPathSum(self, root): :type root: TreeNode :rtype: int
- def max_path(self, root): 以root为根节点的树的最大的路径长度 :param root: :return:
<|skeleton|>
class Solution:
def maxPathS... | 163b376acab84e28c74cb784d10fe39f11510921 | <|skeleton|>
class Solution:
def maxPathSum(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def max_path(self, root):
"""以root为根节点的树的最大的路径长度 :param root: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxPathSum(self, root):
""":type root: TreeNode :rtype: int"""
if root is None:
return 0
length1 = None
length2 = None
if root.left is not None:
length1 = self.maxPathSum(root.left)
if root.right is not None:
len... | the_stack_v2_python_sparse | code/124. Binary Tree Maximum Path Sum(H)/124. Binary Tree Maximum Path Sum(H).py | cathyxingchang/leetcode | train | 2 | |
3fc027822bc4b20546b08fb940bf5de65ad5b0bd | [
"if self.error_message:\n return '%s: %s' % (self.__class__.__name__, self.messageFormat(self.error_message))\nelse:\n return '%s: %s' % (self.__class__.__name__, self.messageFormat())",
"if template is None:\n template = self.DEFAULTTEMPLATE\nline, lineChar = self.getLineCoordinate()\nvariables = {'prod... | <|body_start_0|>
if self.error_message:
return '%s: %s' % (self.__class__.__name__, self.messageFormat(self.error_message))
else:
return '%s: %s' % (self.__class__.__name__, self.messageFormat())
<|end_body_0|>
<|body_start_1|>
if template is None:
template =... | Sub-class of SyntaxError for use by SimpleParse parsers Every instance will have the following attributes: buffer -- pointer to the source buffer position -- integer position in buffer where error occured or -1 production -- the production which failed expected -- string (currently taken from grammar) describing what p... | ParserSyntaxError | [
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LGPL-2.1-or-later",
"GPL-3.0-only",
"LGPL-2.0-or-later",
"GPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParserSyntaxError:
"""Sub-class of SyntaxError for use by SimpleParse parsers Every instance will have the following attributes: buffer -- pointer to the source buffer position -- integer position in buffer where error occured or -1 production -- the production which failed expected -- string (cu... | stack_v2_sparse_classes_10k_train_001789 | 2,101 | permissive | [
{
"docstring": "Create a string representation of the error",
"name": "__str__",
"signature": "def __str__(self)"
},
{
"docstring": "Create a default message for this syntax error",
"name": "messageFormat",
"signature": "def messageFormat(self, template=None)"
},
{
"docstring": "... | 3 | null | Implement the Python class `ParserSyntaxError` described below.
Class description:
Sub-class of SyntaxError for use by SimpleParse parsers Every instance will have the following attributes: buffer -- pointer to the source buffer position -- integer position in buffer where error occured or -1 production -- the product... | Implement the Python class `ParserSyntaxError` described below.
Class description:
Sub-class of SyntaxError for use by SimpleParse parsers Every instance will have the following attributes: buffer -- pointer to the source buffer position -- integer position in buffer where error occured or -1 production -- the product... | 7f600ad153270feff12aa7aa86d7ed0a49ebc71c | <|skeleton|>
class ParserSyntaxError:
"""Sub-class of SyntaxError for use by SimpleParse parsers Every instance will have the following attributes: buffer -- pointer to the source buffer position -- integer position in buffer where error occured or -1 production -- the production which failed expected -- string (cu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ParserSyntaxError:
"""Sub-class of SyntaxError for use by SimpleParse parsers Every instance will have the following attributes: buffer -- pointer to the source buffer position -- integer position in buffer where error occured or -1 production -- the production which failed expected -- string (currently taken... | the_stack_v2_python_sparse | pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/simpleparse/error.py | alexus37/AugmentedRealityChess | train | 1 |
a99f82655c676f4e8b30b2b00a3c005ded995c4f | [
"try:\n set_ = oai_provider_set_api.get_by_id(set_id)\n serializer = serializers.OaiProviderSetSerializer(set_, context={'request': request})\n return Response(serializer.data, status=status.HTTP_200_OK)\nexcept exceptions.DoesNotExist:\n content = OaiPmhMessage.get_message_labelled('No Set found with t... | <|body_start_0|>
try:
set_ = oai_provider_set_api.get_by_id(set_id)
serializer = serializers.OaiProviderSetSerializer(set_, context={'request': request})
return Response(serializer.data, status=status.HTTP_200_OK)
except exceptions.DoesNotExist:
content = ... | Set Detail | SetDetail | [
"BSD-3-Clause",
"Apache-2.0",
"MIT",
"NIST-Software"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SetDetail:
"""Set Detail"""
def get(self, request, set_id):
"""Get a OaiProviderSet Args: request: HTTP request set_id: ObjectId Returns: - code: 200 content: Registry - code: 404 content: Object was not found - code: 500 content: Internal server error"""
<|body_0|>
def ... | stack_v2_sparse_classes_10k_train_001790 | 7,772 | permissive | [
{
"docstring": "Get a OaiProviderSet Args: request: HTTP request set_id: ObjectId Returns: - code: 200 content: Registry - code: 404 content: Object was not found - code: 500 content: Internal server error",
"name": "get",
"signature": "def get(self, request, set_id)"
},
{
"docstring": "Delete a... | 3 | stack_v2_sparse_classes_30k_train_000063 | Implement the Python class `SetDetail` described below.
Class description:
Set Detail
Method signatures and docstrings:
- def get(self, request, set_id): Get a OaiProviderSet Args: request: HTTP request set_id: ObjectId Returns: - code: 200 content: Registry - code: 404 content: Object was not found - code: 500 conte... | Implement the Python class `SetDetail` described below.
Class description:
Set Detail
Method signatures and docstrings:
- def get(self, request, set_id): Get a OaiProviderSet Args: request: HTTP request set_id: ObjectId Returns: - code: 200 content: Registry - code: 404 content: Object was not found - code: 500 conte... | 1d2380d99c00c96a7c5ebdf8513b8ad5e8926d9f | <|skeleton|>
class SetDetail:
"""Set Detail"""
def get(self, request, set_id):
"""Get a OaiProviderSet Args: request: HTTP request set_id: ObjectId Returns: - code: 200 content: Registry - code: 404 content: Object was not found - code: 500 content: Internal server error"""
<|body_0|>
def ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SetDetail:
"""Set Detail"""
def get(self, request, set_id):
"""Get a OaiProviderSet Args: request: HTTP request set_id: ObjectId Returns: - code: 200 content: Registry - code: 404 content: Object was not found - code: 500 content: Internal server error"""
try:
set_ = oai_provi... | the_stack_v2_python_sparse | core_oaipmh_provider_app/rest/oai_provider_set/views.py | usnistgov/core_oaipmh_provider_app | train | 0 |
0bbf15f3c8623d96deaef7161dc9a8c071aa731e | [
"m, n = (len(grid), len(grid[0]))\nstart = None\ncnt = 0\nfor i in range(m):\n for j in range(n):\n if grid[i][j] == 0:\n cnt += 1\n elif grid[i][j] == 1:\n start = (i, j)\n\ndef dfs(i, j, c=0):\n if grid[i][j] == 2 and c == cnt + 1:\n return 1\n saved = grid[i][j... | <|body_start_0|>
m, n = (len(grid), len(grid[0]))
start = None
cnt = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 0:
cnt += 1
elif grid[i][j] == 1:
start = (i, j)
def dfs(i, j, c=0):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
"""Nov 13, 2021 10:23 DFS"""
<|body_0|>
def uniquePathsIII(self, grid: List[List[int]]) -> int:
"""Feb 19, 2023 22:45"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m, n = (len(grid)... | stack_v2_sparse_classes_10k_train_001791 | 3,805 | no_license | [
{
"docstring": "Nov 13, 2021 10:23 DFS",
"name": "uniquePathsIII",
"signature": "def uniquePathsIII(self, grid: List[List[int]]) -> int"
},
{
"docstring": "Feb 19, 2023 22:45",
"name": "uniquePathsIII",
"signature": "def uniquePathsIII(self, grid: List[List[int]]) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_006330 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePathsIII(self, grid: List[List[int]]) -> int: Nov 13, 2021 10:23 DFS
- def uniquePathsIII(self, grid: List[List[int]]) -> int: Feb 19, 2023 22:45 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePathsIII(self, grid: List[List[int]]) -> int: Nov 13, 2021 10:23 DFS
- def uniquePathsIII(self, grid: List[List[int]]) -> int: Feb 19, 2023 22:45
<|skeleton|>
class So... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
"""Nov 13, 2021 10:23 DFS"""
<|body_0|>
def uniquePathsIII(self, grid: List[List[int]]) -> int:
"""Feb 19, 2023 22:45"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
"""Nov 13, 2021 10:23 DFS"""
m, n = (len(grid), len(grid[0]))
start = None
cnt = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 0:
cnt += 1
... | the_stack_v2_python_sparse | leetcode/solved/1022_Unique_Paths_III/solution.py | sungminoh/algorithms | train | 0 | |
a4704e7c68fc14882c59a66a444b6bf88b988269 | [
"assert icon_style in IconFactory._convert_styles\nself._view = view\nself._icon_style = icon_style\nself._icon_factory = icon_factory\nself._name = name\nself._debug = debug",
"region, color = value\nicon_path = self._icon_factory.get_icon_path(self._icon_style, color)\nregion_key = GutterIconsColorHighlighter.r... | <|body_start_0|>
assert icon_style in IconFactory._convert_styles
self._view = view
self._icon_style = icon_style
self._icon_factory = icon_factory
self._name = name
self._debug = debug
<|end_body_0|>
<|body_start_1|>
region, color = value
icon_path = sel... | A color highlighter that uses gutter icons to highlight colors. | GutterIconsColorHighlighter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GutterIconsColorHighlighter:
"""A color highlighter that uses gutter icons to highlight colors."""
def __init__(self, view, icon_style, icon_factory, name, debug):
"""Init a GutterIconsColorHighlighter. Arguments: - view - a view to highlight colors in. - icon_style - the icon style.... | stack_v2_sparse_classes_10k_train_001792 | 7,583 | no_license | [
{
"docstring": "Init a GutterIconsColorHighlighter. Arguments: - view - a view to highlight colors in. - icon_style - the icon style. - icon_factory - the icon factory to create icons with. - name - the name of the color highlighter. - debug - whether to enable debug mode.",
"name": "__init__",
"signatu... | 3 | stack_v2_sparse_classes_30k_train_005571 | Implement the Python class `GutterIconsColorHighlighter` described below.
Class description:
A color highlighter that uses gutter icons to highlight colors.
Method signatures and docstrings:
- def __init__(self, view, icon_style, icon_factory, name, debug): Init a GutterIconsColorHighlighter. Arguments: - view - a vi... | Implement the Python class `GutterIconsColorHighlighter` described below.
Class description:
A color highlighter that uses gutter icons to highlight colors.
Method signatures and docstrings:
- def __init__(self, view, icon_style, icon_factory, name, debug): Init a GutterIconsColorHighlighter. Arguments: - view - a vi... | 83d469af3fc11d1aedb5193976ef84c59b595d6c | <|skeleton|>
class GutterIconsColorHighlighter:
"""A color highlighter that uses gutter icons to highlight colors."""
def __init__(self, view, icon_style, icon_factory, name, debug):
"""Init a GutterIconsColorHighlighter. Arguments: - view - a view to highlight colors in. - icon_style - the icon style.... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GutterIconsColorHighlighter:
"""A color highlighter that uses gutter icons to highlight colors."""
def __init__(self, view, icon_style, icon_factory, name, debug):
"""Init a GutterIconsColorHighlighter. Arguments: - view - a view to highlight colors in. - icon_style - the icon style. - icon_facto... | the_stack_v2_python_sparse | .config/sublime-text-2/Packages/Color Highlighter/gutter_icons_color_highlighter.py | Wallkerock/X-setup | train | 10 |
b50876a373beea5b55bfe702cfb558dd9b2d6665 | [
"self.session = session\nself.summary_placeholders = {}\nself.summary_ops = {}\nself.train_summary_writer = tf.summary.FileWriter(os.path.join(log_path, 'train'), self.session.graph)\nself.test_summary_writer = tf.summary.FileWriter(os.path.join(log_path, 'test'))",
"summary_writer = self.train_summary_writer if ... | <|body_start_0|>
self.session = session
self.summary_placeholders = {}
self.summary_ops = {}
self.train_summary_writer = tf.summary.FileWriter(os.path.join(log_path, 'train'), self.session.graph)
self.test_summary_writer = tf.summary.FileWriter(os.path.join(log_path, 'test'))
<|e... | TensorLogger object helps to log the training/testing progress in Tensorboard | TensorLogger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TensorLogger:
"""TensorLogger object helps to log the training/testing progress in Tensorboard"""
def __init__(self, log_path, session):
""":param str log_path: path where we keep the logs :param tf.Session session: tensorflow session"""
<|body_0|>
def log_scalars(self, ... | stack_v2_sparse_classes_10k_train_001793 | 2,167 | no_license | [
{
"docstring": ":param str log_path: path where we keep the logs :param tf.Session session: tensorflow session",
"name": "__init__",
"signature": "def __init__(self, log_path, session)"
},
{
"docstring": "Logs the scalars of decoded string in Tensorboard :param int step: the step of the summary ... | 2 | stack_v2_sparse_classes_30k_train_001333 | Implement the Python class `TensorLogger` described below.
Class description:
TensorLogger object helps to log the training/testing progress in Tensorboard
Method signatures and docstrings:
- def __init__(self, log_path, session): :param str log_path: path where we keep the logs :param tf.Session session: tensorflow ... | Implement the Python class `TensorLogger` described below.
Class description:
TensorLogger object helps to log the training/testing progress in Tensorboard
Method signatures and docstrings:
- def __init__(self, log_path, session): :param str log_path: path where we keep the logs :param tf.Session session: tensorflow ... | 6793d8f471038b2401df2376aa7a8d97b440927a | <|skeleton|>
class TensorLogger:
"""TensorLogger object helps to log the training/testing progress in Tensorboard"""
def __init__(self, log_path, session):
""":param str log_path: path where we keep the logs :param tf.Session session: tensorflow session"""
<|body_0|>
def log_scalars(self, ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TensorLogger:
"""TensorLogger object helps to log the training/testing progress in Tensorboard"""
def __init__(self, log_path, session):
""":param str log_path: path where we keep the logs :param tf.Session session: tensorflow session"""
self.session = session
self.summary_placeho... | the_stack_v2_python_sparse | object_detection/utils/tensor_logger.py | zvadaadam/traffic-object-detection | train | 0 |
a6cb4bd1c560abaad1a0deaffc2214891c6453fa | [
"super(RecyclingEmbedder, self).__init__()\nself.c_m = c_m\nself.c_z = c_z\nself.min_bin = min_bin\nself.max_bin = max_bin\nself.no_bins = no_bins\nself.inf = inf\nself.linear = Linear(self.no_bins, self.c_z)\nself.layer_norm_m = LayerNorm(self.c_m)\nself.layer_norm_z = LayerNorm(self.c_z)",
"m_update = self.laye... | <|body_start_0|>
super(RecyclingEmbedder, self).__init__()
self.c_m = c_m
self.c_z = c_z
self.min_bin = min_bin
self.max_bin = max_bin
self.no_bins = no_bins
self.inf = inf
self.linear = Linear(self.no_bins, self.c_z)
self.layer_norm_m = LayerNorm(... | Embeds the output of an iteration of the model for recycling. Implements Algorithm 32. | RecyclingEmbedder | [
"Apache-2.0",
"CC-BY-4.0",
"LicenseRef-scancode-other-permissive",
"CC-BY-NC-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecyclingEmbedder:
"""Embeds the output of an iteration of the model for recycling. Implements Algorithm 32."""
def __init__(self, c_m: int, c_z: int, min_bin: float, max_bin: float, no_bins: int, inf: float=100000000.0, **kwargs):
"""Args: c_m: MSA channel dimension c_z: Pair embedd... | stack_v2_sparse_classes_10k_train_001794 | 9,577 | permissive | [
{
"docstring": "Args: c_m: MSA channel dimension c_z: Pair embedding channel dimension min_bin: Smallest distogram bin (Angstroms) max_bin: Largest distogram bin (Angstroms) no_bins: Number of distogram bins",
"name": "__init__",
"signature": "def __init__(self, c_m: int, c_z: int, min_bin: float, max_b... | 2 | stack_v2_sparse_classes_30k_train_001329 | Implement the Python class `RecyclingEmbedder` described below.
Class description:
Embeds the output of an iteration of the model for recycling. Implements Algorithm 32.
Method signatures and docstrings:
- def __init__(self, c_m: int, c_z: int, min_bin: float, max_bin: float, no_bins: int, inf: float=100000000.0, **k... | Implement the Python class `RecyclingEmbedder` described below.
Class description:
Embeds the output of an iteration of the model for recycling. Implements Algorithm 32.
Method signatures and docstrings:
- def __init__(self, c_m: int, c_z: int, min_bin: float, max_bin: float, no_bins: int, inf: float=100000000.0, **k... | 2134cc09b3994b6280e6e3c569dd7d761e4da7a0 | <|skeleton|>
class RecyclingEmbedder:
"""Embeds the output of an iteration of the model for recycling. Implements Algorithm 32."""
def __init__(self, c_m: int, c_z: int, min_bin: float, max_bin: float, no_bins: int, inf: float=100000000.0, **kwargs):
"""Args: c_m: MSA channel dimension c_z: Pair embedd... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RecyclingEmbedder:
"""Embeds the output of an iteration of the model for recycling. Implements Algorithm 32."""
def __init__(self, c_m: int, c_z: int, min_bin: float, max_bin: float, no_bins: int, inf: float=100000000.0, **kwargs):
"""Args: c_m: MSA channel dimension c_z: Pair embedding channel d... | the_stack_v2_python_sparse | openfold/model/embedders.py | aqlaboratory/openfold | train | 2,033 |
922779d62712c10b4d0423cb4dce0b5fe6ed2fe6 | [
"creds_list = self._client.list(user.id)\nif check:\n assert_that(creds_list, is_not(empty()))\nreturn creds_list",
"credentials = self._client.create(user_id=user.id, project_id=project.id)\nif check:\n self.check_presence(credentials)\n assert_that(credentials, has_properties(user_id=user.id, tenant_id... | <|body_start_0|>
creds_list = self._client.list(user.id)
if check:
assert_that(creds_list, is_not(empty()))
return creds_list
<|end_body_0|>
<|body_start_1|>
credentials = self._client.create(user_id=user.id, project_id=project.id)
if check:
self.check_pr... | Ec2 credentials steps | Ec2Steps | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ec2Steps:
"""Ec2 credentials steps"""
def list(self, user, check=True):
"""Step to list all ec2 credentials. Args: user (object): user check (bool): flag whether to check step or not Returns: keystoneclient.v3.ec2.Ec2: list of ec2 credentials Raises: AssertionError: if check failed""... | stack_v2_sparse_classes_10k_train_001795 | 3,590 | no_license | [
{
"docstring": "Step to list all ec2 credentials. Args: user (object): user check (bool): flag whether to check step or not Returns: keystoneclient.v3.ec2.Ec2: list of ec2 credentials Raises: AssertionError: if check failed",
"name": "list",
"signature": "def list(self, user, check=True)"
},
{
"... | 4 | null | Implement the Python class `Ec2Steps` described below.
Class description:
Ec2 credentials steps
Method signatures and docstrings:
- def list(self, user, check=True): Step to list all ec2 credentials. Args: user (object): user check (bool): flag whether to check step or not Returns: keystoneclient.v3.ec2.Ec2: list of ... | Implement the Python class `Ec2Steps` described below.
Class description:
Ec2 credentials steps
Method signatures and docstrings:
- def list(self, user, check=True): Step to list all ec2 credentials. Args: user (object): user check (bool): flag whether to check step or not Returns: keystoneclient.v3.ec2.Ec2: list of ... | e7583444cd24893ec6ae237b47db7c605b99b0c5 | <|skeleton|>
class Ec2Steps:
"""Ec2 credentials steps"""
def list(self, user, check=True):
"""Step to list all ec2 credentials. Args: user (object): user check (bool): flag whether to check step or not Returns: keystoneclient.v3.ec2.Ec2: list of ec2 credentials Raises: AssertionError: if check failed""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Ec2Steps:
"""Ec2 credentials steps"""
def list(self, user, check=True):
"""Step to list all ec2 credentials. Args: user (object): user check (bool): flag whether to check step or not Returns: keystoneclient.v3.ec2.Ec2: list of ec2 credentials Raises: AssertionError: if check failed"""
cre... | the_stack_v2_python_sparse | stepler/keystone/steps/ec2.py | Mirantis/stepler | train | 16 |
c304412776bb401013b68891d817ab2218926480 | [
"if not nums:\n return\nblucket = [[], [], []]\nfor v in nums:\n blucket[v % 10].append(v)\nnums[:] = [b for a in blucket for b in a]\nreturn nums",
"i = j = 0\nfor k in range(len(nums)):\n v = nums[k]\n nums[k] = 2\n if v < 2:\n nums[j] = 1\n j += 1\n if v == 0:\n nums[i] =... | <|body_start_0|>
if not nums:
return
blucket = [[], [], []]
for v in nums:
blucket[v % 10].append(v)
nums[:] = [b for a in blucket for b in a]
return nums
<|end_body_0|>
<|body_start_1|>
i = j = 0
for k in range(len(nums)):
v =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def sortColors2(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""... | stack_v2_sparse_classes_10k_train_001796 | 1,210 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "sortColors",
"signature": "def sortColors(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "so... | 2 | stack_v2_sparse_classes_30k_train_005299 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def sortColors2(self, nums): :type nums: List[int] :rtype: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def sortColors2(self, nums): :type nums: List[int] :rtype: ... | 472f780c3214aab5c713612812d834ccbe589434 | <|skeleton|>
class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def sortColors2(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
if not nums:
return
blucket = [[], [], []]
for v in nums:
blucket[v % 10].append(v)
nums[:] = [b for a in blucket... | the_stack_v2_python_sparse | 2/75-Sort_Colors.py | ChangXiaodong/Leetcode-solutions | train | 4 | |
d9e619d937e124b73bc3f3704d20d94d20045839 | [
"super(RNNEncoder, self).__init__()\nself.batch = batch\nself.units = units\nself.embedding = tf.keras.layers.Embedding(input_dim=vocab, output_dim=embedding)\nself.gru = tf.keras.layers.GRU(units=self.units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)",
"shape = (self.batch,... | <|body_start_0|>
super(RNNEncoder, self).__init__()
self.batch = batch
self.units = units
self.embedding = tf.keras.layers.Embedding(input_dim=vocab, output_dim=embedding)
self.gru = tf.keras.layers.GRU(units=self.units, recurrent_initializer='glorot_uniform', return_sequences=Tr... | Class RNNEncoder | RNNEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNEncoder:
"""Class RNNEncoder"""
def __init__(self, vocab, embedding, units, batch):
"""Constructor for Class RNNEncoder Parameters: vocab is an integer representing the size of the input vocabulary embedding is an integer representing the dimensionality of the embedding vector uni... | stack_v2_sparse_classes_10k_train_001797 | 3,356 | permissive | [
{
"docstring": "Constructor for Class RNNEncoder Parameters: vocab is an integer representing the size of the input vocabulary embedding is an integer representing the dimensionality of the embedding vector units is an integer representing the number of hidden units in the RNN cell batch is an integer represent... | 3 | null | Implement the Python class `RNNEncoder` described below.
Class description:
Class RNNEncoder
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Constructor for Class RNNEncoder Parameters: vocab is an integer representing the size of the input vocabulary embedding is an integer re... | Implement the Python class `RNNEncoder` described below.
Class description:
Class RNNEncoder
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Constructor for Class RNNEncoder Parameters: vocab is an integer representing the size of the input vocabulary embedding is an integer re... | eaf23423ec0f412f103f5931d6610fdd67bcc5be | <|skeleton|>
class RNNEncoder:
"""Class RNNEncoder"""
def __init__(self, vocab, embedding, units, batch):
"""Constructor for Class RNNEncoder Parameters: vocab is an integer representing the size of the input vocabulary embedding is an integer representing the dimensionality of the embedding vector uni... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RNNEncoder:
"""Class RNNEncoder"""
def __init__(self, vocab, embedding, units, batch):
"""Constructor for Class RNNEncoder Parameters: vocab is an integer representing the size of the input vocabulary embedding is an integer representing the dimensionality of the embedding vector units is an inte... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/0-rnn_encoder.py | ledbagholberton/holbertonschool-machine_learning | train | 1 |
bdd16bb6870ea5a9ded39bef95448c15cdc1223b | [
"super(GraphVisualizerConnectedcolumn, self).__init__(grid, column_id, column_span)\nfor i in range(column_span):\n self._grid.setColumnStretch(self._column_id + i, 1)",
"painter = QPainter(surface)\nfor connection in self._connected_items:\n start = surface.mapFromGlobal(connection.from_item.get_attach_poi... | <|body_start_0|>
super(GraphVisualizerConnectedcolumn, self).__init__(grid, column_id, column_span)
for i in range(column_span):
self._grid.setColumnStretch(self._column_id + i, 1)
<|end_body_0|>
<|body_start_1|>
painter = QPainter(surface)
for connection in self._connected_... | Simple visual column with arrow between connected widget. | GraphVisualizerConnectedcolumn | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphVisualizerConnectedcolumn:
"""Simple visual column with arrow between connected widget."""
def __init__(self, grid, column_id, column_span=1):
"""Initialize a GraphVisualizerConnectedcolumn instance."""
<|body_0|>
def draw(self, surface):
"""Draw the surface... | stack_v2_sparse_classes_10k_train_001798 | 24,840 | permissive | [
{
"docstring": "Initialize a GraphVisualizerConnectedcolumn instance.",
"name": "__init__",
"signature": "def __init__(self, grid, column_id, column_span=1)"
},
{
"docstring": "Draw the surface.",
"name": "draw",
"signature": "def draw(self, surface)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003345 | Implement the Python class `GraphVisualizerConnectedcolumn` described below.
Class description:
Simple visual column with arrow between connected widget.
Method signatures and docstrings:
- def __init__(self, grid, column_id, column_span=1): Initialize a GraphVisualizerConnectedcolumn instance.
- def draw(self, surfa... | Implement the Python class `GraphVisualizerConnectedcolumn` described below.
Class description:
Simple visual column with arrow between connected widget.
Method signatures and docstrings:
- def __init__(self, grid, column_id, column_span=1): Initialize a GraphVisualizerConnectedcolumn instance.
- def draw(self, surfa... | bbcf475a4b4e85836123452053bbbf34cc44063a | <|skeleton|>
class GraphVisualizerConnectedcolumn:
"""Simple visual column with arrow between connected widget."""
def __init__(self, grid, column_id, column_span=1):
"""Initialize a GraphVisualizerConnectedcolumn instance."""
<|body_0|>
def draw(self, surface):
"""Draw the surface... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GraphVisualizerConnectedcolumn:
"""Simple visual column with arrow between connected widget."""
def __init__(self, grid, column_id, column_span=1):
"""Initialize a GraphVisualizerConnectedcolumn instance."""
super(GraphVisualizerConnectedcolumn, self).__init__(grid, column_id, column_span... | the_stack_v2_python_sparse | posydon/visualization/VH_diagram/GraphVisualizer.py | POSYDON-code/POSYDON | train | 11 |
a5040f3a5e0e47313cc30b6e0bc1a9011ddb5779 | [
"super().__init__(sensor, name, bridge, primary_sensor)\nself.device_registry_id = None\nself.event_id = slugify(self.sensor.name)\nself._last_state = dict(self.sensor.state)\nself.bridge.reset_jobs.append(self.bridge.sensor_manager.coordinator.async_add_listener(self.async_update_callback))",
"if self.sensor.sta... | <|body_start_0|>
super().__init__(sensor, name, bridge, primary_sensor)
self.device_registry_id = None
self.event_id = slugify(self.sensor.name)
self._last_state = dict(self.sensor.state)
self.bridge.reset_jobs.append(self.bridge.sensor_manager.coordinator.async_add_listener(self... | When you want signals instead of entities. Stateless sensors such as remotes are expected to generate an event instead of a sensor entity in hass. | HueEvent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HueEvent:
"""When you want signals instead of entities. Stateless sensors such as remotes are expected to generate an event instead of a sensor entity in hass."""
def __init__(self, sensor, name, bridge, primary_sensor=None):
"""Register callback that will be used for signals."""
... | stack_v2_sparse_classes_10k_train_001799 | 3,659 | permissive | [
{
"docstring": "Register callback that will be used for signals.",
"name": "__init__",
"signature": "def __init__(self, sensor, name, bridge, primary_sensor=None)"
},
{
"docstring": "Fire the event if reason is that state is updated.",
"name": "async_update_callback",
"signature": "def a... | 3 | null | Implement the Python class `HueEvent` described below.
Class description:
When you want signals instead of entities. Stateless sensors such as remotes are expected to generate an event instead of a sensor entity in hass.
Method signatures and docstrings:
- def __init__(self, sensor, name, bridge, primary_sensor=None)... | Implement the Python class `HueEvent` described below.
Class description:
When you want signals instead of entities. Stateless sensors such as remotes are expected to generate an event instead of a sensor entity in hass.
Method signatures and docstrings:
- def __init__(self, sensor, name, bridge, primary_sensor=None)... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class HueEvent:
"""When you want signals instead of entities. Stateless sensors such as remotes are expected to generate an event instead of a sensor entity in hass."""
def __init__(self, sensor, name, bridge, primary_sensor=None):
"""Register callback that will be used for signals."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HueEvent:
"""When you want signals instead of entities. Stateless sensors such as remotes are expected to generate an event instead of a sensor entity in hass."""
def __init__(self, sensor, name, bridge, primary_sensor=None):
"""Register callback that will be used for signals."""
super().... | the_stack_v2_python_sparse | homeassistant/components/hue/v1/hue_event.py | home-assistant/core | train | 35,501 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.