name
stringclasses
293 values
input_types
listlengths
0
49
output_type
stringlengths
1
180
code
stringlengths
37
97.8k
dependencies
listlengths
0
6
lib_used
listlengths
0
11
imports
listlengths
0
40
line_count
int64
3
155
full_code
stringlengths
51
996k
input_type_defs
listlengths
1
11
v0
[ "List[str]", "str" ]
Any
def v0(self, v1: List[str], v2: str): v3 = v1.index('--tfx_ir') self.assertAllGreater(len(v1), v3) v4 = json.loads(v1[v3 + 1]) v5 = json.dumps(v4, sort_keys=True) with open(os.path.join(self._source_data_dir, v2)) as v6: v7 = json.dumps(json.load(v6), sort_keys=True) self.assertEqual...
[]
[ "json", "os" ]
[ "import json", "import os" ]
8
# Copyright 2019 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
null
v0
[]
None
def v0(self) -> None: self.q_net = self.policy.q_net self.q_net_target = self.policy.q_net_target
[]
[]
[]
3
from typing import Any, Dict, List, Optional, Tuple, Type, Union import numpy as np import torch as th from torch.nn import functional as F from stable_baselines3.common import logger from stable_baselines3.common.off_policy_algorithm import OffPolicyAlgorithm from stable_baselines3.common.type_aliases import GymEnv,...
null
v0
[]
Tuple[List[str], List[str]]
def v0(self) -> Tuple[List[str], List[str]]: v1 = ['policy', 'policy.optimizer'] return (v1, [])
[]
[]
[]
3
from typing import Any, Dict, List, Optional, Tuple, Type, Union import numpy as np import torch as th from torch.nn import functional as F from stable_baselines3.common import logger from stable_baselines3.common.off_policy_algorithm import OffPolicyAlgorithm from stable_baselines3.common.type_aliases import GymEnv,...
null
v0
[ "object", "callable" ]
Any
def v0(self, v1: object, v2: callable): self._check_comm_hook(v2) self.logger._set_comm_hook_name(v2.__qualname__) dist._register_comm_hook(self.reducer, v1, v2)
[]
[ "torch" ]
[ "import torch", "import torch.distributed as dist", "from torch._utils import _get_device_index" ]
4
import copy import inspect import itertools import logging import os import warnings from contextlib import contextmanager from typing import NamedTuple import torch import torch.distributed as dist RPC_AVAILABLE = False if dist.is_available(): from torch.distributed.distributed_c10d import ReduceOp from torc...
null
v0
[ "Optional[AdaptContext]" ]
str
def v0(self, v1: Optional[AdaptContext]) -> str: v2 = self._format return f'%({self._obj}){v2}' if self._obj else f'%{v2}'
[]
[]
[]
3
""" SQL composition utility module """ # Copyright (C) 2020-2021 The Psycopg Team import codecs import string from abc import ABC, abstractmethod from typing import Any, Iterator, List, Optional, Sequence, Union from .pq import Escaping from .abc import AdaptContext from .adapt import Transformer, PyFormat from ._en...
null
v0
[ "str", "str", "dict | None", "dict | None" ]
Tuple[dict, str]
def v0(v1: str, v2: str, v3: dict | None=None, v4: dict | None=None) -> Tuple[dict, str]: if not v4: v4 = {'Authorization': f'Bearer {v2}'} v5 = requests.post('https://api.github.com/graphql', json={'query': v1, 'variables': v3}, headers=v4) if v5.status_code == 200: return (v5.json(), v5.he...
[]
[ "requests" ]
[ "import requests" ]
8
from __future__ import annotations from anytree import NodeMixin from datetime import datetime, timezone from dotenv import load_dotenv from os import environ from os.path import join, dirname from typing import Tuple, List, Any, Dict, Optional import re import requests from rich.box import Box __all__ = [ "get_d...
null
v6
[ "str", "str", "Dict[str, str]" ]
Tuple[bool, Any, str]
def v6(v7: str, v8: str, v9: Dict[str, str]) -> Tuple[bool, Any, str]: (v10, v11) = v0(v7, v8, v9) if list(v10.keys())[0] == 'errors': return (True, v10['errors'][0]['message'], v11) try: return (False, v10['data']['repository'], v11) except TypeError: return (True, 'Query failed...
[ { "name": "v0", "input_types": [ "str", "str", "dict | None", "dict | None" ], "output_type": "Tuple[dict, str]", "code": "def v0(v1: str, v2: str, v3: dict | None=None, v4: dict | None=None) -> Tuple[dict, str]:\n if not v4:\n v4 = {'Authorization': f'Bearer {v...
[ "requests" ]
[ "import requests" ]
8
from __future__ import annotations from anytree import NodeMixin from datetime import datetime, timezone from dotenv import load_dotenv from os import environ from os.path import join, dirname from typing import Tuple, List, Any, Dict, Optional import re import requests from rich.box import Box __all__ = [ "get_d...
null
v0
[ "str" ]
Tuple[str, str] | List[str]
def v0(v1: str) -> Tuple[str, str] | List[str]: v2 = re.compile('^(git(hub)?|https?)') v3 = re.compile('^[a-zA-Z0-9\\-_.]+/[a-zA-Z0-9\\-_.]+') v4 = re.compile('^(https|git)?(://|@)?([^/:]+)[/:](?P<owner>[^/:]+)/(?P<name>.+)(.git)?$') v5 = re.compile('((.git)|/)$') if v2.match(v1): if v3.matc...
[]
[ "re" ]
[ "import re" ]
19
from __future__ import annotations from anytree import NodeMixin from datetime import datetime, timezone from dotenv import load_dotenv from os import environ from os.path import join, dirname from typing import Tuple, List, Any, Dict, Optional import re import requests from rich.box import Box __all__ = [ "get_d...
null
v0
[ "str" ]
str
def v0(v1: str) -> str: if not v1: return 'null' v2 = datetime.now() v3 = datetime.strptime(v1, '%Y-%m-%dT%H:%M:%SZ') v3 = v3.replace(tzinfo=timezone.utc) v4 = int(v2.timestamp() - v3.timestamp()) v5 = [1, 60, 3600, 86400, 604800, 2629746, 31556925] v6 = ['Second', 'Minute', 'Hour', ...
[]
[ "datetime" ]
[ "from datetime import datetime, timezone" ]
13
from __future__ import annotations from anytree import NodeMixin from datetime import datetime, timezone from dotenv import load_dotenv from os import environ from os.path import join, dirname from typing import Tuple, List, Any, Dict, Optional import re import requests from rich.box import Box __all__ = [ "get_d...
null
v0
[ "str" ]
str
def v0(v1: str) -> str: print(type(v1)) return f'Hi {v1}'
[]
[]
[]
3
#!/usr/bin/env python3 def ret_string(name: str) -> str: print(type(name)) return f"Hi {name}" for n in ["Karel", "Pepa", 18, "Lucie"]: try: print(type(n)) print(ret_string(n)) except TypeError as err: print(n) print(err)
null
v0
[ "List[List[int]]", "int" ]
bool
def v0(self, v1: List[List[int]], v2: int) -> bool: v3 = 0 v4 = len(v1[0]) - 1 while v3 < len(v1) and v4 >= 0: if v1[v3][v4] == v2: return True elif v1[v3][v4] > v2: v4 -= 1 else: v3 += 1 return False
[]
[]
[]
11
from typing import List class Solution: """ 74.搜索二维矩阵 | 难度:中等 | 标签:数组、二分查找 编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性: <p> 每行中的整数从左到右按升序排列。 每行的第一个整数大于前一行的最后一个整数。 <p> 示例 1: 输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 输出:true <p> 示例 2: 输入:matrix = ...
null
v0
[ "Optional[int]", "Optional[float]", "Optional[bool]", "Optional[int]", "Optional[int]" ]
Any
def v0(self, v1: Optional[int]=None, v2: Optional[float]=None, v3: Optional[bool]=None, v4: Optional[int]=None, v5: Optional[int]=None): if v2 is not None: self.inferencer.model.prediction_heads[0].no_ans_boost = v2 if v3 is not None: self.return_no_answers = v3 if v5 is not None: se...
[]
[]
[]
12
from typing import List, Optional, Dict, Any, Union, Callable import logging import multiprocessing from pathlib import Path from collections import defaultdict from time import perf_counter import torch from haystack.modeling.data_handler.data_silo import DataSilo, DistillationDataSilo from haystack.modeling.data_ha...
null
v0
[]
Optional[str]
def v0(self) -> Optional[str]: if self.image_192 is not None: return self.image_192 if self.image_72 is not None: return self.image_72 return None
[]
[]
[]
6
from typing import List, Optional from dataclasses import dataclass UserID = str BotID = str ChannelID = str @dataclass class Channel: """ https://api.slack.com/types/channel """ id: ChannelID name: str is_archived: bool is_member: bool @staticmethod def from_json(json: dict): ...
null
v0
[ "'List[List[int]]'" ]
'List[List[int]]'
def v0(self, v1: 'List[List[int]]') -> 'List[List[int]]': v2 = len(v1) if v2 == 0: return [] if v2 == 1: (v3, v4, v5) = v1[0] return [[v3, v5], [v4, 0]] v6 = self.getSkyline(v1[:v2 // 2]) v7 = self.getSkyline(v1[v2 // 2:]) return self.merge_skylines(v6, v7)
[]
[]
[]
10
class Solution: def getSkyline(self, buildings: 'List[List[int]]') -> 'List[List[int]]': """ Divide-and-conquer algorithm to solve skyline problem, which is similar with the merge sort algorithm. """ n = len(buildings) # The base cases if n == 0: r...
null
v0
[ "Any", "Dict[str, Any]" ]
None
def v0(self, v1: Any, v2: Dict[str, Any], **v3: Any) -> None: if hasattr(v1, 'template'): v4 = v1.template.name if v4 not in self.templates_rendered: if v2.get('shallow_tested') and v4 not in self.templates_rendered: self.shallow_tested_templates.add(v4) else:...
[]
[]
[]
9
import multiprocessing import os import random import shutil from functools import partial from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Type, Union, cast from unittest import TestLoader, TestSuite, mock, runner from unittest.result import TestResult from django.conf import settings from django.d...
null
v0
[ "List[Tensor]", "nn.Parameter", "nn.Module" ]
Optional[Tensor]
def v0(v1: List[Tensor], v2: nn.Parameter, v3: nn.Module) -> Optional[Tensor]: if len(v1) == 0: return None else: v4 = len(v1) v5 = torch.stack(v1) v6 = (v2 * torch.tanh(v3(v5)).mean(1)).sum(-1) v7 = F.softmax(v6, dim=0) v5 = torch.sum(v7.view(v4, 1, -1) * v5, dim...
[]
[ "torch" ]
[ "import torch", "from torch import Tensor, nn", "import torch.nn.functional as F" ]
10
from typing import Union, Dict, Optional, List import torch from torch import Tensor, nn import torch.nn.functional as F from torch_geometric.typing import NodeType, EdgeType, Metadata, Adj from torch_geometric.nn.dense import Linear from torch_geometric.utils import softmax from torch_geometric.nn.conv impo...
null
v0
[ "Iterable[str]" ]
Dict[str, str]
def v0(self, v1: Iterable[str]) -> Dict[str, str]: v2 = {frozenset(v): k for (v3, v4) in self._feature_dict.items()} v5: Dict[str, str] = OrderedDict() for v6 in v1: for (v7, v8) in v2.items(): if v6 in v7: v5[v6] = v8 continue return v5
[]
[ "collections" ]
[ "from collections import OrderedDict" ]
9
# @Author: dileep # @Last Modified by: dileep from collections import OrderedDict import os from typing import Tuple, Iterable, Sequence, Dict, Union import numpy as np import pandas as pd from sklearn.preprocessing import LabelEncoder, OneHotEncoder from sklearn.model_selection import train_test_split from . import...
null
v0
[ "Iterable[str]" ]
Tuple[np.ndarray, np.ndarray]
def v0(self, v1: Iterable[str]) -> Tuple[np.ndarray, np.ndarray]: v2 = self._feature_dict['binary-category'] or self._feature_dict['multi-category'] for v3 in v1: if v3 in v2: self.pp
[]
[]
[]
5
# @Author: dileep # @Last Modified by: dileep from collections import OrderedDict import os from typing import Tuple, Iterable, Sequence, Dict, Union import numpy as np import pandas as pd from sklearn.preprocessing import LabelEncoder, OneHotEncoder from sklearn.model_selection import train_test_split from . import...
null
v4
[ "List[str]" ]
None
def v4(v5: List[str]) -> None: for v6 in v5: print('loading command :: ', v6) v7 = v2(v6) v7.register()
[ { "name": "v2", "input_types": [ "str" ], "output_type": "v0", "code": "def v2(v3: str) -> v0:\n return importlib.import_module(v3)", "dependencies": [] } ]
[ "importlib" ]
[ "import importlib" ]
5
import importlib from typing import List class ModuleInterface: @staticmethod def register() -> None: """Init the command""" def import_module(name: str) -> ModuleInterface: return importlib.import_module(name) # type: ignore def load_commands(commands: List[str]) -> None: for command_nam...
[ "class v0:\n\n @staticmethod\n def v1() -> None:\n \"\"\"Init the command\"\"\"" ]
v0
[ "torch.Tensor", "torch.Tensor", "torch.Tensor", "torch.nn.parameter.Parameter" ]
Tuple[torch.Tensor, torch.Tensor]
def v0(self, v1: torch.Tensor, v2: torch.Tensor, v3: torch.Tensor, v4: torch.nn.parameter.Parameter) -> Tuple[torch.Tensor, torch.Tensor]: if not self._hide_goal: v2[..., 7:10] = v1[..., 7:10] v3[..., 7:10] = torch.full(v3[..., 7:10].shape, -float('inf')) return (v2, v3)
[]
[ "torch" ]
[ "import torch" ]
5
import os from typing import Tuple import numpy as np from numpy.random import MT19937, RandomState, SeedSequence import torch from gym import utils from gym.envs.mujoco import mujoco_env class Reacher3DEnv(mujoco_env.MujocoEnv, utils.EzPickle): def __init__(self, task_id=None, hide_goal=False): self.vie...
null
v0
[]
dict
def v0(self) -> dict: v1 = {'person': self.person, 'negative': self.negative, 'passive': self.passive, 'passive_negative': self.passive_negative} v2 = json.loads(json.dumps(v1, indent=2, ensure_ascii=False)) return v2
[]
[ "json" ]
[ "import json" ]
4
""" @author: Nathanael Jöhrmann """ import json import textwrap class Conjugations: def __init__(self): self.person = {} self.negative = ["", ""] self.passive = ["", ""] self.passive_negative = ["", ""] @property def summary(self) -> str: result = "" sep ...
null
v0
[ "dict" ]
None
def v0(self, v1: dict) -> None: self.person = v1['person'] self.negative = v1['negative'] self.passive = v1['passive'] self.passive_negative = v1['passive_negative']
[]
[]
[]
5
""" @author: Nathanael Jöhrmann """ import json import textwrap class Conjugations: def __init__(self): self.person = {} self.negative = ["", ""] self.passive = ["", ""] self.passive_negative = ["", ""] @property def summary(self) -> str: result = "" sep ...
null
v0
[ "object", "str" ]
Any
def v0(self, v1: object, v2: str) -> Any: if v2 not in v1: raise ValueError return v1[v2]
[]
[]
[]
4
# Copyright (c) 2020 Antti Kivi # Licensed under the MIT License """A module that contains the class that represents the project that the build script acts on. """ import importlib import json import logging import os from typing import Any, List from .support.system import System from .support import environment ...
null
v0
[ "object", "str" ]
str
def v0(self, v1: object, v2: str) -> str: v3 = None if self.SHARED_VERSION_KEY not in v1 else v1[self.SHARED_VERSION_KEY] if v2 not in v1: raise ValueError v4 = v1[v2] if self.VERSION_KEY not in v4: if v3: return v3 else: raise ValueError elif v4[self....
[]
[]
[]
14
# Copyright (c) 2020 Antti Kivi # Licensed under the MIT License """A module that contains the class that represents the project that the build script acts on. """ import importlib import json import logging import os from typing import Any, List from .support.system import System from .support import environment ...
null
v0
[ "str", "str" ]
float
def v0(self, v1: str, v2: str) -> float: v3 = np.array(self._get_vectors_from_sentene(v1)) v4 = np.array(self._get_vectors_from_sentene(v2)) v5 = self._calc_cosine_sim(v3, v4) v6 = np.max(v5, axis=0).mean() v7 = np.max(v5, axis=1).mean() return (v6 + v7) / 2.0
[]
[ "numpy" ]
[ "import numpy as np" ]
7
""" Copyright: Copyright 2019 by Katsuya SHIMABUKURO. License: MIT, see LICENSE for details. """ import pathlib import gzip import requests import tqdm import numpy as np from gensim.models import KeyedVectors FILE_ID = '0B7XkCwpI5KDYNlNUTTlSS21pQmM' SOURCE_URL = 'https://drive.google.com/uc?export=download&i...
null
v52
[ "Any", "Any", "Any", "Any", "float" ]
Any
def v52(v53, v54, v55, v56=40, v57: float=None): v58 = v53.symbols['exogenous'].index(v55) if v57 is None: try: v57 = numpy.sqrt(v53.exogenous.Σ[v58, v58]) except: v57 = numpy.sqrt(v53.exogenous.σ) v59 = numpy.zeros(len(v53.symbols['exogenous'])) v59[v58] = v57 ...
[ { "name": "v0", "input_types": [ "Any", "Any" ], "output_type": "Any", "code": "def v0(v1, v2):\n v3 = v1.shape\n v4 = v3[0]\n v5 = v3[1]\n v6 = np.zeros((v4, v5), dtype=int)\n for v7 in range(v4):\n for v8 in range(v5):\n v9 = v1[v7, v8, :]\n ...
[ "numpy", "xarray" ]
[ "import numpy", "import xarray as xr", "import numpy as np" ]
18
import numpy import pandas import xarray as xr import numpy as np from dolo.compiler.model import Model from dolo.numeric.optimize.ncpsolve import ncpsolve from dolo.numeric.optimize.newton import newton as newton_solver from dolo.numeric.optimize.newton import SerialDifferentiableFunction ## TODO: extend for mc proc...
null
v15
[ "Dict[Any, torch.nn.Module]" ]
torch.nn.Module
def v15(v16: Dict[Any, torch.nn.Module]) -> torch.nn.Module: v17 = len(v16) v18 = list(v16.values()) v19 = v18[0] for v20 in range(1, v17): v19 = v0(v19, v18[v20]) v19 = v8(v19, 1.0 / v17) return v19
[ { "name": "v0", "input_types": [ "Any", "Any" ], "output_type": "Any", "code": "def v0(v1, v2):\n v3 = v2.named_parameters()\n v4 = v1.named_parameters()\n v5 = dict(v4)\n with torch.no_grad():\n for (v6, v7) in v3:\n if v6 in v5:\n v5[v6]...
[ "torch" ]
[ "import torch" ]
8
import syft as sy import torch from typing import Dict from typing import Any import logging logger = logging.getLogger(__name__) def extract_batches_per_worker(federated_train_loader: sy.FederatedDataLoader): """Extracts the batches from the federated_train_loader and stores them in a dictionary (keys = ...
null
v0
[ "int" ]
Any
def v0(v1: int): v2 = 2 v3 = int(v1 / 2) v4 = torch.randn(v3, v2, requires_grad=True) - 5 v5 = torch.randn(v3, v2, requires_grad=True) + 5 v6 = torch.cat([v4, v5], dim=0) v7 = torch.zeros(v3, requires_grad=False).long() v8 = torch.ones(v3, requires_grad=False).long() v9 = torch.cat([v7, ...
[]
[ "torch" ]
[ "import torch" ]
10
import syft as sy import torch from typing import Dict from typing import Any import logging logger = logging.getLogger(__name__) def extract_batches_per_worker(federated_train_loader: sy.FederatedDataLoader): """Extracts the batches from the federated_train_loader and stores them in a dictionary (keys = ...
null
v0
[ "Sequence[str]", "Callable[..., None]" ]
Generator[Any, None, None]
def v0(self, v1: Sequence[str], v2: Callable[..., None]) -> Generator[Any, None, None]: yield self._solve_part1(v1, v2) yield self._solve_part2(v1, v2)
[]
[]
[]
3
from helpers.executor import Executor from helpers.util import * import itertools from itertools import * import re from re import * import numpy as np from typing import Any, Callable, Generator, Sequence day, year = None, None # TODO: Update day and year for current day split_seq = '\n' class Solution(Executor)...
null
v0
[]
int
def v0(self) -> int: v1 = self.tmp if not v1: v2 = self.storage while v2: v1.append(v2.pop()) return v1.pop()
[]
[]
[]
7
class MyQueue: def __init__(self): """ Uses two stacks to implement a Queue. Storage holds elements pushed right before the first pop. """ self.storage, self.tmp = [], [] def push(self, x: int) -> None: """ Unconditionally add to storage. Equivalent to stack.push.""" ...
null
v0
[ "str", "str" ]
Any
def v0(self, v1: str, v2: str): v3 = {'grant_type': 'password', 'login': v1, 'password': v2, 'client_id': 'other.conta', 'client_secret': 'yQPeLzoHuJzlMMSAjC-LgNUJdUecx8XO'} v4 = requests.post(self.auth_url, json=v3, headers=self.headers) v5 = self._handle_response(v4) return v5
[]
[ "requests" ]
[ "import requests", "from requests import Response" ]
5
import json import os import uuid from typing import Tuple import requests from qrcode import QRCode from requests import Response PAYMENT_EVENT_TYPES = ( 'TransferOutEvent', 'TransferInEvent', 'TransferOutReversalEvent', 'BarcodePaymentEvent', 'DebitPurchaseEvent', 'DebitPurchaseReversalEvent...
null
v0
[ "str", "Any", "str" ]
Any
def v0(self, v1: str, v2, v3: str): v4 = self._password_auth(v1, v2) self.headers['Authorization'] = f"Bearer {v4['access_token']}" v5 = {'qr_code_id': v3, 'type': 'login-webapp'} v6 = requests.post(self.proxy_list_app_url['lift'], json=v5, headers=self.headers) v4 = self._handle_response(v6) se...
[]
[ "requests", "uuid" ]
[ "import uuid", "import requests", "from requests import Response" ]
10
import json import os import uuid from typing import Tuple import requests from qrcode import QRCode from requests import Response PAYMENT_EVENT_TYPES = ( 'TransferOutEvent', 'TransferInEvent', 'TransferOutReversalEvent', 'BarcodePaymentEvent', 'DebitPurchaseEvent', 'DebitPurchaseReversalEvent...
null
v0
[ "int", "int" ]
None
def v0(self, v1: int, v2: int, **v3) -> None: if v1 == 0: return if v1 % self.save_iters == 0: self._save_gen_learner(iteration=v1, epoch=v2)
[]
[]
[]
5
from fastai.basic_train import Learner, LearnerCallback from fastai.vision.gan import GANLearner class GANSaveCallback(LearnerCallback): """A `LearnerCallback` that saves history of metrics while training `learn` into CSV `filename`.""" def __init__( self, learn: GANLearner, learn_gen...
null
v0
[ "int", "int" ]
Any
def v0(self, v1: int, v2: int): v3 = '{}_{}_{}'.format(self.filename, v2, v1) self.learn_gen.save(v3)
[]
[]
[]
3
from fastai.basic_train import Learner, LearnerCallback from fastai.vision.gan import GANLearner class GANSaveCallback(LearnerCallback): """A `LearnerCallback` that saves history of metrics while training `learn` into CSV `filename`.""" def __init__( self, learn: GANLearner, learn_gen...
null
v0
[]
bool
def v0(self) -> bool: if os.path.exists(f'{self._file_path}'): return True else: self._create_dir() return False
[]
[ "os" ]
[ "import os" ]
6
#!/usr/bin/env python3 # # Author: eaglewings # E-Mail: ZWFnbGV3aW5ncy55aUBnbWFpbC5jb20= # Created Time: 2019-04-17 15:17 # Last Modified: # Description: # - Project: BT Trackers Updater # - File Name: update.py # - Trackers Updater import os import re from typing import NoReturn class Filer...
null
v0
[]
NoReturn
def v0(self) -> NoReturn: v1 = False with open(self._path, 'r+') as v2: v3 = v2.readlines() v2.seek(0) v2.truncate() for v4 in v3: if re.search('bt-tracker=.*', v4): v4 = v4.replace(v4, f'bt-tracker={self._trackers}\n') v2.write(v4) ...
[]
[ "re" ]
[ "import re" ]
18
#!/usr/bin/env python3 # # Author: eaglewings # E-Mail: ZWFnbGV3aW5ncy55aUBnbWFpbC5jb20= # Created Time: 2019-04-17 15:17 # Last Modified: # Description: # - Project: BT Trackers Updater # - File Name: update.py # - Trackers Updater import os import re from typing import NoReturn class Filer...
null
v0
[ "Any" ]
Iterable[dict]
def v0(v1) -> Iterable[dict]: with open(v1) as v2: v3 = csv.DictReader(v2) yield from v3
[]
[ "csv" ]
[ "import csv" ]
4
#!/usr/bin/env python3 """ An example script to send data to CommCare using the Submission API Usage: $ export CCHQ_PROJECT_SPACE=my-project-space $ export CCHQ_CASE_TYPE=person $ export CCHQ_USERNAME=user@example.com $ export CCHQ_PASSWORD=MijByG_se3EcKr.t $ export CCHQ_USER_ID=c0ffeeeeeb574eb8b5...
null
v0
[]
str
def v0() -> str: v1 = datetime.now(tz=timezone.utc) v2 = v1.isoformat(timespec='milliseconds') v3 = v2.replace('+00:00', 'Z') return v3
[]
[ "datetime" ]
[ "from datetime import datetime, timezone" ]
5
#!/usr/bin/env python3 """ An example script to send data to CommCare using the Submission API Usage: $ export CCHQ_PROJECT_SPACE=my-project-space $ export CCHQ_CASE_TYPE=person $ export CCHQ_USERNAME=user@example.com $ export CCHQ_PASSWORD=MijByG_se3EcKr.t $ export CCHQ_USER_ID=c0ffeeeeeb574eb8b5...
null
v0
[]
argparse.ArgumentParser
def v0() -> argparse.ArgumentParser: v1 = argparse.ArgumentParser() v1.add_argument('--mobilecoind-host', default='localhost', type=str, help='Mobilecoind host') v1.add_argument('--mobilecoind-port', default='4444', type=str, help='Mobilecoind port') v1.add_argument('--key-dir', required=True, type=str,...
[]
[ "argparse" ]
[ "import argparse" ]
7
#!/usr/bin/env python3 # Copyright (c) 2018-2021 The MobileCoin Foundation """ The purpose of this script is to print the balances for all keys in a given account directory. Example setup and usage: ``` python3 balances.py --key-dir ../../../target/sample_data/master/keys/ ``` """ import argparse import grpc imp...
null
v7
[ "Any", "int" ]
Any
def v7(v8, v9: int): v10 = [] for v11 in range(1, v9): v10.append(v0(v8, v9 - v11, v11 - 1, v11)) v12 = v0(v8, 0, v9 - 1, v9) v13 = v10.pop() while len(v10) > 0: v13 = pd.merge(v13, v10.pop(), on='ID') v14 = v12['price{}'.format(v9)] return (v13, v14)
[ { "name": "v0", "input_types": [ "Any", "int", "int", "int" ], "output_type": "Any", "code": "def v0(v1, v2: int, v3: int, v4: int):\n v5 = v1.copy()\n for v6 in range(v3):\n remove_row_from_tail(v5)\n for v6 in range(v2):\n remove_row_from_head(v5)...
[ "pandas" ]
[ "import pandas as pd" ]
10
from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split import pandas as pd import sqlalchemy from config.config import symbol,backward_steps import joblib from df_functions import * def prepare_single_dataset(df,remove_from_heads:int,remove_from_tails:int,label:int): ...
null
v0
[ "'List[List[int]]'" ]
'bool'
def v0(self, v1: 'List[List[int]]') -> 'bool': v2 = 0 v3 = v4 = math.inf v5 = v6 = -math.inf v7 = set() for v8 in v1: v3 = min(v3, v8[0]) v4 = min(v4, v8[1]) v5 = max(v5, v8[2]) v6 = max(v6, v8[3]) v2 += (v8[2] - v8[0]) * (v8[3] - v8[1]) v9 = ((v8[0], ...
[]
[ "math" ]
[ "import math" ]
19
import math class Solution: def isRectangleCover(self, rectangles: 'List[List[int]]') -> 'bool': area = 0 x1 = y1 = math.inf x2 = y2 = -math.inf table = set() for rec in rectangles: x1 = min(x1, rec[0]) y1 = min(y1, rec[1]) x2 = max(x2, rec...
null
v0
[]
'Arrow'
def v0(self, **v1: Any) -> 'Arrow': v2 = {} for (v3, v4) in v1.items(): if v3 in self._ATTRS: v2[v3] = v4 elif v3 in ['week', 'quarter']: raise ValueError(f'Setting absolute {v3} is not supported.') elif v3 not in ['tzinfo', 'fold']: raise ValueError(f...
[]
[]
[]
18
""" Provides the :class:`Arrow <arrow.arrow.Arrow>` class, an enhanced ``datetime`` replacement. """ import calendar import sys from datetime import date from datetime import datetime as dt_datetime from datetime import time as dt_time from datetime import timedelta from datetime import tzinfo as dt_tzinfo from math...
null
v0
[ "float", "str" ]
str
def v0(v1: float, v2: str='hms') -> str: (v3, v4) = divmod(v1, 60) if v2 == 'ms': v5 = '{:d}m:{:02d}s'.format(int(v3), int(v4)) elif v2 == 'hms': (v6, v3) = divmod(v3, 60) v5 = '{:d}h:{:02d}m:{:02d}s'.format(int(v6), int(v3), int(v4)) else: raise Exception("Format {} not ...
[]
[]
[]
10
#!/usr/bin/env python # Copyright 2018 Division of Medical Image Computing, German Cancer Research Center (DKFZ). # # 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...
null
v0
[ "torch.nn.Module", "Tuple[str, Any]", "bool" ]
torch.nn.Module
def v0(v1: torch.nn.Module, v2: Tuple[str, Any], v3: bool=True) -> torch.nn.Module: for v4 in v1.parameters(): if v3: assert not hasattr(v4, v2[0]), 'param {} already has attr {} (w/ val {})'.format(v4, v2[0], getattr(v4, v2[0])) setattr(v4, v2[0], v2[1]) return v1
[]
[]
[]
6
#!/usr/bin/env python # Copyright 2018 Division of Medical Image Computing, German Cancer Research Center (DKFZ). # # 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...
null
v5
[ "torch.nn.Module", "float", "Iterable" ]
list
def v5(v6: torch.nn.Module, v7: float=0.0, v8: Iterable=('norm',)) -> list: if v7 is None: v7 = 0.0 v9 = [torch.nn.BatchNorm1d, torch.nn.BatchNorm2d, torch.nn.BatchNorm3d, torch.nn.InstanceNorm1d, torch.nn.InstanceNorm2d, torch.nn.InstanceNorm3d, torch.nn.LayerNorm, torch.nn.GroupNorm, torch.nn.SyncBatc...
[ { "name": "v0", "input_types": [ "torch.nn.Module", "Tuple[str, Any]", "bool" ], "output_type": "torch.nn.Module", "code": "def v0(v1: torch.nn.Module, v2: Tuple[str, Any], v3: bool=True) -> torch.nn.Module:\n for v4 in v1.parameters():\n if v3:\n assert no...
[ "numpy", "torch" ]
[ "from torch.utils.tensorboard import SummaryWriter", "import numpy as np", "import torch" ]
29
#!/usr/bin/env python # Copyright 2018 Division of Medical Image Computing, German Cancer Research Center (DKFZ). # # 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...
null
v0
[ "str", "torch.nn.Module", "torch.optim.Optimizer" ]
Tuple
def v0(v1: str, v2: torch.nn.Module, v3: torch.optim.Optimizer) -> Tuple: v4 = torch.load(os.path.join(v1, 'params.pth')) v2.load_state_dict(v4['state_dict']) v3.load_state_dict(v4['optimizer']) with open(os.path.join(v1, 'monitor_metrics.pickle'), 'rb') as v5: v6 = pickle.load(v5) v7 = v4['...
[]
[ "os", "pickle", "torch" ]
[ "import os, sys", "import pickle", "from torch.utils.tensorboard import SummaryWriter", "import torch" ]
8
#!/usr/bin/env python # Copyright 2018 Division of Medical Image Computing, German Cancer Research Center (DKFZ). # # 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...
null
v0
[ "torch.nn.Module", "torch.optim.Optimizer", "dict", "int" ]
Any
def v0(self, v1: torch.nn.Module, v2: torch.optim.Optimizer, v3: dict, v4: int): v5 = np.mean(np.array([[0 if ii is None or np.isnan(ii) else ii for v6 in v3['val'][sc]] for v7 in self.cf.model_selection_criteria]), 0) v8 = [v6 for v6 in v5[1:]] v9 = np.argsort(v8, kind='stable')[::-1] + 1 v9 = v9[v9 >=...
[]
[ "numpy", "os", "pickle", "subprocess", "torch" ]
[ "import os, sys", "import subprocess", "import pickle", "from torch.utils.tensorboard import SummaryWriter", "import numpy as np", "import torch" ]
28
#!/usr/bin/env python # Copyright 2018 Division of Medical Image Computing, German Cancer Research Center (DKFZ). # # 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...
null
v0
[ "Tensor", "Tensor", "Tensor", "Tensor", "Tensor", "Tensor", "Tensor" ]
Any
def v0(self, v1: Tensor, v2: Tensor, v3: Tensor, v4: Tensor, v5: Tensor, v6: Tensor, v7: Tensor): v8 = self.positional_encoding(self.src_tok_emb(v1)) v9 = self.positional_encoding(self.tgt_tok_emb(v2)) v10 = self.transformer_encoder(v8, v3, v5) v11 = self.transformer_decoder(v9, v10, v4, None, v6, v7) ...
[]
[]
[]
6
import torch # import torchtext import torch.nn as nn # from torchtext.vocab import Vocab, build_vocab_from_iterator # from torchtext.utils import unicode_csv_reader # from torchtext.data.datasets_utils import _RawTextIterableDataset from torch import Tensor from typing import Iterable, List # import sentencepiece as s...
null
v25
[ "Any", "tuple", "bool" ]
Any
def v25(self, v26, v27: tuple, v28: bool): (v29, v30) = v0(v26, v27) v31 = {'command': 'run-method', 'static': v28, 'hash-code': self._hash_code, 'name': v29['name'], 'argument-types': v29['arguments'], 'argument-deserialization-types': v30} v31['arguments'] = v17(v29, v27) if self._bridge._closed: ...
[ { "name": "v0", "input_types": [ "Any", "Any" ], "output_type": "Any", "code": "def v0(v1, v2):\n v3 = None\n for v4 in v1:\n if _check_single_method_spec(v4, v2):\n v3 = v4\n break\n if v3 is None:\n raise Exception('Incorrect arguments. ...
[ "copy", "numpy" ]
[ "import numpy as np", "import copy" ]
9
import json import re import time import typing import warnings import inspect import numpy as np import zmq from weakref import WeakSet import threading import copy import sys from threading import Lock class DataSocket: """ Wrapper for ZMQ socket that sends and recieves dictionaries Includes ZMQ client,...
null
v0
[ "tuple" ]
pd.DataFrame
def v0(v1: tuple) -> pd.DataFrame: v2 = None for v3 in filter(lambda df: v3 is not None and len(v3) > 0, v1): v3['metric'] = v3.index v4 = pd.melt(v3, id_vars='metric', var_name='date') v4 = v4.dropna(axis=0, how='any') if len(v4) == 0: continue if v2 is None:...
[]
[ "pandas" ]
[ "import pandas as pd" ]
15
#!/usr/bin/python3 """ Responsible for ingesting data related to the business performance over time. Data is placed into the asx_company_financial_metric collection, ready for the core viewer app to use. Stocks whose financial details have been retrieved in the past month are skipped. """ import pymongo import argparse...
null
v0
[ "tuple", "str" ]
dict
def v0(v1: tuple, v2: str) -> dict: v3 = {'asx_code': v2, 'fetch_date': v1.Index, 'volume': v1.Volume, 'last_price': v1.Close, 'day_low_price': v1.Low, 'day_high_price': v1.High, 'open_price': v1.Open, 'error_code': '', 'error_descr': '', 'change_price': v1.change_price, 'change_in_percent': v1.change_in_percent} ...
[]
[]
[]
3
#!/usr/bin/python3 """ Responsible for ingesting data related to the business performance over time. Data is placed into the asx_company_financial_metric collection, ready for the core viewer app to use. Stocks whose financial details have been retrieved in the past month are skipped. """ import pymongo import argparse...
null
v0
[ "str" ]
bool
def v0(self, v1: str) -> bool: (v2, v3) = self.twopointer(0, len(v1) - 1, v1) if v2 >= v3: return True return self.valid(v2 + 1, v3, v1) or self.valid(v2, v3 - 1, v1)
[]
[]
[]
5
class Solution: def validPalindrome(self, s: str) -> bool: left, right = self.twopointer(0, len(s) - 1, s) if left >= right : return True return self.valid(left + 1, right, s) or self.valid(left, right - 1, s) def valid(self, left, right, s) : l, r = self.twopoin...
null
v1
[ "Sequence[str]", "v0" ]
int
def v1(v2: Sequence[str], *, v3: v0=COMMANDS) -> int: v4 = ArgumentParser(prog='python3 -m deal') v4.add_argument('command', choices=sorted(v3)) (v5, v6) = v4.parse_known_args(v2) v7 = v3[v5.command] return v7(v6)
[]
[ "argparse" ]
[ "from argparse import ArgumentParser" ]
6
# built-in from argparse import ArgumentParser from types import MappingProxyType from typing import Callable, Mapping, Sequence # app from ._lint import lint_command from ._memtest import memtest_command from ._stub import stub_command from ._test import test_command CommandsType = Mapping[str, Callable[[Sequence[s...
[ "v0 = Mapping[str, Callable[[Sequence[str]], int]]" ]
v0
[]
None
def v0(self) -> None: self.clean_db() self.client = self.app.test_client()
[]
[]
[]
3
# 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
[ "float", "float", "Any" ]
Any
def v0(self, v1: float, v2: float, v3): v4 = self.delta(v2, v1) self._item_group.viewroot.document().resizeSelection(v4)
[]
[]
[]
3
# -*- coding: utf-8 -*- import logging from math import floor from PyQt5.QtCore import ( QPointF, QRectF, Qt ) from PyQt5.QtGui import ( QPainterPath, QKeyEvent, QMouseEvent ) from PyQt5.QtWidgets import ( QGraphicsItem, QGraphicsItemGroup, QGraphicsPathItem, QGraphicsSceneMouse...
null
v0
[ "float", "float" ]
float
def v0(self, v1: float, v2: float) -> float: (v3, v4) = self._bounds v5 = int(floor((v1 - v2) / self._BASE_WIDTH)) if v5 > 0 and v5 > v4: v5 = v4 elif v5 < 0 and abs(v5) > v3: v5 = -v3 return v5
[]
[ "math" ]
[ "from math import floor" ]
8
# -*- coding: utf-8 -*- import logging from math import floor from PyQt5.QtCore import ( QPointF, QRectF, Qt ) from PyQt5.QtGui import ( QPainterPath, QKeyEvent, QMouseEvent ) from PyQt5.QtWidgets import ( QGraphicsItem, QGraphicsItemGroup, QGraphicsPathItem, QGraphicsSceneMouse...
null
v0
[ "float" ]
Any
def v0(self, v1: float): v2 = self._item_group.childItems() if v2: v3 = v2[0].partItem() v4 = '+%d' % v1 if v1 >= 0 else '%d' % v1 v3.updateStatusBar(v4) self.setX(self._BASE_WIDTH * v1)
[]
[]
[]
7
# -*- coding: utf-8 -*- import logging from math import floor from PyQt5.QtCore import ( QPointF, QRectF, Qt ) from PyQt5.QtGui import ( QPainterPath, QKeyEvent, QMouseEvent ) from PyQt5.QtWidgets import ( QGraphicsItem, QGraphicsItemGroup, QGraphicsPathItem, QGraphicsSceneMouse...
null
v0
[ "str" ]
None
def v0(self, v1: str) -> None: self.file1.write(v1) self.file2.write(v1)
[]
[]
[]
3
from typing import Any import sys import time import os import tempfile class Logger2(): def __init__(self, file1: Any, file2: Any): self.file1 = file1 self.file2 = file2 def write(self, data: str) -> None: self.file1.write(data) self.file2.write(data) def flush(self) -> ...
null
v0
[]
None
def v0(self) -> None: self.file1.flush() self.file2.flush()
[]
[]
[]
3
from typing import Any import sys import time import os import tempfile class Logger2(): def __init__(self, file1: Any, file2: Any): self.file1 = file1 self.file2 = file2 def write(self, data: str) -> None: self.file1.write(data) self.file2.write(data) def flush(self) -> ...
null
v0
[]
dict
def v0(self) -> dict: assert self._time_start is not None return dict(start_time=self._time_start - 0, end_time=self._time_stop - 0, elapsed_sec=self._time_stop - self._time_start)
[]
[]
[]
3
from typing import Any import sys import time import os import tempfile class Logger2(): def __init__(self, file1: Any, file2: Any): self.file1 = file1 self.file2 = file2 def write(self, data: str) -> None: self.file1.write(data) self.file2.write(data) def flush(self) -> ...
null
v0
[ "str" ]
Dict[str, any]
def v0(v1: str) -> Dict[str, any]: v2 = {'TEXT_NUMBER': {'type': 'string'}, 'DATE': {'type': 'string', 'format': 'date'}, 'DATETIME': {'type': 'string', 'format': 'date-time'}} return v2.get(v1, {'type': 'string'})
[]
[]
[]
3
# # Copyright (c) 2021 Airbyte, Inc., all rights reserved. # import json from datetime import datetime from typing import Dict, Generator import smartsheet from airbyte_cdk import AirbyteLogger from airbyte_cdk.models import ( AirbyteCatalog, AirbyteConnectionStatus, AirbyteMessage, AirbyteRecordMess...
null
v3
[ "Dict" ]
Dict
def v3(v4: Dict) -> Dict: v5 = {i['title']: v0(i['type']) for v6 in v4['columns']} v7 = {'$schema': 'http://json-schema.org/draft-07/schema#', 'type': 'object', 'properties': v5} return v7
[ { "name": "v0", "input_types": [ "str" ], "output_type": "Dict[str, any]", "code": "def v0(v1: str) -> Dict[str, any]:\n v2 = {'TEXT_NUMBER': {'type': 'string'}, 'DATE': {'type': 'string', 'format': 'date'}, 'DATETIME': {'type': 'string', 'format': 'date-time'}}\n return v2.get(v1, {...
[]
[]
4
# # Copyright (c) 2021 Airbyte, Inc., all rights reserved. # import json from datetime import datetime from typing import Dict, Generator import smartsheet from airbyte_cdk import AirbyteLogger from airbyte_cdk.models import ( AirbyteCatalog, AirbyteConnectionStatus, AirbyteMessage, AirbyteRecordMess...
null
v0
[ "str" ]
str
def v0(self, v1: str) -> str: v2 = self._get_Gromos_input_header(v1) if v1 == 'production': v2 += self._get_Gromos_production_body() else: raise NotImplementedError(f'Something went wrong with {v1} input.') return v2
[]
[]
[]
7
import datetime from os import stat class GromosFactory: """Class to build the string needed to create a Gromos input file (*.imd), a make_script fiel (*.arg) and a job file (*.job)""" def __init__(self, configuration: dict, structure: str) -> None: self.configuration = configuration self.str...
null
v0
[ "str" ]
str
def v0(self, v1: str) -> str: v2 = datetime.date.today() v3 = f'TITLE\nAutomatically generated input file for {v1} run with constph\nVersion {v2}\nEND\n' return v3
[]
[ "datetime" ]
[ "import datetime" ]
4
import datetime from os import stat class GromosFactory: """Class to build the string needed to create a Gromos input file (*.imd), a make_script fiel (*.arg) and a job file (*.job)""" def __init__(self, configuration: dict, structure: str) -> None: self.configuration = configuration self.str...
null
v0
[]
str
def v0(self) -> str: v1 = self.configuration['search_run']['search_parameters']['NSM'] v2 = self.configuration['search_run']['search_parameters']['NSTLIM'] v3 = self.configuration['search_run']['search_parameters']['dt'] v4 = self.configuration['search_run']['search_parameters']['ATMNR1'] v5 = self....
[]
[]
[]
16
import datetime from os import stat class GromosFactory: """Class to build the string needed to create a Gromos input file (*.imd), a make_script fiel (*.arg) and a job file (*.job)""" def __init__(self, configuration: dict, structure: str) -> None: self.configuration = configuration self.str...
null
v0
[ "Tensor", "Tensor", "Tensor", "Tensor", "Tensor", "Tensor" ]
Tuple[Tensor, Tensor, Tensor, Tensor]
def v0(v1: Tensor, v2: Tensor, v3: Tensor, v4: Tensor, v5: Tensor, v6: Tensor) -> Tuple[Tensor, Tensor, Tensor, Tensor]: (v7, v8, v9, v10, v11, v12) = (v1[0], v2[0], v3[0], v4[0], v5[0], v6[0]) for v13 in range(1, len(v1)): (v14, v15, v16, v17, v18, v19) = (v1[v13], v2[v13], v3[v13], v4[v13], v5[v13], v...
[]
[]
[]
14
# Copyright The PyTorch Lightning team. # # 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
[]
list[res.Response]
def v0(self, *v1: Any, **v2: Any) -> list[res.Response]: if self.github_repo: self.action(self.github_repo, *v1, **v2) else: for v3 in self.config_manager.config.github_selected_repos: self.action(v3, *v1, **v2) return self.responses
[]
[]
[]
7
"""Base Github use case.""" from __future__ import annotations import traceback from typing import Any import git_portfolio.config_manager as cm import git_portfolio.github_service as gs import git_portfolio.responses as res class GhUseCase: """Github use case.""" def __init__( self, config...
null
v0
[ "Tuple[Tuple[str]]" ]
Any
def v0(self, v1: Tuple[Tuple[str]]): for v2 in v1: if not isinstance(v2, Tuple) or len(v2) < 2: continue self.register_font(v2)
[]
[ "typing" ]
[ "from typing import Dict, Tuple, Any, Optional" ]
5
# -*- coding: utf-8 -*- from typing import Dict, Tuple, Any, Optional import re import string import ast import codecs import argparse import yaml from reportlab.pdfgen import canvas from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.cidfonts import UnicodeCIDFont from reportlab.pdfbase.ttfonts import TT...
null
v0
[ "Dict" ]
str
def v0(self, v1: Dict) -> str: v2 = v1.get('value', '') v3 = re.search('\\$(.*)$', v2) if v3: v4 = v3.group(1) v5 = self._input_data.get(v4, '') v6 = string.Template(v3.group(0)) v2 = v6.substitute(**{v4: v5}) return v2
[]
[ "re", "string" ]
[ "import re", "import string" ]
9
# -*- coding: utf-8 -*- from typing import Dict, Tuple, Any, Optional import re import string import ast import codecs import argparse import yaml from reportlab.pdfgen import canvas from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.cidfonts import UnicodeCIDFont from reportlab.pdfbase.ttfonts import TT...
null
v0
[ "float", "float", "str", "float", "str" ]
Any
def v0(self, v1: float, v2: float, v3: str, v4: float, v5: str): if not v3: return self._canvas.setFont(v5, v4) self._canvas.drawString(v1, v2, v3)
[]
[]
[]
5
# -*- coding: utf-8 -*- from typing import Dict, Tuple, Any, Optional import re import string import ast import codecs import argparse import yaml from reportlab.pdfgen import canvas from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.cidfonts import UnicodeCIDFont from reportlab.pdfbase.ttfonts import TT...
null
v0
[ "float", "float", "str", "float", "str" ]
Any
def v0(self, v1: float, v2: float, v3: str, v4: float, v5: str): if not v3: return v6 = self._canvas.beginText() v6.setTextOrigin(v1, v2) v6.setFont(v5, v4) v6.textLines(v3) self._canvas.drawText(v6)
[]
[]
[]
8
# -*- coding: utf-8 -*- from typing import Dict, Tuple, Any, Optional import re import string import ast import codecs import argparse import yaml from reportlab.pdfgen import canvas from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.cidfonts import UnicodeCIDFont from reportlab.pdfbase.ttfonts import TT...
null
v0
[ "Dict" ]
Any
def v0(self, v1: Dict): v2 = self.unit2dot(v1.get('x')) v3 = self.unit2dot(v1.get('y')) v4 = self.get_value(v1) (v5, v6) = self.get_font(v1) self.put_textbox(v2, v3, v4, v5, v6)
[]
[]
[]
6
# -*- coding: utf-8 -*- from typing import Dict, Tuple, Any, Optional import re import string import ast import codecs import argparse import yaml from reportlab.pdfgen import canvas from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.cidfonts import UnicodeCIDFont from reportlab.pdfbase.ttfonts import TT...
null
v0
[ "Dict" ]
Any
def v0(self, v1: Dict): self.line_style(v1) v2 = self.unit2dot(v1.get('x')) v3 = self.unit2dot(v1.get('y')) v4 = self.unit2dot(v1.get('dx')) v5 = self.unit2dot(v1.get('dy')) self._canvas.line(v2, v3, v2 + v4, v3 + v5)
[]
[]
[]
7
# -*- coding: utf-8 -*- from typing import Dict, Tuple, Any, Optional import re import string import ast import codecs import argparse import yaml from reportlab.pdfgen import canvas from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.cidfonts import UnicodeCIDFont from reportlab.pdfbase.ttfonts import TT...
null
v0
[ "Dict" ]
Any
def v0(self, v1: Dict): self.line_style(v1) v2 = v1.get('points') v3 = self.unit2dot(v2[0].get('x')) v4 = self.unit2dot(v2[0].get('y')) v5 = v1.get('close') v6 = self._canvas.beginPath() v6.moveTo(v3, v4) for v7 in v2[1:]: v8 = self.unit2dot(v7.get('x')) v9 = self.unit2do...
[]
[]
[]
17
# -*- coding: utf-8 -*- from typing import Dict, Tuple, Any, Optional import re import string import ast import codecs import argparse import yaml from reportlab.pdfgen import canvas from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.cidfonts import UnicodeCIDFont from reportlab.pdfbase.ttfonts import TT...
null
v0
[ "Dict" ]
Any
def v0(self, v1: Dict): self.line_style(v1) v2 = self.unit2dot(v1.get('x')) v3 = self.unit2dot(v1.get('y')) v4 = self.unit2dot(v1.get('dx')) v5 = self.unit2dot(v1.get('dy')) v6 = self.unit2dot(v1.get('sx')) v7 = self.unit2dot(v1.get('sy')) v8 = int(v1.get('num')) self._canvas.line(v2...
[]
[]
[]
14
# -*- coding: utf-8 -*- from typing import Dict, Tuple, Any, Optional import re import string import ast import codecs import argparse import yaml from reportlab.pdfgen import canvas from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.cidfonts import UnicodeCIDFont from reportlab.pdfbase.ttfonts import TT...
null
v0
[ "Dict" ]
Any
def v0(self, v1: Dict): v2 = self.unit2dot(v1.get('y')) v3 = self.unit2dot(v1.get('year_x')) v4 = self.unit2dot(v1.get('month_x')) v5 = self.unit2dot(v1.get('value_x')) v6 = self.unit2dot(v1.get('ijo_x')) v7 = self.unit2dot(v1.get('dy')) v8 = self.unit2dot(v1.get('caption_x')) (v9, v10) ...
[]
[]
[]
32
# -*- coding: utf-8 -*- from typing import Dict, Tuple, Any, Optional import re import string import ast import codecs import argparse import yaml from reportlab.pdfgen import canvas from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.cidfonts import UnicodeCIDFont from reportlab.pdfbase.ttfonts import TT...
null
v0
[ "Dict" ]
Any
def v0(self, v1: Dict): v2 = self.unit2dot(v1.get('y')) v3 = self.unit2dot(v1.get('year_x')) v4 = self.unit2dot(v1.get('month_x')) v5 = self.unit2dot(v1.get('value_x')) v6 = self.unit2dot(v1.get('dy')) v7 = self.get_value(v1) (v8, v9) = self.get_font(v1) try: v10 = ast.literal_ev...
[]
[ "ast" ]
[ "import ast" ]
21
# -*- coding: utf-8 -*- from typing import Dict, Tuple, Any, Optional import re import string import ast import codecs import argparse import yaml from reportlab.pdfgen import canvas from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.cidfonts import UnicodeCIDFont from reportlab.pdfbase.ttfonts import TT...
null
v0
[]
str
def v0(self) -> str: v1 = self._hdr if self._hdr else self.uid v2 = '>' + v1 + '\n' for v3 in self.residues: if v3.pdb_label: v4 = '{}{}'.format(v3.pdb_residue_num, v3.pdb_insert_code if v3.pdb_insert_code else ' ') v5 = [v3.aa, v3.seq_num, v4, v3.pdb_aa] else: ...
[]
[]
[]
11
""" Manipulate protein sequences and alignments """ # core import io import gzip import logging import re import functools # pip import dendropy # local from cathpy.core import error as err from cathpy.core.tests import is_valid_domain_id from cathpy.core.models import AminoAcid, AminoAcids, Residue, Segment LOG = ...
null
v131
[]
[v0]
def v131(self) -> [v0]: v132 = (self.seqres_sequence, self.atom_sequence) return v132
[]
[]
[]
3
""" Manipulate protein sequences and alignments """ # core import io import gzip import logging import re import functools # pip import dendropy # local from cathpy.core import error as err from cathpy.core.tests import is_valid_domain_id from cathpy.core.models import AminoAcid, AminoAcids, Residue, Segment LOG = ...
[ "class v0(object):\n v1 = '[.\\\\-]'\n v2 = False\n\n def __init__(self, v3: str, v4: str, *, v5=None, v6=None):\n self._hdr = v3\n self._seq = v4\n try:\n v7 = v0.split_hdr(v3)\n except:\n raise err.GeneralError('caught error while parsing sequence header:...
v0
[ "nn.Module", "int", "Any" ]
nn.Module
def v0(v1: nn.Module, v2: int, v3='auto', **v4) -> nn.Module: v5 = v1.__class__ if v1.in_channels == v2: warnings.warn('make_n_channel_input call is spurious') return v1 v6 = v5(v2, out_channels=v1.out_channels, kernel_size=v4.get('kernel_size', v1.kernel_size), stride=v4.get('stride', v1.st...
[]
[ "math", "torch", "warnings" ]
[ "import math", "import warnings", "import torch", "from torch import Tensor, nn" ]
16
import math import warnings import torch from typing import List, Union from torch import Tensor, nn from ..common import EncoderModule, _take __all__ = ["GenericTimmEncoder", "make_n_channel_input_std_conv"] class GenericTimmEncoder(EncoderModule): def __init__(self, timm_encoder: Union[nn.Module, str], layer...
null
v0
[ "tf.TensorShape" ]
Any
def v0(self, v1: tf.TensorShape): v2 = self._init_weight(self.num_positions, self.embedding_dim) self.weight = self.add_weight(name='embeddings', shape=[self.num_positions, self.embedding_dim]) v2 = tf.cast(v2, dtype=self.weight.dtype) self.weight.assign(v2) super().build(v1)
[]
[ "tensorflow" ]
[ "import tensorflow as tf" ]
6
# coding=utf-8 # Copyright 2021, Google Inc. and The HuggingFace Inc. team. All rights reserved. # # 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...
null
v0
[ "dict" ]
np.ndarray
def v0(v1: dict) -> np.ndarray: v2 = np.array(v1['real']) if v1.get('imag'): v2 = v2 + 1j * np.array(v1['imag']) return v2
[]
[ "numpy" ]
[ "import numpy as np" ]
5
"""General-purpose utilities.""" import numpy as np from scipy.linalg import expm import random import math import operator import sys import json import openfermion from openfermion import hermitian_conjugated from openfermion.ops import SymbolicOperator from networkx.readwrite import json_graph import lea import col...
null
v0
[ "np.ndarray" ]
dict
def v0(v1: np.ndarray) -> dict: v2 = {} if np.iscomplexobj(v1): v2['real'] = v1.real.tolist() v2['imag'] = v1.imag.tolist() else: v2['real'] = v1.tolist() return v2
[]
[ "numpy" ]
[ "import numpy as np" ]
8
"""General-purpose utilities.""" import numpy as np from scipy.linalg import expm import random import math import operator import sys import json import openfermion from openfermion import hermitian_conjugated from openfermion.ops import SymbolicOperator from networkx.readwrite import json_graph import lea import col...
null
v0
[ "int", "int" ]
List[int]
def v0(v1: int, v2: int) -> List[int]: if pow(2, v2) < v1: sys.exit('Insufficient number of bits for representing the number {}'.format(v1)) v3 = bin(v1) v3 = v3[2:len(v3)] v4 = [int(x) for v5 in list(v3)] if len(v4) < v2: v6 = v2 - len(v4) v4 = [int(v5) for v5 in list(np.zer...
[]
[ "numpy", "sys" ]
[ "import numpy as np", "import sys" ]
10
"""General-purpose utilities.""" import numpy as np from scipy.linalg import expm import random import math import operator import sys import json import openfermion from openfermion import hermitian_conjugated from openfermion.ops import SymbolicOperator from networkx.readwrite import json_graph import lea import col...
null
v0
[ "List[int]" ]
int
def v0(v1: List[int]) -> int: v2 = 0 v3 = 1 for v4 in range(len(v1)): v2 = v2 + v3 * v1[len(v1) - 1 - v4] v3 = v3 * 2 return v2
[]
[]
[]
7
"""General-purpose utilities.""" import numpy as np from scipy.linalg import expm import random import math import operator import sys import json import openfermion from openfermion import hermitian_conjugated from openfermion.ops import SymbolicOperator from networkx.readwrite import json_graph import lea import col...
null
v9
[ "np.ndarray", "np.ndarray", "float" ]
bool
def v9(v10: np.ndarray, v11: np.ndarray, v12: float=1e-15) -> bool: if v4(v10, v12) == False: raise Exception('The first input matrix is not unitary.') if v4(v11, v12) == False: raise Exception('The second input matrix is not unitary.') v13 = np.dot(v10.conj().T, v11) v14 = v13.item((0, ...
[ { "name": "v0", "input_types": [ "Any", "Any" ], "output_type": "Any", "code": "def v0(v1, v2=1e-15):\n v3 = np.array(v1).shape\n if v3[0] != v3[1]:\n raise Exception('Input matrix is not square.')\n return np.allclose(v1, np.eye(v1.shape[0]), atol=v2)", "dependen...
[ "numpy" ]
[ "import numpy as np" ]
8
"""General-purpose utilities.""" import numpy as np from scipy.linalg import expm import random import math import operator import sys import json import openfermion from openfermion import hermitian_conjugated from openfermion.ops import SymbolicOperator from networkx.readwrite import json_graph import lea import col...
null
v0
[]
None
def v0(self) -> None: self.session.cookies.clear() self.getDetails()
[]
[]
[]
3
import os import json import requests from typing import Optional from . import credentials from . import info from . import session class Client(session.Session): _SCHOOL_NAME : str = None _EMAIL : str = None _ID : int = None _PASSWORD : str = None markingPeriods : list = [] hasCachedCredenti...
null
v0
[ "int" ]
None
def v0(self, v1: int) -> None: None if self.hasGetGrades else self.getGrades() v2 = self.grades[v1 - 1] for v3 in v2['Data']: print("{}'s grade is {}".format(v3.get('CourseName')[:len(v3.get('CourseName')) - 12], v3.get('Average')))
[]
[]
[]
5
import os import json import requests from typing import Optional from . import credentials from . import info from . import session class Client(session.Session): _SCHOOL_NAME : str = None _EMAIL : str = None _ID : int = None _PASSWORD : str = None markingPeriods : list = [] hasCachedCredenti...
null
v0
[ "list", "list", "Any" ]
int
def v0(self, v1: list, v2: list, v3=1) -> int: assert len(v1) != 0 and len(v2) != 0 v4 = 0 for v5 in range(len(v1) - v3 + 1): (v6, v7) = (1, 0) v8 = v1[v5:v5 + v3] for v9 in range(v5 + v3, len(v1) - v3 + 1): if v8 == v1[v9:v9 + v3]: v6 += 1 for v10...
[]
[]
[]
14
from datautil.dataloader import batch_iter import torch.nn.functional as F import torch.optim as optim import torch.nn.utils as nn_utils import time import torch import numpy as np from config.Const import * class NMT(object): def __init__(self, encoder, decoder): super(NMT, self).__init__() self....
null
v0
[ "list", "list", "Any" ]
float
def v0(self, v1: list, v2: list, v3=4) -> float: assert len(v1) != 0 and len(v2) != 0 v4 = 0 (v5, v6) = (len(v1), len(v2)) for v7 in range(1, v3 + 1): v8 = max(0, v5 - v7 + 1) v4 += 0.25 * np.log(self.count_ngram(v1, v2, v7) / v8) return np.exp(v4 + min(0.0, 1 - v6 / v5))
[]
[ "numpy" ]
[ "import numpy as np" ]
8
from datautil.dataloader import batch_iter import torch.nn.functional as F import torch.optim as optim import torch.nn.utils as nn_utils import time import torch import numpy as np from config.Const import * class NMT(object): def __init__(self, encoder, decoder): super(NMT, self).__init__() self....
null
v0
[ "list", "list", "Any" ]
float
def v0(self, v1: list, v2: list, v3=4) -> float: assert len(v1) != 0 and len(v1) == len(v2) (v4, v5) = (0, 0) for (v6, v7) in zip(v1, v2): v4 += len(v7) v5 += len(v6) v8 = 0 for v9 in range(1, v3 + 1): (v10, v11) = (0, 0) for (v6, v7) in zip(v1, v2): v10 +...
[]
[ "numpy" ]
[ "import numpy as np" ]
14
from datautil.dataloader import batch_iter import torch.nn.functional as F import torch.optim as optim import torch.nn.utils as nn_utils import time import torch import numpy as np from config.Const import * class NMT(object): def __init__(self, encoder, decoder): super(NMT, self).__init__() self....
null
v0
[ "str", "Any", "Any" ]
Any
def v0(self, v1: str, v2='(', v3=')'): if v1.strip().startswith(v2) and v1.strip().endswith(v3): return True return False
[]
[]
[]
4
import itertools import re from abc import ABCMeta, abstractmethod from collections import deque from pathlib import Path from typing import List from startrek.exceptions import ScriptException from startrek.utils import pairwise OMITTED = 'OMITTED' class ScriptBase(metaclass=ABCMeta): def __init__(self, script_...
null
v2
[ "str" ]
Any
def v2(v3: str): v4 = {'STRING': ['"' + s + '"' for v5 in 'hello world so little time'.split()], 'CONTROLSEQ': ['\\' + v5 for v5 in 'alpha beta gamma delta sum prod deg circ ast lneg times rtimes'.split()], 'DECIMAL': ['3.14', '2.718', '1.0', '4.96'], 'INTEGER': [str(i) for v6 in range(0, 10)], 'SYMBOL': ['<', '>',...
[ { "name": "v0", "input_types": [ "Any" ], "output_type": "Any", "code": "def v0(v1):\n if not v1:\n raise TypeError(f'ran, expected nonempty list {v1}')\n return v1\n return v1[randint(0, len(v1))]", "dependencies": [] } ]
[ "numpy" ]
[ "from numpy.random import poisson, binomial, randint" ]
3
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 16 05:48:26 2021 @author: thales Generate random samples from parsers """ from numpy.random import (poisson , binomial, randint) from tokenlib import (Item , Etok, mk_stream) import lib import state def bernoulli(p): return binomial(1,p) ...
null
v0
[ "Sequence[np.ndarray]", "bool", "bool" ]
Union[np.ndarray, Tuple[np.ndarray, Tuple[int, ...]]]
def v0(v1: Sequence[np.ndarray], *, v2: bool=True, v3: bool=False) -> Union[np.ndarray, Tuple[np.ndarray, Tuple[int, ...]]]: v4 = np.stack(np.meshgrid(*v1, indexing='ij'), -1) v5 = v4.shape if v2: v4 = v4.reshape(-1, len(v1)) if v3: return (v4, v5) return v4
[]
[ "numpy" ]
[ "import numpy as np", "from numpy import ndarray" ]
8
"""Module with generic methods.""" from __future__ import annotations import functools import numbers from typing import ( TYPE_CHECKING, Any, Callable, Iterable, List, Optional, Sequence, Tuple, TypeVar, Union, cast, overload, ) import numpy as np import scipy.integra...
null
v0
[ "np.ndarray", "Any" ]
Any
def v0(v1: np.ndarray, v2: Any) -> Any: v2 = check_array_indexer(v1, v2) if isinstance(v2, tuple): v3 = [i for v4 in v2 if v4 is not Ellipsis] if len(v3) > 1: raise KeyError(v2) v2 = v3[0] if isinstance(v2, numbers.Integral): v2 = int(v2) v2 = range(len(v1...
[]
[ "numbers", "pandas" ]
[ "import numbers", "from pandas.api.indexers import check_array_indexer" ]
12
"""Module with generic methods.""" from __future__ import annotations import functools import numbers from typing import ( TYPE_CHECKING, Any, Callable, Iterable, List, Optional, Sequence, Tuple, TypeVar, Union, cast, overload, ) import numpy as np import scipy.integra...
null
v0
[ "ndarray" ]
Tuple[ndarray, ndarray]
def v0(v1: ndarray) -> Tuple[ndarray, ndarray]: check_classification_targets(v1) v2 = LabelEncoder() v3 = v2.fit_transform(v1) v4 = v2.classes_ if v4.size < 2: raise ValueError(f'The number of classes has to be greater thanone; got {v4.size} class') return (v4, v3)
[]
[ "sklearn" ]
[ "from sklearn.base import clone", "from sklearn.preprocessing import LabelEncoder", "from sklearn.utils.multiclass import check_classification_targets" ]
8
"""Module with generic methods.""" from __future__ import annotations import functools import numbers from typing import ( TYPE_CHECKING, Any, Callable, Iterable, List, Optional, Sequence, Tuple, TypeVar, Union, cast, overload, ) import numpy as np import scipy.integra...
null
v0
[ "Dict[str, Tensor]" ]
Dict[str, Tensor]
def v0(self, v1: Dict[str, Tensor]) -> Dict[str, Tensor]: if 'h' in v1: v2 = v1['h'] elif 'encoder_last_state' in v1: v2 = torch.transpose(v1['encoder_last_state'], 0, 1) else: raise ValueError(f"You must provide a hidden input in dec_input '{v1}'") if 'x' in v1: v3 = v1[...
[]
[ "torch" ]
[ "import torch", "from torch import Tensor, nn", "from torch.nn import functional as F" ]
17
import random from typing import Dict import torch from torch import Tensor, nn from torch.nn import functional as F class RNNDecoder(nn.Module): @property def max_gen_length(self) -> int: return self.hparams["dec_max_gen_length"] @property def EOS_idx(self) -> int: return self.hpara...
null
v0
[ "Dict[str, Tensor]", "Any" ]
Dict[str, Tensor]
def v0(self, v1: Dict[str, Tensor], v2) -> Dict[str, Tensor]: v3 = random.random() < v2 v4: int = v1['encoder_output'].shape[0] v5: int = self.output.in_features v6: int = self.output.out_features v7 = v1['target'][0].shape[0] if v3 else self.max_gen_length v8 = self.get_step_input(v1) v9 = ...
[]
[ "random", "torch" ]
[ "import random", "import torch", "from torch import Tensor, nn", "from torch.nn import functional as F" ]
25
import random from typing import Dict import torch from torch import Tensor, nn from torch.nn import functional as F class RNNDecoder(nn.Module): @property def max_gen_length(self) -> int: return self.hparams["dec_max_gen_length"] @property def EOS_idx(self) -> int: return self.hpara...
null
v0
[ "float", "(int, int, int)", "float" ]
float
def v0(v1: float, v2: (int, int, int), v3: float) -> float: (v4, v5, v6) = v2 v7 = int(v4 / 100) v8 = 2 - v7 + int(v7 / 4) v9 = int(365.25 * (v4 + 4716)) + int(30.6001 * (v5 + 1)) + v6 + v8 - 1524.5 v10 = (v9 + v1 / 24.0 - 2451545.0) / 36525.0 v11 = 280.46061837 + 360.98564736629 * (v9 - 2451545...
[]
[]
[]
9
def get_sidereal_time(time: float, date: (int, int, int), longitude: float) -> float: year, month, day = date # Calculate the Julian Day A = int(year/100) B = 2 - A + int(A/4) jd = int(365.25*(year + 4716)) + int(30.6001*(month + 1)) + day + B - 1524.5 # Calculate Greenwich Sidereal Time T = (jd + time/...
null
v0
[ "list", "int" ]
int
def v0(self, v1: list, v2: int) -> int: v3 = 0 while v3 < len(v1): if v1[v3] == v2: v1[v3] = v1[-1] del v1[-1] else: v3 += 1 return len(v1)
[]
[]
[]
9
# 在python中复制操作重新赋一个标识符,所以可以直接赋值 class Solution(): def removeElement(self, nums: list, val: int) -> int: lst=[] for i in range(len(nums)): if nums[i]!=val: lst.append(nums[i]) nums[:]=lst return len(lst) #python计数与删除操作 class Solution2: def removeE...
null