name stringclasses 844
values | input_types listlengths 0 100 | output_type stringlengths 1 419 | code stringlengths 34 233k | dependencies listlengths 0 6 | lib_used listlengths 0 11 | imports listlengths 0 66 | line_count int64 3 199 | full_code stringlengths 39 1.01M | input_type_defs listlengths 1 12 ⌀ |
|---|---|---|---|---|---|---|---|---|---|
v0 | [
"Any"
] | torch.FloatTensor | def v0(self, v1) -> torch.FloatTensor:
if isinstance(v1, list):
return self.forward_split(*v1)
v2 = self.layers[0].in_features
v3 = v1[:, :v2]
v4 = v1[:, v2:]
return self.forward_split(v3, v4) | [] | [] | [] | 7 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
from copy import deepcopy
from typing import Dict
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from ml.rl.preprocessing.identify_types import CONTINUOUS
... | null |
v0 | [
"Any",
"Any"
] | torch.FloatTensor | def v0(self, v1, v2) -> torch.FloatTensor:
v3 = v1
for (v4, v5) in enumerate(self.activations):
if v4 == 0:
v3 = self.batch_norm_ops[v4](v3)
elif v4 == 1:
v3 = self.batch_norm_ops[v4](v3)
v3 = torch.cat((v3, v2), dim=1)
v3 = self.layers[v4](v3)
... | [] | [
"torch"
] | [
"import torch",
"import torch.nn as nn",
"import torch.nn.functional as F",
"import torch.nn.init as init"
] | 17 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
from copy import deepcopy
from typing import Dict
import ml.rl.types as rlt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from ml.rl.models.base import Mo... | null |
v0 | [] | np.ndarray | def v0(self) -> np.ndarray:
v1 = self.theta * (self.mu - self.noise)
v2 = v1 + self.sigma * np.random.randn(self.action_dim)
self.noise = self.noise + v2
return self.noise | [] | [
"numpy"
] | [
"import numpy as np"
] | 5 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
from copy import deepcopy
from typing import Dict
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from ml.rl.preprocessing.identify_types import CONTINUOUS
... | null |
v0 | [
"Image.Image",
"tuple[int, int]",
"float",
"tuple[int, int]"
] | Image.Image | def v0(v1: Image.Image, v2: tuple[int, int], v3: float=1.0, v4: tuple[int, int]=(0, 0)) -> Image.Image:
v5 = Image.new('RGBA', v2)
v5.paste(v1.convert('RGBA'), v4, v1.convert('RGBA'))
return Image.blend(Image.new('RGBA', v2), v5, v3) | [] | [
"PIL"
] | [
"from PIL import Image"
] | 4 | """Do stuff to images to prepare them.
"""
from __future__ import annotations
import warnings
from deprecation import deprecated
from PIL import Image
@deprecated("use renderWAlphaOffset", version="2021.1")
def rasterImageOA( # pylint:disable=missing-function-docstring
image: Image.Image, size: tuple[int, int], a... | null |
v0 | [
"EvalPrediction"
] | Any | def v0(self, v1: EvalPrediction):
v2 = v1.predictions[0] if isinstance(v1.predictions, tuple) else v1.predictions
v2 = np.squeeze(v2) if self.is_regression else np.argmax(v2, axis=1)
if self.data_args.dataset_name is not None:
v3 = self.metric.compute(predictions=v2, references=v1.label_ids)
... | [] | [
"numpy"
] | [
"import numpy as np"
] | 12 | import torch
from torch.utils import data
from torch.utils.data import Dataset
from datasets.arrow_dataset import Dataset as HFDataset
from datasets.load import load_dataset, load_metric
from transformers import (
AutoTokenizer,
DataCollatorWithPadding,
EvalPrediction,
default_data_collator,
)
import nu... | null |
v0 | [] | None | def v0(self) -> None:
if self.get('serverfingerprint'):
if not self.get('server'):
raise Exception("config key 'serverfingerprint' requires 'server' to also be set")
self.make_key_not_modifiable('server') | [] | [] | [] | 5 | import json
import threading
import time
import os
import stat
import ssl
from decimal import Decimal
from typing import Union, Optional, Dict, Sequence, Tuple
from numbers import Real
from copy import deepcopy
from aiorpcx import NetAddress
from . import util
from . import constants
from .util import base_units, bas... | null |
v0 | [
"Real"
] | Optional[int] | def v0(self, v1: Real) -> Optional[int]:
if self.mempool_fees is None:
return None
v2 = 0
for (v3, v4) in self.mempool_fees:
v2 += v4
if v3 <= v1:
break
return v2 | [] | [] | [] | 9 | import json
import threading
import time
import os
import stat
import ssl
from decimal import Decimal
from typing import Union, Optional, Dict, Sequence, Tuple
from numbers import Real
from copy import deepcopy
from aiorpcx import NetAddress
from . import util
from . import constants
from .util import base_units, bas... | null |
v0 | [
"Any"
] | Optional[int] | def v0(self, v1) -> Optional[int]:
v2 = self.depth_target(v1)
return self.depth_target_to_fee(v2) | [] | [] | [] | 3 | import json
import threading
import time
import os
import stat
import ssl
from decimal import Decimal
from typing import Union, Optional, Dict, Sequence, Tuple
from numbers import Real
from copy import deepcopy
from aiorpcx import NetAddress
from . import util
from . import constants
from .util import base_units, bas... | null |
v0 | [
"Optional[int]"
] | str | def v0(self, v1: Optional[int]) -> str:
if v1 is None:
return 'unknown from tip'
return '%.1f MB from tip' % (v1 / 1000000) | [] | [] | [] | 4 | import json
import threading
import time
import os
import stat
import ssl
from decimal import Decimal
from typing import Union, Optional, Dict, Sequence, Tuple
from numbers import Real
from copy import deepcopy
from aiorpcx import NetAddress
from . import util
from . import constants
from .util import base_units, bas... | null |
v0 | [
"str"
] | bool | async def v0(self, v1: str, *v2, **v3) -> bool:
v4 = await super().before_action(v1, *v2, **v3)
v5 = not (v1 == 'hold' and self.on_hold)
if v1 == 'hold' and self.on_hold and self.hold_release_toggle:
self.on_hold = False
return v4 and v5 | [] | [] | [] | 6 | import abc
from cx_core import Controller, action
DEFAULT_DELAY = 350 # In milliseconds
class ReleaseHoldController(Controller, abc.ABC):
DEFAULT_MAX_LOOPS = 50
async def init(self):
self.on_hold = False
self.delay = self.args.get("delay", self.default_delay())
self.max_loops = sel... | null |
v0 | [] | None | def v0(self) -> None:
super().setUp()
with open(os.path.join(self.test_driver.repo_dir, 'hh.conf'), 'w') as v1:
v1.write('\n# some comment\nuse_mini_state = true\nuse_watchman = true\nwatchman_subscribe_v2 = true\nlazy_decl = true\nlazy_parse = true\nlazy_init2 = true\nincremental_init = true\nenable_fu... | [] | [
"os"
] | [
"import os"
] | 4 | # pyre-strict
from __future__ import absolute_import, division, print_function, unicode_literals
import json
import os
from typing import Any, ClassVar, Dict, List, Optional
import test_case
import utils
from common_tests import CommonTestDriver
from hh_paths import hh_server
class SymbolUploadTests(test_case.TestC... | null |
v0 | [] | bool | def v0(self) -> bool:
for v1 in os.listdir(self.write_repo):
if not v1.endswith('.json'):
continue
with open(os.path.join(self.write_repo, v1)) as v2:
v3 = json.load(v2)
if not self.verify_json_array(v3):
print('Error with file: {}'.format(v1))
... | [] | [
"json",
"os"
] | [
"import json",
"import os"
] | 10 | # pyre-strict
from __future__ import absolute_import, division, print_function, unicode_literals
import json
import os
from typing import Any, ClassVar, Dict, List, Optional
import test_case
import utils
from common_tests import CommonTestDriver
from hh_paths import hh_server
class SymbolUploadTests(test_case.TestC... | null |
v0 | [
"List[utils.Json]"
] | None | def v0(self, v1: List[utils.Json]) -> None:
v2 = ['hack.ClassDeclaration.1', 'hack.ClassDefinition.1', 'hack.DeclarationLocation.1', 'hack.FileXRefs.1', 'hack.InterfaceDeclaration.1', 'hack.InterfaceDefinition.1', 'hack.TraitDeclaration.1', 'hack.TraitDefinition.1']
for v3 in v1:
self.assertIn('predicat... | [] | [] | [] | 8 | # pyre-strict
from __future__ import absolute_import, division, print_function, unicode_literals
import json
import os
from typing import Any, ClassVar, Dict, List, Optional
import test_case
import utils
from common_tests import CommonTestDriver
from hh_paths import hh_server
class SymbolUploadTests(test_case.TestC... | null |
v0 | [
"Dict[str, Any]",
"List[object]"
] | None | def v0(self, v1: Dict[str, Any], v2: List[object]) -> None:
for (v3, v4) in v1.items():
if v3 in self.valid_keys and type(v4) in self.valid_keys[v3]:
continue
if v3 == 'key':
self.verify_json(v4, v2)
else:
self.assertIn(v3, v2, 'Object key is valid')
... | [] | [] | [] | 10 | # pyre-strict
from __future__ import absolute_import, division, print_function, unicode_literals
import json
import os
from typing import Any, ClassVar, Dict, List, Optional
import test_case
import utils
from common_tests import CommonTestDriver
from hh_paths import hh_server
class SymbolUploadTests(test_case.TestC... | null |
v0 | [] | None | def v0(self) -> None:
print('repo_contents : {}'.format(os.listdir(self.test_driver.repo_dir)))
v1: Optional[List[str]] = None
v1 = ['--write-symbol-info', self.write_repo]
self.test_driver.start_hh_server(args=v1)
assert self.verify_all_json() | [] | [
"os"
] | [
"import os"
] | 6 | # pyre-strict
from __future__ import absolute_import, division, print_function, unicode_literals
import json
import os
from typing import Any, ClassVar, Dict, List, Optional
import test_case
import utils
from common_tests import CommonTestDriver
from hh_paths import hh_server
class SymbolUploadTests(test_case.TestC... | null |
v0 | [
"str"
] | list | def v0(v1: str) -> list:
v2 = []
with open(v1, mode='r', encoding='UTF-8') as v3:
for v4 in v3:
v2.append(v4.strip())
return v2 | [] | [] | [] | 6 | """
GitHub repository: https://github.com/Andrusyshyn-Orest/skyscrapers
This module represents skyscrapers game.
>>> left_to_right_check("412453*", 4)
True
>>> left_to_right_check("452453*", 5)
False
>>> check_not_finished_board(['***21**', '4?????*', '4?????*',\
'*?????5', '*?????*', '*?????*', '*2*1***'])
False
>>... | null |
v0 | [
"list[str]"
] | tuple[int, int, int] | def v0(v1: list[str]) -> tuple[int, int, int]:
v2 = 0
v3 = 0
v4 = 0
v5 = 10
for v6 in v1:
v7 = v6.split(',')
if v4 == 0 and v2 != 0:
v4 = int(v7[5])
if 2 < v2 < v5:
if v7[6] == '':
v5 += 1
else:
v3 += int(v7[... | [] | [] | [] | 19 | """ Module for handling of covid data from the Public Health England API
for the covid data dashboard.
Part of the 2021 Assessement for ECM1400 at University of Exeter
© 2021 - James Cracknell https://github.com/JamesCracknell
"""
import configparser
import time
import sched
import json
import logging
from ... | null |
v19 | [
"Any"
] | None | def v19(v20='Exeter') -> None:
logging.info('Region request processing for %s', v20)
v0('', 'LTLA')
v8('region') | [
{
"name": "v0",
"input_types": [
"Any",
"Any"
],
"output_type": "None",
"code": "def v0(v1='Exeter', v2='LTLA') -> None:\n v3 = {}\n if v2 == 'LTLA':\n v1 = config['covid_defaults']['region']\n elif v2 == 'nation':\n v1 = config['covid_defaults']['nation']\n ... | [
"json",
"logging"
] | [
"import json",
"import logging"
] | 4 | """ Module for handling of covid data from the Public Health England API
for the covid data dashboard.
Part of the 2021 Assessement for ECM1400 at University of Exeter
© 2021 - James Cracknell https://github.com/JamesCracknell
"""
import configparser
import time
import sched
import json
import logging
from ... | null |
v19 | [
"Any"
] | None | def v19(v20='England') -> None:
logging.info('Nation request processing for %s', v20)
v0('', 'nation')
v8('nation') | [
{
"name": "v0",
"input_types": [
"Any",
"Any"
],
"output_type": "None",
"code": "def v0(v1='Exeter', v2='LTLA') -> None:\n v3 = {}\n if v2 == 'LTLA':\n v1 = config['covid_defaults']['region']\n elif v2 == 'nation':\n v1 = config['covid_defaults']['nation']\n ... | [
"json",
"logging"
] | [
"import json",
"import logging"
] | 4 | """ Module for handling of covid data from the Public Health England API
for the covid data dashboard.
Part of the 2021 Assessement for ECM1400 at University of Exeter
© 2021 - James Cracknell https://github.com/JamesCracknell
"""
import configparser
import time
import sched
import json
import logging
from ... | null |
v0 | [
"str"
] | tuple | def v0(v1: str) -> tuple:
v2 = 0
v3 = 2
v4 = 0
v5 = None
v6 = None
if v1 == 'region':
with open('region_covid_data.json', 'r', encoding='UTF-8') as v7:
v8 = json.load(v7)
else:
with open('nation_covid_data.json', 'r', encoding='UTF-8') as v7:
v8 = json... | [] | [
"json",
"logging"
] | [
"import json",
"import logging"
] | 32 | """ Module for handling of covid data from the Public Health England API
for the covid data dashboard.
Part of the 2021 Assessement for ECM1400 at University of Exeter
© 2021 - James Cracknell https://github.com/JamesCracknell
"""
import configparser
import time
import sched
import json
import logging
from ... | null |
v23 | [
"str"
] | None | def v23(v24: str) -> None:
logging.info('Schedule execure for: %s', v24)
v21()
v19() | [
{
"name": "v0",
"input_types": [
"Any",
"Any"
],
"output_type": "None",
"code": "def v0(v1='Exeter', v2='LTLA') -> None:\n v3 = {}\n if v2 == 'LTLA':\n v1 = config['covid_defaults']['region']\n elif v2 == 'nation':\n v1 = config['covid_defaults']['nation']\n ... | [
"json",
"logging"
] | [
"import json",
"import logging"
] | 4 | """ Module for handling of covid data from the Public Health England API
for the covid data dashboard.
Part of the 2021 Assessement for ECM1400 at University of Exeter
© 2021 - James Cracknell https://github.com/JamesCracknell
"""
import configparser
import time
import sched
import json
import logging
from ... | null |
v0 | [
"str",
"int"
] | str | def v0(self, v1: str, v2: int) -> str:
if v2 > 1:
if v1 in self.IRREGULAR_NOUNS:
return self.IRREGULAR_NOUNS.get(v1)
elif v1 in self.SAME_FORMS:
return self.SAME_FORMS.get(v1)
elif v1.endswith(('s', 'x', 'z', 'ch', 'sh')):
return f'{v1}es'
elif v1[... | [] | [] | [] | 13 | __all__ = [
"Pluralize",
"humanize",
"api_route",
]
import functools
import pendulum
import tornado.web
class Pluralize(tornado.web.UIModule):
"""Pluralize a string based on a value.
You Must set `Pluralize` as a valid UIModule
In `ui_modules` setting like so.
ui_modules=dict(
... | null |
v0 | [
"Path",
"pd.DataFrame",
"bool",
"bool"
] | Any | def v0(v1: Path, v2: pd.DataFrame, v3: bool=True, v4: bool=True):
v5 = f'_debug{int(v4)}'
v6 = Path('.') / f'dataset_dicts_cache_test{v5}.pkl'
if not v3 or not v6.exists():
print('Creating data...')
if v4:
v2 = v2.iloc[:500]
v7 = v2.loc[0, 'image_id']
v8 = str(v1 ... | [] | [
"cv2",
"pathlib",
"pickle",
"tqdm"
] | [
"import pickle",
"from pathlib import Path",
"import cv2",
"from tqdm import tqdm"
] | 28 | import pickle
from pathlib import Path
from typing import Optional
import cv2
import numpy as np
import pandas as pd
from detectron2.structures import BoxMode
from tqdm import tqdm
def get_vinbigdata_dicts(
imgdir: Path,
train_df: pd.DataFrame,
train_data_type: str = "original",
use_ca... | null |
v0 | [
"int"
] | str | def v0(v1: int) -> str:
(v2, v1) = divmod(int(v1), 1000)
(v3, v2) = divmod(v2, 60)
(v4, v3) = divmod(v3, 60)
(v5, v4) = divmod(v4, 24)
v6 = (str(v5) + ' day(s), ' if v5 else '') + (str(v4) + ' hour(s), ' if v4 else '') + (str(v3) + ' minute(s), ' if v3 else '') + (str(v2) + ' second(s), ' if v2 else... | [] | [] | [] | 7 | from userbot import bot
from telethon import events
from var import Var
from pathlib import Path
from telethon.tl.types import InputMessagesFilterDocument
import traceback
from userbot.uniborgConfig import Config
from userbot import LOAD_PLUG
from userbot import CMD_LIST
import re
import logging
import inspect
client =... | null |
v0 | [
"bytes",
"list or tuple"
] | str or None | def v0(v1: bytes, v2: list or tuple) -> str or None:
for v3 in v2:
try:
return v1.decode(v3)
except UnicodeDecodeError:
pass
return None | [] | [] | [] | 7 | """
zmail.parser
~~~~~~~~~~~~
This module provides functions to handles MIME object.
"""
import datetime
import logging
import re
import warnings
from base64 import b64decode
from datetime import timedelta, timezone, tzinfo
from email.header import decode_header
from quopri import decodestring
from typing import List
f... | null |
v4 | [
"Any",
"Any"
] | str or None | def v4(v5, v6) -> str or None:
v7 = v0(v5, v6)
if v7 is not None:
v8 = ''
for (v9, v10) in decode_header(v7):
if v10 is not None:
try:
v8 += v9.decode(v10)
except UnicodeDecodeError:
break
elif isinst... | [
{
"name": "v0",
"input_types": [
"bytes",
"list or tuple"
],
"output_type": "str or None",
"code": "def v0(v1: bytes, v2: list or tuple) -> str or None:\n for v3 in v2:\n try:\n return v1.decode(v3)\n except UnicodeDecodeError:\n pass\n retur... | [
"email"
] | [
"from email.header import decode_header"
] | 16 | """
zmail.parser
~~~~~~~~~~~~
This module provides functions to handles MIME object.
"""
import datetime
import logging
import re
import warnings
from base64 import b64decode
from datetime import timedelta, timezone, tzinfo
from email.header import decode_header
from quopri import decodestring
from typing import List
f... | null |
v0 | [
"list"
] | list | def v0(v1: list) -> list:
for (v2, v3) in v1:
if b'X-QQ' in v2:
return ['gbk']
return [] | [] | [] | [] | 5 | """
zmail.parser
~~~~~~~~~~~~
This module provides functions to handles MIME object.
"""
import datetime
import logging
import re
import warnings
from base64 import b64decode
from datetime import timedelta, timezone, tzinfo
from email.header import decode_header
from quopri import decodestring
from typing import List
f... | null |
v0 | [
"Callable"
] | ValuesView[inspect.Parameter] | def v0(v1: Callable) -> ValuesView[inspect.Parameter]:
v2 = inspect.signature(v1)
v3 = v2.parameters.values()
v4 = {inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.POSITIONAL_ONLY}
if not 1 <= len(v3) <= 3:
raise ValueError('f should take between 1 and 3 arguments, but provided functi... | [] | [
"inspect"
] | [
"import inspect"
] | 9 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | null |
v8 | [
"int",
"Any"
] | QuantumCircuit | def v8(v9: int, v10) -> QuantumCircuit:
v11 = QuantumRegister(v9, 'qc')
v12 = ClassicalRegister(v9, 'qm')
v13 = QuantumCircuit(v11, v12)
v13.h(v11[0])
v13.h(v11[1])
v13.h(v11[2])
v13.h(v11[3])
v13.h(v11[4])
v13.h(v11[0])
v13.cz(v11[3], v11[0])
v13.h(v11[0])
v13.cx(v11[3],... | [
{
"name": "v0",
"input_types": [
"int",
"Any"
],
"output_type": "QuantumCircuit",
"code": "def v0(v1: int, v2) -> QuantumCircuit:\n v3 = QuantumRegister(v1, 'ofc')\n v4 = QuantumCircuit(v3, name='Zf')\n for v5 in range(2 ** v1):\n v6 = np.binary_repr(v5, v1)\n ... | [
"math",
"numpy",
"qiskit"
] | [
"import qiskit",
"from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister",
"from qiskit import BasicAer, execute, transpile",
"from qiskit.test.mock import FakeVigo",
"from math import log2, floor, sqrt, pi",
"import numpy as np"
] | 59 | # qubit number=5
# total number=54
import cirq
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2,floor, sqrt, pi
import numpy as np
import networkx as ... | null |
v0 | [] | None | def v0(self) -> None:
self.create_model('meeting/222', {'name': 'name_SNLGsvIV'})
self.create_model('motion_comment_section/31', {'meeting_id': 222, 'name': 'name_loisueb'})
self.create_model('motion_comment_section/32', {'meeting_id': 222, 'name': 'name_blanumop'})
v1 = self.client.post('/', json=[{'ac... | [] | [] | [] | 10 | from tests.system.action.base import BaseActionTestCase
class MotionCommentSectionSortActionTest(BaseActionTestCase):
def test_sort_correct_1(self) -> None:
self.create_model("meeting/222", {"name": "name_SNLGsvIV"})
self.create_model(
"motion_comment_section/31", {"meeting_id": 222, "... | null |
v0 | [] | None | def v0(self) -> None:
self.create_model('list_of_speakers/222', {'name': 'name_SNLGsvIV'})
self.create_model('speaker/31', {'list_of_speakers_id': 222, 'name': 'name_loisueb'})
self.create_model('speaker/32', {'list_of_speakers_id': 222, 'name': 'name_blanumop'})
self.create_model('speaker/33', {'list_o... | [] | [] | [] | 8 | from tests.system.action.base import BaseActionTestCase
class SpeakerSortActionTest(BaseActionTestCase):
def test_sort_correct_1(self) -> None:
self.create_model("list_of_speakers/222", {"name": "name_SNLGsvIV"})
self.create_model(
"speaker/31", {"list_of_speakers_id": 222, "name": "na... | null |
v0 | [
"str",
"dict",
"bool",
"Optional[TextIO]"
] | Any | def v0(self, v1: str, v2: dict, v3: bool, v4: Optional[TextIO]):
for v5 in self.processors:
v5.process(v1, v2, v3, v4) | [] | [] | [] | 3 | from typing import List, Optional, TextIO
from gitlabform.configuration import Configuration
from gitlabform.gitlab import GitLab
from gitlabform.gitlabform.processors.abstract_processor import AbstractProcessor
from gitlabform.gitlabform.processors.project.branches_processor import (
BranchesProcessor,
)
from git... | null |
v0 | [
"Union[str, Iterable]"
] | Any | def v0(self, v1: Union[str, Iterable]):
if not isinstance(v1, str) and (not isinstance(v1, Iterable)):
raise ValueError(f'Values {v1} should be a string or an Iterable (list, numpy array, pytorch, tensorflow tensors)')
v2 = True
if isinstance(v1, str):
v1 = [v1]
v2 = False
v3 = [... | [] | [
"collections"
] | [
"from collections.abc import Iterable, Mapping"
] | 22 | # Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# U... | null |
v0 | [
"Union[int, Iterable]"
] | Any | def v0(self, v1: Union[int, Iterable]):
if not isinstance(v1, int) and (not isinstance(v1, Iterable)):
raise ValueError('Values {values} should be an integer or an Iterable (list, numpy array, pytorch, tensorflow tensors)')
v2 = True
if isinstance(v1, int):
v1 = [v1]
v2 = False
f... | [] | [
"collections"
] | [
"from collections.abc import Iterable"
] | 15 | # Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# U... | null |
v12 | [
"dict"
] | Any | def v12(self, v13: dict):
v14 = {}
for (v15, v16) in v13.items():
v14[v15] = [v4(self[v15], value) if value is not None else None for v17 in v16] if self._column_requires_decoding[v15] else v16
return v14 | [
{
"name": "v1",
"input_types": [
"Any",
"Optional[v0]"
],
"output_type": "bool",
"code": "def v1(v2, v3: Optional[v0]=None) -> bool:\n if v2 is None:\n return False\n elif isinstance(v2, (list, tuple)) and (v3 is None or isinstance(v3, (list, tuple, Sequence))):\n ... | [] | [] | 5 | # Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# U... | [
"v0 = Union[dict, list, tuple, Value, ClassLabel, Translation, TranslationVariableLanguages, Sequence, Array2D, Array3D, Array4D, Array5D, Audio, Image]"
] |
v0 | [
"bs4.BeautifulSoup"
] | Any | def v0(self, v1: bs4.BeautifulSoup):
v2 = v1.find('div', {'id': 'program-course-list'})
self.parse_program_title(v2.find('h1').decode_contents())
for v3 in v2.find_all('div', {'class': 'planlist'}):
v4 = v3.find('h1').decode_contents()
self.parse_plan_list(v3, v4)
for v5 in v3.find_a... | [] | [] | [] | 10 | import bs4
from ..course_list import CourseList
class ProgramParser:
"""Abstract class representing a parser for a whole degree's course list.
Concrete subclasses should define methods to parse a certain page.
"""
def __init__(self):
self.root_course_list = None
self.current_co... | null |
v0 | [
"str",
"str"
] | Tuple[bool, str] | async def v0(self, v1: str, v2: str, **v3: Any) -> Tuple[bool, str]:
if self.checker is None:
raise Exception('LVS/RCX is disabled.')
v3['params'] = v3.pop('lvs_params', None)
return await self.checker.async_run_lvs(v1, v2, **v3) | [] | [] | [] | 5 | # -*- coding: utf-8 -*-
"""This module defines DbAccess, the base class for CAD database manipulation.
"""
from typing import TYPE_CHECKING, List, Dict, Tuple, Optional, Sequence, Any, Union
import os
import abc
import traceback
import yaml
from ..io.file import make_temp_dir, read_file, write_file
from ..verifica... | null |
v0 | [
"str",
"str",
"bool"
] | Tuple[Union[bool, Optional[str]], str] | async def v0(self, v1: str, v2: str, v3: bool=True, **v4: Any) -> Tuple[Union[bool, Optional[str]], str]:
v4['params'] = v4.pop('rcx_params', None)
(v5, v6) = await self.checker.async_run_rcx(v1, v2, **v4)
return self._process_rcx_output(v5, v6, v1, v2, v3) | [] | [] | [] | 4 | # -*- coding: utf-8 -*-
"""This module defines DbAccess, the base class for CAD database manipulation.
"""
from typing import TYPE_CHECKING, List, Dict, Tuple, Optional, Sequence, Any, Union
import os
import abc
import traceback
import yaml
from ..io.file import make_temp_dir, read_file, write_file
from ..verifica... | null |
v0 | [
"str",
"str",
"str"
] | str | async def v0(self, v1: str, v2: str, v3: str, *v4: Any, **v5: Any) -> str:
if self.checker is None:
raise Exception('layout export is disabled.')
return await self.checker.async_export_layout(v1, v2, v3, *v4, **v5) | [] | [] | [] | 4 | # -*- coding: utf-8 -*-
"""This module defines DbAccess, the base class for CAD database manipulation.
"""
from typing import TYPE_CHECKING, List, Dict, Tuple, Optional, Sequence, Any, Union
import os
import abc
import traceback
import yaml
from ..io.file import make_temp_dir, read_file, write_file
from ..verifica... | null |
v0 | [
"Any",
"Any"
] | int | def v0(v1, v2) -> int:
v3 = 0
for v4 in v1:
if v4.startswith(v2):
return v3
v3 += 1
return -1 | [] | [] | [] | 7 | """ This file tests the mockup mode (tezos-client --mode mockup).
In this mode the client does not need a node running.
Make sure to either use the fixture mockup_client or
to mimick it if you want a mockup with custom parameters.
Care is taken not to leave any base_dir dangling after
tests are fi... | null |
v4 | [
"v0"
] | Any | def v4(self, v5: v0):
self.commands[v5.priority][v5.name] = v5
if self._running:
self._sort_commands(v5.priority) | [] | [] | [] | 4 | """Modulární shell pro Python"""
from __future__ import annotations
import argparse
import contextlib
import io
import os
import shlex
import sys
from enum import Enum, IntEnum
from typing import Any, Callable, Iterable
from prompt_toolkit import PromptSession
from prompt_toolkit.auto_suggest import AutoSuggestFromH... | [
"class v0:\n\n def __init__(self, v1: str, v2: Command, v3: CommandEntryPriority):\n self.name: str = v1\n self.command: Command = v2\n self.priority: CommandEntryPriority = v3"
] |
v4 | [
"v0 | None"
] | Any | def v4(self, v5: v0 | None=None):
for v5 in self.commands.keys() if v5 is None else [v5]:
self.commands[v5] = {k: v for (v6, v7) in sorted(self.commands[v5].items())} | [] | [] | [] | 3 | """Modulární shell pro Python"""
from __future__ import annotations
import argparse
import contextlib
import io
import os
import shlex
import sys
from enum import Enum, IntEnum
from typing import Any, Callable, Iterable
from prompt_toolkit import PromptSession
from prompt_toolkit.auto_suggest import AutoSuggestFromH... | [
"class v0(IntEnum):\n v1 = 0\n v2 = 1\n v3 = 2"
] |
v0 | [
"str | None"
] | Any | def v0(self, v1: str | None):
if v1 is None:
print(self.prompt)
else:
self.prompt = v1 | [] | [] | [] | 5 | """Modulární shell pro Python"""
from __future__ import annotations
import argparse
import contextlib
import io
import os
import shlex
import sys
from enum import Enum, IntEnum
from typing import Any, Callable, Iterable
from prompt_toolkit import PromptSession
from prompt_toolkit.auto_suggest import AutoSuggestFromH... | null |
v0 | [
"str"
] | int | def v0(self, v1: str) -> int:
v2 = 1
v3 = 0
v4 = {0: -1}
for (v5, v6) in enumerate(v1):
v7 = ord(v6) - ord('0')
v3 ^= 1 << v7
v2 = max(v2, v5 - v4.get(v3, v5))
for v8 in range(10):
if v3 & 1 << v8:
v9 = v3 - (1 << v8)
v2 = max(v... | [] | [] | [] | 18 | class Solution:
def longestAwesome(self, s: str) -> int:
ans = 1
code = 0
seen = {0 : -1}
for i, ch in enumerate(s):
idx = ord(ch) - ord('0')
code ^= (1 << idx)
ans = max(ans, i - seen.get(code, i))
for j in range(10):
i... | null |
v0 | [
"pd.DataFrame",
"Dict"
] | Tuple | def v0(v1: pd.DataFrame, v2: Dict) -> Tuple:
v3 = v2['target']
v4 = [x for v5 in v1.columns if v5 != v3]
v6 = v2['test_size']
v7 = v2['random_state']
v8 = logging.getLogger(__name__)
v8.info(f"Splitting data for the following independent variables {v4} against the target of '{v3}' with a test si... | [] | [
"logging",
"sklearn"
] | [
"import logging",
"from sklearn.base import BaseEstimator",
"from sklearn.metrics import r2_score",
"from sklearn.model_selection import train_test_split"
] | 11 | import importlib
import logging
from typing import Any, Dict, Tuple
import pandas as pd
from sklearn.base import BaseEstimator
from sklearn.metrics import r2_score
from sklearn.model_selection import train_test_split
def split_data(data: pd.DataFrame, split_options: Dict) -> Tuple:
"""Splits data into features a... | null |
v0 | [
"pd.DataFrame",
"pd.Series",
"Dict[str, Any]"
] | Tuple[BaseEstimator, Dict[str, Any]] | def v0(v1: pd.DataFrame, v2: pd.Series, v3: Dict[str, Any]) -> Tuple[BaseEstimator, Dict[str, Any]]:
v4 = v3.get('module')
v5 = v3.get('class')
v6 = v3.get('kwargs')
v7 = getattr(importlib.import_module(v4), v5)
v8 = v7(**v6)
v9 = logging.getLogger(__name__)
v9.info(f'Fitting model of type {... | [] | [
"importlib",
"logging"
] | [
"import importlib",
"import logging"
] | 11 | import importlib
import logging
from typing import Any, Dict, Tuple
import pandas as pd
from sklearn.base import BaseEstimator
from sklearn.metrics import r2_score
from sklearn.model_selection import train_test_split
def split_data(data: pd.DataFrame, split_options: Dict) -> Tuple:
"""Splits data into features a... | null |
v0 | [
"BaseEstimator",
"pd.DataFrame",
"pd.Series"
] | Dict[str, float] | def v0(v1: BaseEstimator, v2: pd.DataFrame, v3: pd.Series) -> Dict[str, float]:
v4 = v1.predict(v2)
v5 = r2_score(v3, v4)
v6 = logging.getLogger(__name__)
v6.info(f"Model has a coefficient R^2 of {v5:.3f} on test data using a regressor of type '{type(v1)}'")
return {'r2_score': v5} | [] | [
"logging",
"sklearn"
] | [
"import logging",
"from sklearn.base import BaseEstimator",
"from sklearn.metrics import r2_score",
"from sklearn.model_selection import train_test_split"
] | 6 | import importlib
import logging
from typing import Any, Dict, Tuple
import pandas as pd
from sklearn.base import BaseEstimator
from sklearn.metrics import r2_score
from sklearn.model_selection import train_test_split
def split_data(data: pd.DataFrame, split_options: Dict) -> Tuple:
"""Splits data into features a... | null |
v0 | [
"pl.Trainer",
"pl.LightningModule",
"Any",
"Any",
"Any",
"Any"
] | Any | def v0(self, v1: pl.Trainer, v2: pl.LightningModule, v3, v4, v5, v6):
if v5 > self.max_batches:
return
v7 = v2(v4)
v8 = torch.tensor([o - i for (v9, v10) in enumerate(v4['offsets'])])[1:]
v11 = v4['next_dt'][v8 - 1]
v11 = v11.unsqueeze(dim=-1)
v12 = v7['next_dt'][v4['offsets'][1:].detach... | [] | [
"torch"
] | [
"import torch",
"import torch.distributions as d"
] | 15 | import collections
import numpy as np
import pytorch_lightning as pl
import torch
import torch.distributions as d
from torchmetrics import MetricCollection
from neural_lifetimes.metrics import KullbackLeiblerDivergence, ParametricKullbackLeiblerDivergence, WassersteinMetric
from .get_tensorboard_logger import _get_t... | null |
v0 | [
"ET.Element"
] | str | def v0(v1: ET.Element) -> str:
if 'name' in v1.attrib:
v2 = v1.attrib['name']
else:
v2 = v1.attrib['argument'].lstrip('-')
return v2 | [] | [] | [] | 6 | ##############################################################################
#### THIS MODULE IS CURRENTLY WORK IN PROGRESS ###############################
##############################################################################
from copy import deepcopy
import lxml.etree as ET
from typing import Optional, Li... | null |
v11 | [
"ET.Element",
"List[Tuple[str, str]]"
] | Any | def v11(v12: ET.Element, v13: List[Tuple[str, str]]):
def v14(v15: ET.Element, v16: int):
if v16 == len(v13):
return v15
(v17, v18) = v13[v16]
for v19 in v15:
v20 = v0(v19)
if v20 == v17 and v19.tag == v18:
v21 = v14(v19, v16 + 1)
... | [
{
"name": "v0",
"input_types": [
"ET.Element"
],
"output_type": "str",
"code": "def v0(v1: ET.Element) -> str:\n if 'name' in v1.attrib:\n v2 = v1.attrib['name']\n else:\n v2 = v1.attrib['argument'].lstrip('-')\n return v2",
"dependencies": []
},
{
"name"... | [] | [] | 13 | ##############################################################################
#### THIS MODULE IS CURRENTLY WORK IN PROGRESS ###############################
##############################################################################
from copy import deepcopy
import lxml.etree as ET
from typing import Optional, Li... | null |
v0 | [
"int",
"int",
"int"
] | Any | def v0(v1: int, v2: int, v3: int):
v3 = min(v3, v1, v2)
v3 = int(np.ceil(v3))
if v3 % 2 == 0:
v3 += 1
return v3 | [] | [
"numpy"
] | [
"import numpy as np"
] | 6 | # from __future__ import division
#import torch
import math
import random
import numpy as np
import cv2
#import numbers
#import types
#import collections
#import warnings
from .common import preserve_shape, preserve_type, preserve_channel_dim, _maybe_process_in_chunks, polar2z, norm_kernel
from .common import _cv2_st... | null |
v0 | [
"np.ndarray"
] | Any | def v0(v1: np.ndarray):
(v2, v3, v4) = cv2.split(v1)
v5 = np.maximum(np.maximum(v4, v3), v2)
v4[v4 < v5] = 0
v3[v3 < v5] = 0
v2[v2 < v5] = 0
return cv2.merge([v2, v3, v4]) | [] | [
"cv2",
"numpy"
] | [
"import numpy as np",
"import cv2"
] | 7 | # from __future__ import division
#import torch
import math
import random
import numpy as np
import cv2
#import numbers
#import types
#import collections
#import warnings
from .common import preserve_shape, preserve_type, preserve_channel_dim, _maybe_process_in_chunks, polar2z, norm_kernel
from .common import _cv2_st... | null |
v0 | [
"str",
"object"
] | Any | def v0(v1: str, v2: object):
with open(f'database\\imports\\txt\\{v1}.txt', 'a') as v3:
v3.write(str(v2))
print(f'Registro salvo com sucesso!') | [] | [] | [] | 4 | def append_model(local_name: str, model: object):
with open(f"database\\imports\\txt\\{local_name}.txt", "a") as txt:
txt.write(str(model))
print(f"Registro salvo com sucesso!")
def read_id(local_name: str, model: object) -> str or None:
with open(f"database\\imports\\txt\\{local_name}.txt", "... | null |
v0 | [
"str",
"object"
] | str or None | def v0(v1: str, v2: object) -> str or None:
with open(f'database\\imports\\txt\\{v1}.txt', 'r') as v3:
for v4 in v3:
v5 = v4.strip('\n')
v5 = v5.split(',')
if v2.getId() == v5[0]:
print(f'Registro encontrado!')
return v4
return None | [] | [] | [] | 9 | def append_model(local_name: str, model: object):
with open(f"database\\imports\\txt\\{local_name}.txt", "a") as txt:
txt.write(str(model))
print(f"Registro salvo com sucesso!")
def read_id(local_name: str, model: object) -> str or None:
with open(f"database\\imports\\txt\\{local_name}.txt", "... | null |
v0 | [
"str"
] | str or None | def v0(v1: str) -> str or None:
v2 = list()
with open(f'database\\imports\\txt\\{v1}.txt', 'r') as v3:
for v4 in v3:
v5 = v4.strip('\n')
v2.append(v5)
return v2 | [] | [] | [] | 7 | def append_model(local_name: str, model: object):
with open(f"database\\imports\\txt\\{local_name}.txt", "a") as txt:
txt.write(str(model))
print(f"Registro salvo com sucesso!")
def read_id(local_name: str, model: object) -> str or None:
with open(f"database\\imports\\txt\\{local_name}.txt", "... | null |
v0 | [
"dict",
"dict"
] | dict | def v0(v1: dict, v2: dict) -> dict:
print(dumps(v1))
assert 'stack_name' in v1, 'missing stack_name'
assert 'wait_handle' in v1, 'missing wait_handle'
v3 = v1['stack_name']
v4 = v1['wait_handle']
v5 = 'SUCCESS'
if 'error' in v1:
v5 = 'FAILURE'
v6 = {'Status': v5, 'Reason': 'Confi... | [] | [
"json",
"requests"
] | [
"import requests",
"from json import dumps",
"from requests.models import CaseInsensitiveDict"
] | 16 | import requests
from json import dumps
from requests.models import CaseInsensitiveDict
def function_main(event:dict, _:dict)->dict:
'''
Signals the WaitHandle that the step function is complete.
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-waitcondition.html
'''
print(dumps(event... | null |
v0 | [] | ExtensionArray | def v0(self) -> ExtensionArray:
(v1, v2) = numpy.unique(self.data, return_index=True)
v3 = self.data.take(numpy.sort(v2))
return self._from_ndarray(v3) | [] | [
"numpy"
] | [
"import numpy"
] | 4 | #!/usr/bin/env python3
#
# base.py
"""
Base functionality.
"""
#
# Copyright (c) 2020 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
# Based on cyberpandas
# https://github.com/ContinuumIO/cyberpandas
# Copyright (c) 2018, Anaconda, Inc.
#
# Redistribution and use in source and binary forms, with or without
... | null |
v0 | [
"Any",
"bool",
"Any"
] | Any | def v0(self, v1, v2: bool=False, v3=None):
v1 = numpy.asarray(v1, dtype='int')
if v2 and v3 is None:
v3 = self.na_value
elif v2 and (not isinstance(v3, tuple)):
if not numpy.isnan(v3):
v3 = int(v3)
if v2:
v4 = v1 == -1
if not len(self):
if not (v1 ... | [] | [
"numpy"
] | [
"import numpy"
] | 23 | #!/usr/bin/env python3
#
# base.py
"""
Base functionality.
"""
#
# Copyright (c) 2020 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
# Based on cyberpandas
# https://github.com/ContinuumIO/cyberpandas
# Copyright (c) 2018, Anaconda, Inc.
#
# Redistribution and use in source and binary forms, with or without
... | null |
v0 | [
"Union[str, Sequence[str]]"
] | str | def v0(v1: Union[str, Sequence[str]]) -> str:
v2 = subprocess.check_output(v1, stderr=subprocess.DEVNULL, shell=False)
return v2.decode(encoding='utf-8') | [] | [
"subprocess"
] | [
"import subprocess"
] | 3 | import subprocess
from typing import Sequence, Union
import click
def run_single_command(command: Union[str, Sequence[str]]) -> str:
# More info:
# - https://github.com/PyCQA/bandit#exclusions (`# nosec`)
# - https://bandit.readthedocs.io/en/stable/plugins/b605_start_process_with_a_shell.html # noqa
... | null |
v0 | [] | None | def v0(self) -> None:
if self.pod:
v1: k8s.V1Pod = self.pod
v2 = v1.metadata.namespace
v3 = v1.metadata.name
v4 = {}
if self.termination_grace_period is not None:
v4 = {'grace_period_seconds': self.termination_grace_period}
self.client.delete_namespaced_po... | [] | [] | [] | 9 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | null |
v0 | [] | None | def v0(self) -> None:
v1 = logging.getLogger(self.__module__ + '.' + self.__class__.__name__)
if not v1.isEnabledFor(logging.INFO):
return
v1.info(self.__str__()) | [] | [
"logging"
] | [
"import logging"
] | 5 | # This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... | null |
v0 | [
"h5py.Group"
] | None | def v0(self, v1: h5py.Group) -> None:
v2 = v1.require_group(self.name)
v2.attrs['__class__'] = self.__class__.__name__
v2.attrs['__module__'] = self.__class__.__module__
v2.attrs['__version__'] = self.VERSION | [] | [] | [] | 5 | # This code is part of Qiskit.
#
# (C) Copyright IBM 2021, 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivat... | null |
v0 | [
"str",
"float"
] | Any | def v0(self, v1: str, v2: float):
if v1 == 'mae':
v3 = l1_loss
elif v1 == 'mse':
v3 = mse_loss
elif v1 == 'cross_entropy':
v3 = cross_entropy
elif v1 == 'binary_crossentropy':
v3 = binary_cross_entropy
else:
raise ValueError(f'Unknown loss name: {v1}.')
se... | [] | [
"torch"
] | [
"import torch",
"from torch import nn, optim",
"from torch.nn import functional as F",
"from torch.nn.functional import mse_loss, l1_loss, binary_cross_entropy, cross_entropy"
] | 13 | # AUTOGENERATED! DO NOT EDIT! File to edit: nbs/04_resources.ipynb (unless otherwise specified).
__all__ = ['getInfo', 'NBeatsNet', 'squeeze_last_dim', 'seasonality_model', 'trend_model', 'linear_space', 'Block',
'SeasonalityBlock', 'TrendBlock', 'GenericBlock']
# Cell
import os
import re
#N-BEATS
import ... | null |
v0 | [
"str",
"Any"
] | Any | def v0(v1: str, v2=[]):
with open(v1, 'ab') as v3:
v4 = []
v5 = []
for v6 in range(len(v2)):
v7 = v3.tell()
v3.write(v2[v6][:])
v8 = v3.tell()
v4.append(v7)
v5.append(v8 - v7)
return (v4, v5) | [] | [] | [] | 11 | """
Copyright (C) 2018-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... | null |
v0 | [
"bool"
] | Any | def v0(self, v1: bool):
for v2 in chain(self.parameters(), self.buffers()):
v2.requires_grad = v1 | [] | [
"itertools"
] | [
"from itertools import chain"
] | 3 | from typing import Sequence
from itertools import chain
import torch
import torch.nn as nn
from torchvision import models
from criteria.lpips.utils import normalize_activation
def get_network(net_type: str):
if net_type == 'alex':
return AlexNet()
elif net_type == 'squeeze':
... | null |
v4 | [
"v0"
] | List[List[int]] | def v4(self, v5: v0) -> List[List[int]]:
v6 = []
if not v5:
return v6
v7 = [v5]
v8 = True
while v7:
v9 = len(v7)
v10 = []
for v11 in range(v9):
v12 = v7.pop()
if v8:
v10.append(v12.val)
else:
v10.inse... | [] | [] | [] | 21 | from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# 方法1-层序遍历:
class Solution1:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
res = []
if not root:
r... | [
"class v0:\n\n def __init__(self, v1=0, v2=None, v3=None):\n self.val = v1\n self.left = v2\n self.right = v3"
] |
v0 | [
"str",
"list"
] | Any | def v0(self, v1: str, v2: list):
v3 = locals()
v4 = {'tags': ['sm', 'configure', 'bypassActivationLockAttempts'], 'operation': 'createNetworkSmBypassActivationLockAttempt'}
v5 = f'/networks/{v1}/sm/bypassActivationLockAttempts'
v6 = ['ids']
v7 = {k.strip(): v for (v8, v9) in v3.items() if v8.strip()... | [] | [] | [] | 7 | class Sm(object):
def __init__(self, session):
super(Sm, self).__init__()
self._session = session
def createNetworkSmBypassActivationLockAttempt(self, networkId: str, ids: list):
"""
**Bypass activation lock attempt**
https://developer.cisco.com/meraki/api-v1/#!create-ne... | null |
v0 | [
"str",
"str"
] | Any | def v0(self, v1: str, v2: str):
v3 = {'tags': ['sm', 'configure', 'bypassActivationLockAttempts'], 'operation': 'getNetworkSmBypassActivationLockAttempt'}
v4 = f'/networks/{v1}/sm/bypassActivationLockAttempts/{v2}'
return self._session.get(v3, v4) | [] | [] | [] | 4 | class Sm(object):
def __init__(self, session):
super(Sm, self).__init__()
self._session = session
def createNetworkSmBypassActivationLockAttempt(self, networkId: str, ids: list):
"""
**Bypass activation lock attempt**
https://developer.cisco.com/meraki/api-v1/#!create-ne... | null |
v0 | [
"str"
] | Any | async def v0(self, v1: str, **v2):
v2.update(locals())
v3 = {'tags': ['SM'], 'operation': 'wipeNetworkSmDevice'}
v4 = f'/networks/{v1}/sm/device/wipe'
v5 = ['wifiMac', 'id', 'serial', 'pin']
v6 = {k.strip(): v for (v7, v8) in v2.items() if v7.strip() in v5}
return await self._session.put(v3, v4,... | [] | [] | [] | 7 | class AsyncSM:
def __init__(self, session):
super().__init__()
self._session = session
async def createNetworkSmBypassActivationLockAttempt(self, networkId: str, ids: list):
"""
**Bypass activation lock attempt**
https://developer.cisco.com/meraki/api/#!create-networ... | null |
v0 | [
"str",
"str"
] | Any | def v0(self, v1: str, v2: str):
v3 = {'tags': ['sm', 'configure', 'devices'], 'operation': 'refreshNetworkSmDeviceDetails'}
v4 = f'/networks/{v1}/sm/devices/{v2}/refreshDetails'
return self._session.post(v3, v4) | [] | [] | [] | 4 | class Sm(object):
def __init__(self, session):
super(Sm, self).__init__()
self._session = session
def createNetworkSmBypassActivationLockAttempt(self, networkId: str, ids: list):
"""
**Bypass activation lock attempt**
https://developer.cisco.com/meraki/api-v1/#!create-ne... | null |
v0 | [
"str"
] | Any | async def v0(self, v1: str, **v2):
v2.update(locals())
v3 = {'tags': ['SM'], 'operation': 'getNetworkSmDevices'}
v4 = f'/networks/{v1}/sm/devices'
v5 = ['fields', 'wifiMacs', 'serials', 'ids', 'scope', 'batchSize', 'batchToken']
v6 = {k.strip(): v for (v7, v8) in v2.items() if v7.strip() in v5}
... | [] | [] | [] | 7 | class AsyncSM:
def __init__(self, session):
super().__init__()
self._session = session
async def createNetworkSmBypassActivationLockAttempt(self, networkId: str, ids: list):
"""
**Bypass activation lock attempt**
https://developer.cisco.com/meraki/api/#!create-networ... | null |
v0 | [
"str",
"bool"
] | Any | def v0(self, v1: str, v2: bool, **v3):
v3.update(locals())
v4 = {'tags': ['appliance', 'configure', 'warmSpare'], 'operation': 'updateNetworkApplianceWarmSpare'}
v5 = f'/networks/{v1}/appliance/warmSpare'
v6 = ['enabled', 'spareSerial', 'uplinkMode', 'virtualIp1', 'virtualIp2']
v7 = {k.strip(): v fo... | [] | [] | [] | 7 | class Appliance(object):
def __init__(self, session):
super(Appliance, self).__init__()
self._session = session
def getDeviceApplianceDhcpSubnets(self, serial: str):
"""
**Return the DHCP subnet information for an appliance**
https://developer.cisco.com/meraki/... | null |
v0 | [
"str",
"str",
"str"
] | Any | async def v0(self, v1: str, v2: str, v3: str, **v4):
v4.update(locals())
v5 = {'tags': ['SM'], 'operation': 'updateNetworkSmDevicesTags'}
v6 = f'/networks/{v1}/sm/devices/tags'
v7 = ['wifiMacs', 'ids', 'serials', 'scope', 'tags', 'updateAction']
v8 = {k.strip(): v for (v9, v10) in v4.items() if v9.s... | [] | [] | [] | 7 | class AsyncSM:
def __init__(self, session):
super().__init__()
self._session = session
async def createNetworkSmBypassActivationLockAttempt(self, networkId: str, ids: list):
"""
**Bypass activation lock attempt**
https://developer.cisco.com/meraki/api/#!create-networ... | null |
v0 | [
"str",
"str"
] | Any | async def v0(self, v1: str, v2: str):
v3 = {'tags': ['SM'], 'operation': 'unenrollNetworkSmDevice'}
v4 = f'/networks/{v1}/sm/devices/{v2}/unenroll'
return await self._session.post(v3, v4) | [] | [] | [] | 4 | class AsyncSM:
def __init__(self, session):
super().__init__()
self._session = session
async def createNetworkSmBypassActivationLockAttempt(self, networkId: str, ids: list):
"""
**Bypass activation lock attempt**
https://developer.cisco.com/meraki/api/#!create-networ... | null |
v0 | [
"str"
] | Any | def v0(self, v1: str):
v2 = {'tags': ['networks', 'configure', 'firmwareUpgrades'], 'operation': 'getNetworkFirmwareUpgrades'}
v3 = f'/networks/{v1}/firmwareUpgrades'
return self._session.get(v2, v3) | [] | [] | [] | 4 | class AsyncNetworks:
def __init__(self, session):
super().__init__()
self._session = session
def getNetwork(self, networkId: str):
"""
**Return a network**
https://developer.cisco.com/meraki/api-v1/#!get-network
- networkId (string): (required)
"""
... | null |
v0 | [
"str",
"str"
] | Any | async def v0(self, v1: str, v2: str):
v3 = {'tags': ['Traffic shaping'], 'operation': 'getNetworkSsidTrafficShaping'}
v4 = f'/networks/{v1}/ssids/{v2}/trafficShaping'
return await self._session.get(v3, v4) | [] | [] | [] | 4 | class AsyncTrafficShaping:
def __init__(self, session):
super().__init__()
self._session = session
async def updateNetworkSsidTrafficShaping(self, networkId: str, number: str, **kwargs):
"""
**Update the traffic shaping settings for an SSID on an MR network**
https:/... | null |
v0 | [
"str"
] | Any | def v0(self, v1: str, **v2):
v2.update(locals())
v3 = {'tags': ['sm', 'configure', 'users'], 'operation': 'getNetworkSmUsers'}
v4 = f'/networks/{v1}/sm/users'
v5 = ['ids', 'usernames', 'emails', 'scope']
v6 = {k.strip(): v for (v7, v8) in v2.items() if v7.strip() in v5}
return self._session.get(... | [] | [] | [] | 7 | class Sm(object):
def __init__(self, session):
super(Sm, self).__init__()
self._session = session
def createNetworkSmBypassActivationLockAttempt(self, networkId: str, ids: list):
"""
**Bypass activation lock attempt**
https://developer.cisco.com/meraki/api-v1/#!create-ne... | null |
v0 | [
"str",
"str"
] | Any | async def v0(self, v1: str, v2: str):
v3 = {'tags': ['SM'], 'operation': 'getNetworkSmCellularUsageHistory'}
v4 = f'/networks/{v1}/sm/{v2}/cellularUsageHistory'
return await self._session.get(v3, v4) | [] | [] | [] | 4 | class AsyncSM:
def __init__(self, session):
super().__init__()
self._session = session
async def createNetworkSmBypassActivationLockAttempt(self, networkId: str, ids: list):
"""
**Bypass activation lock attempt**
https://developer.cisco.com/meraki/api/#!create-networ... | null |
v0 | [
"str",
"str"
] | Any | async def v0(self, v1: str, v2: str):
v3 = {'tags': ['SM'], 'operation': 'getNetworkSmUserDeviceProfiles'}
v4 = f'/networks/{v1}/sm/user/{v2}/deviceProfiles'
return await self._session.get(v3, v4) | [] | [] | [] | 4 | class AsyncSM:
def __init__(self, session):
super().__init__()
self._session = session
async def createNetworkSmBypassActivationLockAttempt(self, networkId: str, ids: list):
"""
**Bypass activation lock attempt**
https://developer.cisco.com/docs/meraki-api-v0/#!creat... | null |
v0 | [
"str",
"str",
"Any",
"Any"
] | Any | def v0(self, v1: str, v2: str, v3=1, v4='next', **v5):
v5.update(locals())
v6 = {'tags': ['sm', 'monitor', 'devices', 'performanceHistory'], 'operation': 'getNetworkSmDevicePerformanceHistory'}
v7 = f'/networks/{v1}/sm/devices/{v2}/performanceHistory'
v8 = ['perPage', 'startingAfter', 'endingBefore']
... | [] | [] | [] | 7 | class Sm(object):
def __init__(self, session):
super(Sm, self).__init__()
self._session = session
def createNetworkSmBypassActivationLockAttempt(self, networkId: str, ids: list):
"""
**Bypass activation lock attempt**
https://developer.cisco.com/meraki/api-v1/#!create-ne... | null |
v0 | [
"List[List[str]]"
] | Any | def v0(v1: List[List[str]]):
v2 = StringIO()
v3 = csv.writer(v2)
v3.writerows(v1)
return v2.getvalue() | [] | [
"csv",
"io"
] | [
"import csv",
"from io import StringIO"
] | 5 | import csv
import json
import os
import time
# from notifications_utils.s3 import s3upload as utils_s3upload
import urllib
import uuid
from enum import Enum
from io import StringIO
from typing import Any, Iterator, List, Tuple
import botocore
import requests
from boto3 import Session
from dotenv import load_dotenv
fr... | null |
v0 | [
"torch.Tensor",
"torch.Tensor",
"torch.Tensor",
"torch.Tensor",
"torch.Tensor",
"torch.Tensor",
"torch.Tensor"
] | Tuple[torch.Tensor, torch.Tensor, torch.Tensor] | def v0(self, v1: torch.Tensor, v2: torch.Tensor, v3: torch.Tensor, v4: torch.Tensor, v5: torch.Tensor, v6: torch.Tensor, v7: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
v8 = self._source_mask(v2)
(v9, v10) = self.encoder(v1, v8)
if self.use_gst:
v11 = self.gst(v3)
v9 = ... | [] | [] | [] | 29 | # Copyright 2020 Nagoya University (Tomoki Hayashi)
# 2021 Carnegie Mellon University (Jiatong Shi)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Transformer-SVS related modules."""
from typing import Dict
from typing import Optional
from typing import Sequence
from typing import Tuple
imp... | null |
v0 | [
"torch.Tensor"
] | torch.Tensor | def v0(self, v1: torch.Tensor) -> torch.Tensor:
v2 = torch.cat([v1.new_zeros((v1.shape[0], 1, v1.shape[2])), v1[:, :-1]], dim=1)
return v2 | [] | [
"torch"
] | [
"import torch",
"import torch.nn.functional as F"
] | 3 | # Copyright 2020 Nagoya University (Tomoki Hayashi)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Transformer-TTS related modules."""
from typing import Dict
from typing import Optional
from typing import Sequence
from typing import Tuple
import torch
import torch.nn.functional as F
from typeguard ... | null |
v0 | [
"torch.Tensor",
"torch.Tensor"
] | torch.Tensor | def v0(self, v1: torch.Tensor, v2: torch.Tensor) -> torch.Tensor:
if self.spk_embed_integration_type == 'add':
v2 = self.projection(F.normalize(v2))
v1 = v1 + v2.unsqueeze(1)
elif self.spk_embed_integration_type == 'concat':
v2 = F.normalize(v2).unsqueeze(1).expand(-1, v1.size(1), -1)
... | [] | [
"torch"
] | [
"import torch",
"import torch.nn.functional as F"
] | 10 | # Copyright 2020 Nagoya University (Tomoki Hayashi)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Transformer-TTS related modules."""
from typing import Dict
from typing import Optional
from typing import Sequence
from typing import Tuple
import torch
import torch.nn.functional as F
from typeguard ... | null |
v0 | [
"_curses.window"
] | Any | def v0(self, v1: _curses.window):
v1.clear()
self.fits = self.app.renderer.on_wnd(v1, self.app.theme, 0, 0, self.scroll, 'issue_view.j2', key=self.issue.key, issue=self.issue.fields) | [] | [] | [] | 3 | from datetime import datetime
import _curses
from fatjira.views import CommonView
from yacui import Binding
class IssueView(CommonView):
"""
Issue view.
TODO: Add offline/online indicator.
"""
def __init__(self, app, key):
super().__init__(app)
self.key = key
self.issue ... | null |
v0 | [
"'ConstructionRay'"
] | bool | def v0(self, v1: 'ConstructionRay') -> bool:
if self._is_vertical:
return v1._is_vertical
if v1._is_vertical:
return False
if self._is_horizontal:
return v1._is_horizontal
return math.isclose(self._slope, v1._slope, abs_tol=1e-12) | [] | [
"math"
] | [
"import math"
] | 8 | # Created: 13.03.2010
# Copyright (c) 2010-2020, Manfred Moitzi
# License: MIT License
from typing import TYPE_CHECKING, Optional
import math
from .construct2d import is_point_left_of_line, intersection_line_line_2d, TOLERANCE
from .bbox import BoundingBox2d
from .vector import Vec2
if TYPE_CHECKING:
from ezdxf.ez... | null |
v0 | [
"float"
] | float | def v0(self, v1: float) -> float:
if self._is_vertical:
raise ArithmeticError
return self._yof0 + float(v1) * self._slope | [] | [] | [] | 4 | # Created: 13.03.2010
# Copyright (c) 2010-2020, Manfred Moitzi
# License: MIT License
from typing import TYPE_CHECKING, Optional
import math
from .construct2d import is_point_left_of_line, intersection_line_line_2d, TOLERANCE
from .bbox import BoundingBox2d
from .vector import Vec2
if TYPE_CHECKING:
from ezdxf.ez... | null |
v0 | [
"float"
] | float | def v0(self, v1: float) -> float:
if self._is_vertical:
return self._location.x
elif not self._is_horizontal:
return (float(v1) - self._yof0) / self._slope
else:
raise ArithmeticError | [] | [] | [] | 7 | # Created: 13.03.2010
# Copyright (c) 2010-2020, Manfred Moitzi
# License: MIT License
from typing import TYPE_CHECKING, Optional
import math
from .construct2d import is_point_left_of_line, intersection_line_line_2d, TOLERANCE
from .bbox import BoundingBox2d
from .vector import Vec2
if TYPE_CHECKING:
from ezdxf.ez... | null |
v86 | [
"v0"
] | None | def v86(v87: v0) -> None:
if v87.get_children() and (not v87.focus()):
v87.set_the_selection_correctly(v87.get_children()[0])
v87.tk.call('focus', v87) | [] | [] | [] | 4 | from __future__ import annotations
import logging
import os
import pathlib
import subprocess
import sys
import time
import tkinter
from functools import partial
from tkinter import ttk
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from porcupine import (
get_main_window,
get_paned_windo... | [
"class v0(ttk.Treeview):\n\n def __init__(self, v1: tkinter.Misc) -> None:\n super().__init__(v1, selectmode='browse', show='tree', style='DirectoryTree.Treeview')\n self.bind('<Button-1>', lambda event: self.after_idle(self.on_click, event), add=True)\n self.bind('<<TreeviewOpen>>', self.op... |
v86 | [
"tkinter.Event[v0]"
] | None | def v86(self, v87: tkinter.Event[v0]) -> None:
v88 = self.selection()
if v87.time - self._last_click_time < 500 and self._last_click_selection == v88:
self.open_file_or_dir()
self._last_click_time = v87.time
self._last_click_selection = v88 | [] | [] | [] | 6 | from __future__ import annotations
import logging
import os
import pathlib
import subprocess
import sys
import time
import tkinter
from functools import partial
from tkinter import ttk
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from porcupine import (
get_main_window,
get_paned_windo... | [
"class v0(ttk.Treeview):\n\n def __init__(self, v1: tkinter.Misc) -> None:\n super().__init__(v1, selectmode='browse', show='tree', style='DirectoryTree.Treeview')\n self.bind('<Button-1>', lambda event: self.after_idle(self.on_click, event), add=True)\n self.bind('<<TreeviewOpen>>', self.op... |
v0 | [
"object"
] | None | def v0(self, v1: object=None) -> None:
try:
[v2] = self.selection()
except ValueError:
v3 = []
else:
v3 = [tag for v4 in self.item(v2, 'tags') if v4.startswith('git_')]
if v3:
[v4] = v3
v5 = self.tag_configure(v4, 'foreground')
self.tk.call('ttk::style', '... | [] | [] | [] | 13 | from __future__ import annotations
import logging
import os
import pathlib
import subprocess
import sys
import time
import tkinter
from functools import partial
from tkinter import ttk
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from porcupine import (
get_main_window,
get_paned_windo... | null |
v0 | [
"pathlib.Path",
"bool"
] | None | def v0(self, v1: pathlib.Path, *, v2: bool=True) -> None:
for v3 in self.get_children():
if self.get_path(v3) == v1:
self.move(v3, '', 0)
return
if pathlib.Path.home() in v1.parents:
v4 = '~' + os.sep + str(v1.relative_to(pathlib.Path.home()))
else:
v4 = str(v... | [] | [
"os",
"pathlib"
] | [
"import os",
"import pathlib"
] | 14 | from __future__ import annotations
import logging
import os
import pathlib
import subprocess
import sys
import time
import tkinter
from functools import partial
from tkinter import ttk
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from porcupine import (
get_main_window,
get_paned_windo... | null |
v0 | [
"str"
] | None | def v0(self, v1: str) -> None:
self.selection_set(v1)
self.focus(v1) | [] | [] | [] | 3 | from __future__ import annotations
import logging
import os
import pathlib
import subprocess
import sys
import time
import tkinter
from functools import partial
from tkinter import ttk
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from porcupine import (
get_main_window,
get_paned_windo... | null |
v0 | [
"str"
] | None | def v0(self, v1: str) -> None:
assert v1
self.insert(v1, 'end', text='(empty)', tags='dummy') | [] | [] | [] | 3 | from __future__ import annotations
import logging
import os
import pathlib
import subprocess
import sys
import time
import tkinter
from functools import partial
from tkinter import ttk
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from porcupine import (
get_main_window,
get_paned_windo... | null |
v0 | [
"str"
] | bool | def v0(self, v1: str) -> bool:
v2 = self.get_children(v1)
return len(v2) == 1 and self.tag_has('dummy', v2[0]) | [] | [] | [] | 3 | from __future__ import annotations
import logging
import os
import pathlib
import subprocess
import sys
import time
import tkinter
from functools import partial
from tkinter import ttk
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from porcupine import (
get_main_window,
get_paned_windo... | null |
v0 | [
"Optional[pathlib.Path]",
"str"
] | None | def v0(self, v1: Optional[pathlib.Path], v2: str) -> None:
if self._contains_dummy(v2):
self.delete(self.get_children(v2)[0])
v3 = {self.get_path(id): id for v4 in self.get_children(v2)}
if v1 is None:
assert not v2
v5 = set(v3.keys())
else:
v5 = set(v1.iterdir())
... | [] | [] | [] | 50 | from __future__ import annotations
import logging
import os
import pathlib
import subprocess
import sys
import time
import tkinter
from functools import partial
from tkinter import ttk
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from porcupine import (
get_main_window,
get_paned_windo... | null |
v0 | [
"Tuple[pathlib.Path, str]"
] | Tuple[Any, ...] | def v0(self, v1: Tuple[pathlib.Path, str]) -> Tuple[Any, ...]:
(v2, v3) = v1
v4 = self.item(v3, 'tags')
v5 = [tag for v6 in v4 if v6.startswith('git_')]
assert len(v5) < 2
v7 = v5[0] if v5 else None
return (['git_added', 'git_modified', 'git_mergeconflict', None, 'git_untracked', 'git_ignored'].... | [] | [] | [] | 7 | from __future__ import annotations
import logging
import os
import pathlib
import subprocess
import sys
import time
import tkinter
from functools import partial
from tkinter import ttk
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from porcupine import (
get_main_window,
get_paned_windo... | null |
v0 | [
"str"
] | pathlib.Path | def v0(self, v1: str) -> pathlib.Path:
assert not self.tag_has('dummy', v1)
return pathlib.Path(self.item(v1, 'values')[0]) | [] | [
"pathlib"
] | [
"import pathlib"
] | 3 | from __future__ import annotations
import logging
import os
import pathlib
import subprocess
import sys
import time
import tkinter
from functools import partial
from tkinter import ttk
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from porcupine import (
get_main_window,
get_paned_windo... | null |
v0 | [
"torch.Tensor",
"higher.patch._MonkeyPatchBase",
"dict"
] | typing.List[torch.Tensor] | def v0(self, v1: torch.Tensor, v2: higher.patch._MonkeyPatchBase, v3: dict) -> typing.List[torch.Tensor]:
v4 = [None] * self.config['num_models']
for v5 in range(self.config['num_models']):
v6 = v2.forward()
v7 = v3['f_base_net'].forward(v1, params=v6)
v4[v5] = v7
return v4 | [] | [] | [] | 7 | import torch
import higher
import typing
from MLBaseClass import MLBaseClass
from _utils import kl_divergence_gaussians
from HyperNetClasses import NormalVariationalNet
from Maml import Maml
class Abml(MLBaseClass):
def __init__(self, config: dict) -> None:
super().__init__(config=config)
self.hy... | null |
v0 | [
"torch.Tensor",
"torch.Tensor",
"higher.patch._MonkeyPatchBase",
"dict"
] | torch.Tensor | def v0(self, v1: torch.Tensor, v2: torch.Tensor, v3: higher.patch._MonkeyPatchBase, v4: dict) -> torch.Tensor:
v5 = self.prediction(x=v1, adapted_hyper_net=v3, model=v4)
v6 = 0
for v7 in v5:
v8 = self.config['loss_function'](input=v7, target=v2)
v6 = v6 + v8
v6 = v6 / len(v5)
return ... | [] | [] | [] | 8 | import torch
import numpy as np
import higher
import typing
from MLBaseClass import MLBaseClass
from HyperNetClasses import EnsembleNet
from Maml import Maml
class Bmaml(MLBaseClass):
def __init__(self, config: dict) -> None:
super().__init__(config=config)
self.hyper_net_class = Ensemble... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.