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
[ "str" ]
int
def v0(self, v1: str) -> int: self.line_buffer.write(v1) return self.wrapped.write(v1)
[]
[]
[]
3
import inspect import io import json import logging as logginglib import sys from datetime import datetime from typing import Any, Callable, Dict, List, Optional, Set, TextIO, Tuple from typing_extensions import Literal from hpc.autoscale import hpclogging as logging from hpc.autoscale.codeanalysis import hpcwrapclas...
null
v0
[]
None
def v0(self) -> None: self.flush() self.wrapped.close()
[]
[]
[]
3
import inspect import io import json import logging as logginglib import sys from datetime import datetime from typing import Any, Callable, Dict, List, Optional, Set, TextIO, Tuple from typing_extensions import Literal from hpc.autoscale import hpclogging as logging from hpc.autoscale.codeanalysis import hpcwrapclas...
null
v0
[ "str", "Any", "Any" ]
Any
def v0(v1: str, v2='1', v3='0'): v4 = 0 for v5 in range(len(v1)): v6 = None if v1[len(v1) - 1 - v5] == v2: v6 = 1 elif v1[len(v1) - 1 - v5] == v3: v6 = 0 v4 += 2 ** v5 * v6 return v4
[]
[]
[]
10
def binaryToInt (string: str, oneChar = "1", zeroChar = "0"): out = 0 for i in range(len(string)): currentDigit = None if string[len(string) - 1 - i] == oneChar: currentDigit = 1 elif string[len(string) - 1 - i] == zeroChar: currentDigit = 0 out +...
null
v3
[ "str" ]
int
def v3(self, v4: str) -> int: @lru_cache(None) def v5(v6, v7): print(v6, v7) if v6 > v7: return 0 if v6 == v7: return 1 if v4[v6] == v4[v7]: return v5(v6 + 1, v7 - 1) + 2 return max(v5(v6 + 1, v7), v5(v6, v7 - 1)) return v5(0, len(...
[ { "name": "v0", "input_types": [ "Any", "Any" ], "output_type": "Any", "code": "@lru_cache(None)\ndef v0(v1, v2):\n print(v1, v2)\n if v1 > v2:\n return 0\n if v1 == v2:\n return 1\n if s[v1] == s[v2]:\n return v0(v1 + 1, v2 - 1) + 2\n return max(v...
[]
[]
13
from functools import lru_cache class Solution: def longestPalindromeSubseq(self, s: str) -> int: @lru_cache(None) def helper(b,e): print(b,e) if b > e : return 0 if b == e : return 1 if s[b] == s[e] : return helper(b+1,e-1) + 2 ...
null
v0
[]
Path
def v0() -> Path: v1 = os.getenv('USER') if Path('/checkpoint/').is_dir(): v2 = Path('/checkpoint/{}/experiments'.format(v1)) v2.mkdir(exist_ok=True) return v2 raise RuntimeError('No shared folder available')
[]
[ "os", "pathlib" ]
[ "import os", "from pathlib import Path" ]
7
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ A script to run multinode training with submitit. """ import argparse import os import uuid from pathlib import Path import main as detection import submitit def parse_args(): detection_parser = detection.get_args_parser() parser = ar...
null
v0
[]
None
async def v0(self) -> None: await super().async_will_remove_from_hass() if self._async_unsub_state_changed is not None: self._async_unsub_state_changed() self._async_unsub_state_changed = None
[]
[]
[]
5
"""Entity for Zigbee Home Automation.""" from __future__ import annotations import asyncio from collections.abc import Callable import functools import logging from typing import TYPE_CHECKING, Any from homeassistant.const import ATTR_NAME from homeassistant.core import CALLBACK_TYPE, Event, callback from homeassista...
null
v7
[ "str" ]
Any
def v7(v8: str): v9 = v5(v8) if not v9: return v10 = v0(v9, 'USD', 'EUR') print(f'{v8}: {round(v10, 2)} EUR')
[ { "name": "v0", "input_types": [ "float", "str", "str" ], "output_type": "Any", "code": "def v0(v1: float, v2: str, v3: str):\n v4 = CurrencyRates()\n return v4.convert(v2, v3, v1)", "dependencies": [] }, { "name": "v5", "input_types": [ "str" ],...
[]
[]
6
import os import argparse # import json from wallstreet import Stock from wallstreet_cli import xetra from forex_python.converter import CurrencyRates LOCAL_DB_PATH = os.path.join(os.path.dirname(__file__), "data", "db.txt") def _currency_conversion(source_v: float, source_currency: str, target_currency: str): ...
null
v5
[ "list", "str" ]
Any
def v5(v6: list, v7: str=LOCAL_DB_PATH): if not os.path.exists(v7): os.makedirs(os.path.dirname(v7), exist_ok=True) v6 = v6 + v0() v8 = open(v7, 'w') v8.write('{}'.format(v6)) v8.close()
[ { "name": "v0", "input_types": [ "str" ], "output_type": "Any", "code": "def v0(v1: str=LOCAL_DB_PATH):\n if not os.path.exists(v1):\n return []\n v2 = open(v1, 'r')\n v3 = v2.read()\n v2.close()\n v4 = v3.strip('][').replace(\"'\", '').split(', ')\n return v4", ...
[ "os" ]
[ "import os" ]
7
import os import argparse # import json from wallstreet import Stock from wallstreet_cli import xetra from forex_python.converter import CurrencyRates LOCAL_DB_PATH = os.path.join(os.path.dirname(__file__), "data", "db.txt") def _currency_conversion(source_v: float, source_currency: str, target_currency: str): ...
null
v0
[ "str" ]
Any
def v0(v1: str=LOCAL_DB_PATH): if not os.path.exists(v1): return [] v2 = open(v1, 'r') v3 = v2.read() v2.close() v4 = v3.strip('][').replace("'", '').split(', ') return v4
[]
[ "os" ]
[ "import os" ]
8
import os import argparse # import json from wallstreet import Stock from wallstreet_cli import xetra from forex_python.converter import CurrencyRates LOCAL_DB_PATH = os.path.join(os.path.dirname(__file__), "data", "db.txt") def _currency_conversion(source_v: float, source_currency: str, target_currency: str): ...
null
v0
[ "Tensor" ]
Tensor
def v0(self, v1: Tensor) -> Tensor: v2 = OrderedDict() for v3 in range(self.__num_branches): v4 = f'branch_{v3}' v2[v4] = self.branches[v4].forward(v1) v5 = torch.cat([v2[f'branch_{v3}'] for v3 in range(self.__num_branches)], dim=1) return v5
[]
[ "collections", "torch" ]
[ "from collections import OrderedDict", "import torch", "from torch import nn", "from torch import Tensor" ]
7
""" The core part of the SOTA model of CPSC2019, branched, and has different scope (in terms of dilation) in each branch """ from copy import deepcopy from itertools import repeat from collections import OrderedDict from typing import Union, Optional, Sequence, NoReturn import numpy as np np.set_printoptions(precision...
null
v0
[ "Optional[int]", "Optional[int]" ]
Sequence[Union[int, None]]
def v0(self, v1: Optional[int]=None, v2: Optional[int]=None) -> Sequence[Union[int, None]]: v3 = 0 for v4 in range(self.__num_branches): v5 = f'branch_{v4}' (v6, v7, v8) = self.branches[v5].compute_output_shape(v1, v2) v3 += v7 v9 = (v2, v3, v8) return v9
[]
[]
[]
8
""" The core part of the SOTA model of CPSC2019, branched, and has different scope (in terms of dilation) in each branch """ from copy import deepcopy from itertools import repeat from collections import OrderedDict from typing import Union, Optional, Sequence, NoReturn import numpy as np np.set_printoptions(precision...
null
v0
[ "Any" ]
None
def v0(self, v1) -> None: v2 = datetime.datetime.utcnow().isoformat() v3 = self.raw_data_root / 'version.txt' with v3.open('w') as v4: v4.write(f'Updated on {v2}\n') v4.write(f'Using forecast from {v1}\n')
[]
[ "datetime" ]
[ "import datetime" ]
6
import enum from typing import Any import click import pandas as pd import numpy as np import structlog import pathlib import pydantic import datetime import zoltpy.util from covidactnow.datapublic import common_init, common_df from scripts import helpers from covidactnow.datapublic.common_fields import ( GetB...
null
v0
[ "Any", "int", "Any" ]
Any
def v0(v1, v2: int=0, v3=''): v4 = list(zip(*v1)) v5 = len(v1) v6 = v4[:v2 + 1] v7 = v4[v2] for v8 in v4[v2 + 1:]: v9 = [] for (v10, (v11, v12)) in enumerate(zip(v7, v8)): if v10 == v5 - 1: v9.append(v12) v6.append(v9) break...
[]
[]
[]
20
from sys import getsizeof from typing import ( TYPE_CHECKING, Any, Hashable, Iterable, List, Optional, Sequence, Tuple, Union, ) import warnings import numpy as np from pandas._config import get_option from pandas._libs import algos as libalgos, index as libindex, lib from pandas....
null
v0
[ "Any", "Any", "bool" ]
np.ndarray
def v0(v1, v2, v3: bool=False) -> np.ndarray: v1 = coerce_indexer_dtype(v1, v2) if v3: v1 = v1.copy() v1.flags.writeable = False return v1
[]
[ "pandas" ]
[ "from pandas._config import get_option", "from pandas._libs import algos as libalgos, index as libindex, lib", "from pandas._libs.hashtable import duplicated_int64", "from pandas._typing import AnyArrayLike, ArrayLike, Scalar", "from pandas.compat.numpy import function as nv", "from pandas.errors import P...
6
from sys import getsizeof from typing import ( TYPE_CHECKING, Any, Hashable, Iterable, List, Optional, Sequence, Tuple, Union, ) import warnings import numpy as np from pandas._config import get_option from pandas._libs import algos as libalgos, index as libindex, lib from pandas....
null
v0
[ "List", "List" ]
Any
def v0(self, v1: List, v2: List): v3 = isna(v1) if np.any(v3): v2 = np.where(v3[v2], -1, v2) return v2
[]
[ "numpy", "pandas" ]
[ "import numpy as np", "from pandas._config import get_option", "from pandas._libs import algos as libalgos, index as libindex, lib", "from pandas._libs.hashtable import duplicated_int64", "from pandas._typing import AnyArrayLike, ArrayLike, Scalar", "from pandas.compat.numpy import function as nv", "fro...
5
from sys import getsizeof from typing import ( TYPE_CHECKING, Any, Hashable, Iterable, List, Optional, Sequence, Tuple, Union, ) import warnings import numpy as np from pandas._config import get_option from pandas._libs import algos as libalgos, index as libindex, lib from pandas....
null
v0
[ "Optional[List]", "Optional[List]" ]
Any
def v0(self, v1: Optional[List]=None, v2: Optional[List]=None): v1 = v1 or self.codes v2 = v2 or self.levels if len(v2) != len(v1): raise ValueError('Length of levels and codes must match. NOTE: this index is in an inconsistent state.') v3 = len(v1[0]) for (v4, (v5, v6)) in enumerate(zip(v2,...
[]
[ "pandas" ]
[ "from pandas._config import get_option", "from pandas._libs import algos as libalgos, index as libindex, lib", "from pandas._libs.hashtable import duplicated_int64", "from pandas._typing import AnyArrayLike, ArrayLike, Scalar", "from pandas.compat.numpy import function as nv", "from pandas.errors import P...
21
from sys import getsizeof from typing import ( TYPE_CHECKING, Any, Hashable, Iterable, List, Optional, Sequence, Tuple, Union, ) import warnings import numpy as np from pandas._config import get_option from pandas._libs import algos as libalgos, index as libindex, lib from pandas....
null
v2
[]
bool
def v2(self) -> bool: def v3(v4): return 'mixed' in v4 or 'string' in v4 or 'unicode' in v4 return any((v3(level) for v5 in self._inferred_type_levels))
[ { "name": "v0", "input_types": [ "Any" ], "output_type": "Any", "code": "def v0(v1):\n return 'mixed' in v1 or 'string' in v1 or 'unicode' in v1", "dependencies": [] } ]
[]
[]
5
from __future__ import annotations from functools import wraps from sys import getsizeof from typing import ( TYPE_CHECKING, Any, Callable, Collection, Hashable, Iterable, List, Sequence, Tuple, cast, ) import warnings import numpy as np from pandas._config import get_option ...
null
v0
[ "bool" ]
int
def v0(self, v1: bool=False) -> int: v2 = 24 v3 = sum((i.memory_usage(deep=v1) for v4 in self.levels)) v5 = sum((v4.nbytes for v4 in self.codes)) v6 = sum((getsizeof(v4, v2) for v4 in self.names)) v7 = v3 + v5 + v6 v7 += self._engine.sizeof(deep=v1) return v7
[]
[ "sys" ]
[ "from sys import getsizeof" ]
8
from sys import getsizeof from typing import ( TYPE_CHECKING, Any, Hashable, Iterable, List, Optional, Sequence, Tuple, Union, ) import warnings import numpy as np from pandas._config import get_option from pandas._libs import algos as libalgos, index as libindex, lib from pandas....
null
v0
[]
int
def v0(self) -> int: v1 = [ensure_int64(level_codes) for v2 in self.codes] for v3 in range(self.nlevels, 0, -1): if libalgos.is_lexsorted(v1[:v3]): return v3 return 0
[]
[ "pandas" ]
[ "from pandas._config import get_option", "from pandas._libs import algos as libalgos, index as libindex, lib", "from pandas._libs.hashtable import duplicated_int64", "from pandas._typing import AnyArrayLike, ArrayLike, Scalar", "from pandas.compat.numpy import function as nv", "from pandas.errors import P...
6
from sys import getsizeof from typing import ( TYPE_CHECKING, Any, Hashable, Iterable, List, Optional, Sequence, Tuple, Union, ) import warnings import numpy as np from pandas._config import get_option from pandas._libs import algos as libalgos, index as libindex, lib from pandas....
null
v5
[ "'Series'", "Any", "Any" ]
Any
def v5(self, v6: 'Series', v7, v8): v9 = v6._values[v7] if is_scalar(v7): return v9 v10 = self[v7] v10 = v0(v10, v8) v11 = v6._constructor(v9, index=v10, name=v6.name) return v11.__finalize__(v6)
[ { "name": "v0", "input_types": [ "Any", "Any" ], "output_type": "Any", "code": "def v0(v1, v2):\n v3 = v1\n if isinstance(v2, tuple):\n for v4 in v2:\n try:\n v1 = v1.droplevel(0)\n except ValueError:\n return v3\n e...
[ "pandas" ]
[ "from pandas._config import get_option", "from pandas._libs import algos as libalgos, index as libindex, lib", "from pandas._libs.hashtable import duplicated_int64", "from pandas._typing import AnyArrayLike, ArrayLike, Scalar", "from pandas.compat.numpy import function as nv", "from pandas.errors import P...
8
from sys import getsizeof from typing import ( TYPE_CHECKING, Any, Hashable, Iterable, List, Optional, Sequence, Tuple, Union, ) import warnings import numpy as np from pandas._config import get_option from pandas._libs import algos as libalgos, index as libindex, lib from pandas....
null
v0
[ "Union[Hashable, Sequence[Hashable]]", "str", "str" ]
int
def v0(self, v1: Union[Hashable, Sequence[Hashable]], v2: str, v3: str) -> int: if not isinstance(v1, tuple): v1 = (v1,) return self._partial_tup_index(v1, side=v2)
[]
[]
[]
4
from sys import getsizeof from typing import ( TYPE_CHECKING, Any, Hashable, Iterable, List, Optional, Sequence, Tuple, Union, ) import warnings import numpy as np from pandas._config import get_option from pandas._libs import algos as libalgos, index as libindex, lib from pandas....
null
v0
[ "Index", "Hashable" ]
int
def v0(self, v1: Index, v2: Hashable) -> int: if is_scalar(v2) and isna(v2): return -1 else: return v1.get_loc(v2)
[]
[ "pandas" ]
[ "from pandas._config import get_option", "from pandas._libs import algos as libalgos, index as libindex, lib", "from pandas._libs.hashtable import duplicated_int64", "from pandas._typing import AnyArrayLike, ArrayLike, Scalar", "from pandas.compat.numpy import function as nv", "from pandas.errors import P...
5
from sys import getsizeof from typing import ( TYPE_CHECKING, Any, Hashable, Iterable, List, Optional, Sequence, Tuple, Union, ) import warnings import numpy as np from pandas._config import get_option from pandas._libs import algos as libalgos, index as libindex, lib from pandas....
null
v0
[ "tuple[Scalar | Iterable | AnyArrayLike, ...]", "Int64Index" ]
Int64Index
def v0(self, v1: tuple[Scalar | Iterable | AnyArrayLike, ...], v2: Int64Index) -> Int64Index: if self._is_lexsorted(): v3 = False for (v4, v5) in enumerate(v1): if is_list_like(v5): if not v3: v6 = self.levels[v4].get_indexer(v5) v6...
[]
[ "numpy", "pandas" ]
[ "import numpy as np", "from pandas._config import get_option", "from pandas._libs import algos as libalgos, index as libindex, lib", "from pandas._libs.hashtable import duplicated", "from pandas._typing import AnyArrayLike, DtypeObj, Scalar, Shape", "from pandas.compat.numpy import function as nv", "fro...
36
from __future__ import annotations from functools import wraps from sys import getsizeof from typing import ( TYPE_CHECKING, Any, Callable, Collection, Hashable, Iterable, List, Sequence, Tuple, cast, ) import warnings import numpy as np from pandas._config import get_option ...
null
v0
[ "Any" ]
bool
def v0(self, v1) -> bool: if self.nlevels != v1.nlevels: return False for v2 in range(self.nlevels): if not self.levels[v2].equals(v1.levels[v2]): return False return True
[]
[]
[]
7
from sys import getsizeof from typing import ( TYPE_CHECKING, Any, Hashable, Iterable, List, Optional, Sequence, Tuple, Union, ) import warnings import numpy as np from pandas._config import get_option from pandas._libs import algos as libalgos, index as libindex, lib from pandas....
null
v0
[ "Any", "Any", "bool" ]
Any
def v0(v1, v2, v3: bool): if not v3: return self[v1] v4 = v5 = self[v1] v2 = [self._get_level_number(i) for v6 in v2] for v6 in sorted(v2, reverse=True): try: v5 = v5.droplevel(v6) except ValueError: return v4 return v5
[]
[]
[]
11
from sys import getsizeof from typing import ( TYPE_CHECKING, Any, Hashable, Iterable, List, Optional, Sequence, Tuple, Union, ) import warnings import numpy as np from pandas._config import get_option from pandas._libs import algos as libalgos, index as libindex, lib from pandas....
null
v0
[ "int" ]
bool
def v0(self, v1: int) -> bool: for v2 in self.baseoffsets: if v1 >= v2 and v1 < v2 + self.buffersize: return True else: return False
[]
[]
[]
6
# ------------------------------------------------------------------------------ # CodeHawk Binary Analyzer # Author: Henny Sipma # ------------------------------------------------------------------------------ # The MIT License (MIT) # # Copyright (c) 2021 Aarno Labs LLC # # Permission is hereby granted, free of ...
null
v0
[ "List[Union[int, float]]", "List[Union[int, float]]", "List[float]", "np.ndarray", "np.ndarray" ]
Dict[Tuple[int, int], float]
def v0(v1: List[Union[int, float]], v2: List[Union[int, float]], v3: List[float], v4: np.ndarray, v5: np.ndarray) -> Dict[Tuple[int, int], float]: v6 = dict() for (v7, v8, v9) in zip(v1, v2, v3): v10 = int(np.argmin(np.abs(v4 - v7))) v11 = int(np.argmin(np.abs(v5 - v8))) v6[v10, v11] = v...
[]
[ "numpy" ]
[ "import numpy as np" ]
7
from typing import Callable from typing import Dict from typing import List from typing import Optional from typing import Tuple from typing import Union import numpy as np import scipy from optuna._experimental import experimental from optuna.logging import get_logger from optuna.study import Study from optuna.study...
null
v0
[ "Dict[Tuple[int, int], float]", "int" ]
np.ndarray
def v0(v1: Dict[Tuple[int, int], float], v2: int) -> np.ndarray: v3 = [] v4 = [] v5 = [] v6 = np.zeros(v2 ** 2) for v7 in range(v2): for v8 in range(v2): v9 = v8 * v2 + v7 if (v7, v8) in v1: v3.append(1) v4.append(v9) v5...
[]
[ "numpy", "scipy" ]
[ "import numpy as np", "import scipy" ]
24
from typing import Callable from typing import Dict from typing import List from typing import Optional from typing import Tuple from typing import Union import numpy as np import scipy from optuna._experimental import experimental from optuna.logging import get_logger from optuna.study import Study from optuna.study...
null
v0
[ "List[str]" ]
'_LabelEncoder'
def v0(self, v1: List[str]) -> '_LabelEncoder': self.labels = sorted(set(v1)) return self
[]
[]
[]
3
from typing import Callable from typing import Dict from typing import List from typing import Optional from typing import Tuple from typing import Union import numpy as np import scipy from optuna._experimental import experimental from optuna.logging import get_logger from optuna.study import Study from optuna.study...
null
v0
[ "torch.Tensor" ]
torch.Tensor
def v0(self, v1: torch.Tensor) -> torch.Tensor: v2 = self.activation(v1) v3 = self.round(v2) return v3
[]
[]
[]
4
from typing import Tuple, Union import torch import torch.nn as nn from entmax import Entmax15, Sparsemax from tabnet.sparsemax import EntmaxBisect from tabnet.utils import GhostBatchNorm1d, Round1 as Round, HardSigm2 as HardSigm class Attentive(nn.Module): def __init__(self, dim: int = -1, attentive_type: str ...
null
v0
[ "str" ]
Any
def v0(self, v1: str): v2 = glob.glob(f'{self.root}/{v1}/*.py') v3 = [basename(module)[:-3] for v4 in v2 if isfile(v4) and v4.endswith('.py')] for v4 in v3: self.load(v1.replace('/', '.') + f'.{v4}')
[]
[ "glob", "os" ]
[ "import glob", "from os.path import basename, isdir, isfile" ]
5
import glob import logging from importlib import import_module from os.path import basename, isdir, isfile from pathlib import Path from aiogram import Dispatcher class ModuleManager: def __init__(self, dp: Dispatcher): self.dp = dp self.root = Path(__file__).parent.parent def load_path(sel...
null
v0
[ "list" ]
Any
def v0(self, v1: list): for v2 in v1: if v2.startswith('$'): self.load(f'{v2[1:]}.__init__') elif isdir(f'{self.root}/{v2}/'): self.load_path(v2) else: self.load(v2)
[]
[ "os" ]
[ "from os.path import basename, isdir, isfile" ]
8
import glob import logging from importlib import import_module from os.path import basename, isdir, isfile from pathlib import Path from aiogram import Dispatcher class ModuleManager: def __init__(self, dp: Dispatcher): self.dp = dp self.root = Path(__file__).parent.parent def load_path(sel...
null
v8
[]
str
def v8(self: v0) -> str: if self._iso is not None: return self._iso return self.buffer.hex().upper()
[]
[]
[]
4
"""Codec for currency property inside an XRPL issued currency amount json.""" from __future__ import annotations # Requires Python 3.7+ from typing import Optional, Type from typing_extensions import Final from xrpl.constants import HEX_CURRENCY_REGEX, ISO_CURRENCY_REGEX from xrpl.core.binarycodec.exceptions import...
[ "class v0(Hash160):\n v1: Final[int] = 20\n v2: Optional[str] = None\n\n def __init__(self: v0, v3: Optional[bytes]=None) -> None:\n \"\"\"Construct a Currency.\"\"\"\n if v3 is not None:\n super().__init__(v3)\n else:\n super().__init__(bytes(self.LENGTH))\n ...
v0
[ "int", "int", "int", "int", "int", "int", "int", "str", "float", "bool", "bool" ]
Any
def v0(v1: int, v2: int, v3: int, v4: int=1, v5: int=0, v6: int=1, v7: int=1, v8: str='zeros', v9: float=1.0, v10: bool=False, v11: bool=False, **v12): v13 = Conv2d(in_channels=v1, out_channels=v2, kernel_size=v3, stride=v4, padding=v5, dilation=v6, groups=v7, bias=False, padding_mode=v8) v14 = v1 * v3 * v3 ...
[]
[ "torch" ]
[ "from torch.nn import Conv2d", "import torch.nn as nn", "import torch" ]
13
from .LagrangePolynomial import LagrangeExpand from pytorch_lightning import LightningModule, Trainer from high_order_layers_torch.PolynomialLayers import * from torch.nn import Conv2d import torch.nn as nn import torch from .utils import * def conv2d_wrapper( in_channels: int, out_channels: int, kernel_...
null
v13
[]
List[Union[str, None]]
def v13() -> List[Union[str, None]]: v14 = list(v2()) v14.append([]) return v14
[ { "name": "v0", "input_types": [], "output_type": "str", "code": "def v0() -> str:\n v1 = common.get_config_dir()\n return os.path.join(v1, 'repo_path')", "dependencies": [] }, { "name": "v2", "input_types": [], "output_type": "Dict[str, str]", "code": "@lru_cache()\nde...
[ "os" ]
[ "import os" ]
4
import os import yaml import asyncio import platform from functools import lru_cache from typing import List, Dict, Coroutine, Union from . import info from . import common def get_path_fname() -> str: """ Return the file name that stores the repo locations. """ root = common.get_config_dir() ret...
null
v0
[ "str" ]
bool
def v0(v1: str) -> bool: v2 = os.path.join(v1, '.git') return os.path.exists(v2)
[]
[ "os" ]
[ "import os" ]
3
import os import yaml import asyncio import platform from functools import lru_cache from typing import List, Dict, Coroutine, Union from . import info from . import common def get_path_fname() -> str: """ Return the file name that stores the repo locations. """ root = common.get_config_dir() ret...
null
v10
[ "Dict[str, str]", "str", "str" ]
Any
def v10(v11: Dict[str, str], v12: str, v13: str): v14 = v11[v12] del v11[v12] v11[v13] = v14 v2(v11, 'w')
[ { "name": "v0", "input_types": [], "output_type": "str", "code": "def v0() -> str:\n v1 = common.get_config_dir()\n return os.path.join(v1, 'repo_path')", "dependencies": [] }, { "name": "v2", "input_types": [ "Dict[str, str]", "str" ], "output_type": "Any",...
[ "os" ]
[ "import os" ]
5
import os import yaml import asyncio import platform from functools import lru_cache from typing import List, Dict, Coroutine, Union from . import info from . import common def get_path_fname() -> str: """ Return the file name that stores the repo locations. """ root = common.get_config_dir() ret...
null
v2
[ "Dict[str, str]", "str" ]
Any
def v2(v3: Dict[str, str], v4: str): v5 = ''.join((f'{path},{name}\n' for (v6, v7) in v3.items())) v8 = v0() os.makedirs(os.path.dirname(v8), exist_ok=True) with open(v8, v4) as v9: v9.write(v5)
[ { "name": "v0", "input_types": [], "output_type": "str", "code": "def v0() -> str:\n v1 = common.get_config_dir()\n return os.path.join(v1, 'repo_path')", "dependencies": [] } ]
[ "os" ]
[ "import os" ]
6
import os import yaml import asyncio import platform from functools import lru_cache from typing import List, Dict, Coroutine, Union from . import info from . import common def get_path_fname() -> str: """ Return the file name that stores the repo locations. """ root = common.get_config_dir() ret...
null
v13
[ "Dict[str, str]", "List[str]" ]
Any
def v13(v14: Dict[str, str], v15: List[str]): v16 = set(v14.values()) v15 = set((os.path.abspath(p) for v17 in v15 if v2(v17))) v15 = v15 - v16 if v15: print(f'Found {len(v15)} new repo(s).') v18 = {os.path.basename(os.path.normpath(path)): path for v19 in v15} v5(v18, 'a+') ...
[ { "name": "v0", "input_types": [], "output_type": "str", "code": "def v0() -> str:\n v1 = common.get_config_dir()\n return os.path.join(v1, 'repo_path')", "dependencies": [] }, { "name": "v2", "input_types": [ "str" ], "output_type": "bool", "code": "def v2(v3...
[ "os" ]
[ "import os" ]
10
import os import yaml import asyncio import platform from functools import lru_cache from typing import List, Dict, Coroutine, Union from . import info from . import common def get_path_fname() -> str: """ Return the file name that stores the repo locations. """ root = common.get_config_dir() ret...
null
v4
[ "str", "str", "List[str]" ]
Union[None, str]
async def v4(v5: str, v6: str, v7: List[str]) -> Union[None, str]: v8 = await asyncio.create_subprocess_exec(*v7, stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, start_new_session=True, cwd=v6) (v9, v10) = await v8.communicate() for v11 in (v9, v10): ...
[ { "name": "v0", "input_types": [ "str", "str" ], "output_type": "Any", "code": "def v0(v1: str, v2: str):\n return ''.join([f'{v2}{line}' for v3 in v1.splitlines(keepends=True)])", "dependencies": [] } ]
[ "asyncio" ]
[ "import asyncio" ]
8
import os import yaml import asyncio import platform from functools import lru_cache from typing import List, Dict, Coroutine, Union from . import info from . import common def get_path_fname() -> str: """ Return the file name that stores the repo locations. """ root = common.get_config_dir() ret...
null
v0
[ "List[Coroutine]" ]
List[Union[None, str]]
def v0(v1: List[Coroutine]) -> List[Union[None, str]]: if platform.system() == 'Windows': v2 = asyncio.ProactorEventLoop() asyncio.set_event_loop(v2) else: v2 = asyncio.get_event_loop() try: v3 = v2.run_until_complete(asyncio.gather(*v1)) finally: v2.close() r...
[]
[ "asyncio", "platform" ]
[ "import asyncio", "import platform" ]
11
import os import yaml import asyncio import platform from functools import lru_cache from typing import List, Dict, Coroutine, Union from . import info from . import common def get_path_fname() -> str: """ Return the file name that stores the repo locations. """ root = common.get_config_dir() ret...
null
v12
[ "Union[v0, Sequence[v0]]" ]
List[v0]
def v12(v13: Union[v0, Sequence[v0]]) -> List[v0]: if not isinstance(v13, Sequence): v13 = (v13,) v14 = [] for (v15, v16) in enumerate(v13): v14 += [replace(v16, d=1) for v17 in range(v16.d)] return v14
[]
[ "dataclasses", "typing" ]
[ "from dataclasses import dataclass, field, replace", "from typing import Tuple, List, Dict, Optional, Union, Any, Callable, Sequence" ]
7
""" Bring-Your-Own-Blocks Network A flexible network w/ dataclass based config for stacking those NN blocks. This model is currently used to implement the following networks: GPU Efficient (ResNets) - gernet_l/m/s (original versions called genet, but this was already used (by SENet author)). Paper: `Neural Ar...
[ "@dataclass\nclass v0:\n v1: Union[str, nn.Module]\n v2: int\n v3: int\n v4: int = 2\n v5: Optional[Union[int, Callable]] = None\n v6: float = 1.0\n v7: Optional[str] = None\n v8: Optional[Dict[str, Any]] = None\n v9: Optional[str] = None\n v10: Optional[Dict[str, Any]] = None\n v11...
v0
[ "bool" ]
Any
def v0(self, v1: bool=False): if v1: nn.init.zeros_(self.conv3_1x1.bn.weight) if hasattr(self.self_attn, 'reset_parameters'): self.self_attn.reset_parameters()
[]
[ "torch" ]
[ "import torch", "import torch.nn as nn" ]
5
""" Bring-Your-Own-Blocks Network A flexible network w/ dataclass based config for stacking those NN blocks. This model is currently used to implement the following networks: GPU Efficient (ResNets) - gernet_l/m/s (original versions called genet, but this was already used (by SENet author)). Paper: `Neural Ar...
null
v103
[ "v0" ]
Optional[Any]
def v103(v104: v0) -> Optional[Any]: if '_template' in v104.__dict__ and v104._template is not None: return v104._template return None
[]
[]
[]
4
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import copy import dis import inspect import os.path from types import FrameType from typing import ( TYPE_CHECKING, Any, Callable,...
[ "class v0:\n v1 = ''\n v2 = ['__abs__', '__add__', '__aenter__', '__aexit__', '__aiter__', '__and__', '__anext__', '__await__', '__bool__', '__bytes__', '__call__', '__ceil__', '__complex__', '__contains__', '__delete__', '__delitem__', '__divmod__', '__enter__', '__enter__', '__eq__', '__exit__', '__exit__',...
v5
[ "bool" ]
None
def v5(self, v6: bool) -> None: if self._template and v6: if hasattr(self._template, '__enter__') and hasattr(self._template, '__exit__'): self.__enter__ = lambda : self self.__exit__ = lambda exc_type, exc_value, traceback: None if hasattr(self._template, '__aenter__') and h...
[ { "name": "v0", "input_types": [], "output_type": "Any", "code": "async def v0():\n return self", "dependencies": [] }, { "name": "v1", "input_types": [ "Any", "Any", "Any" ], "output_type": "Any", "code": "async def v1(v2, v3, v4):\n pass", "d...
[]
[]
14
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import copy import dis import inspect import os.path from types import FrameType from typing import ( TYPE_CHECKING, Any, Callable,...
null
v0
[ "str", "int" ]
None
def v0(self, v1: str=None, v2: int=None) -> None: if not self._pbar: return super().display(msg=v1, pos=v2) if self.total != 0: v3 = str(self).split('|')[-1] try: self._pbar._set_value(self.n) self._pbar._set_eta(v3) except AttributeError: pass
[]
[]
[]
10
import inspect from typing import Iterable, Optional from tqdm import tqdm from ..utils.translations import trans _tqdm_kwargs = { p.name for p in inspect.signature(tqdm.__init__).parameters.values() if p.kind is not inspect.Parameter.VAR_KEYWORD and p.name != "self" } class progress(tqdm): """This...
null
v4
[ "v0" ]
str
def v4(self, v5: v0) -> str: v6 = v5._asdict() if self.output_info.output_dir and v5.levelType: v6['levelType'] = f'{v5.levelType}_' return self.output_info.file_name_template.format(**v6)
[]
[]
[]
5
# Copyright 2021 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, ...
[ "class v0(t.NamedTuple):\n v1: str\n v2: str\n\n def v3(self):\n if not self.levelType:\n return f'field {self.shortname}'\n return f'{self.levelType} - field {self.shortname}'" ]
v2
[ "v0", "int" ]
v0
def v2(self, v3: v0, v4: int) -> v0: if not (v3 and v3.next and v4): return v3 v5 = v3 v6 = 1 while v5.next: v5 = v5.next v6 += 1 v5.next = v3 v7 = v3 for v8 in range(v6 - v4 % v6 - 1): v7 = v7.next v9 = v7.next v7.next = None return v9
[]
[]
[]
15
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: if not (head and head.next and k) : return head fast = head cnt = 1 whi...
[ "class v0:\n\n def __init__(self, v1):\n self.val = v1\n self.next = None" ]
v5
[ "v0" ]
bool
def v5(self, v6: v0) -> bool: v7 = v6.at_least v8 = v6.at_most v9 = v6.letter if (v6.password[v7 - 1] == v9) ^ (v6.password[v8 - 1] == v9): return True else: return False
[]
[]
[]
8
import re from typing import NamedTuple from adventofcode2020.utils.abstract import FileReaderSolution class PassPol(NamedTuple): at_least: int at_most: int letter: str password: str class Day02: @staticmethod def split(input_password) -> PassPol: """ Input `7-9 r: rrrkrrrrr...
[ "class v0(NamedTuple):\n v1: int\n v2: int\n v3: str\n v4: str" ]
v0
[ "str" ]
int
def v0(self, v1: str) -> int: v2 = [self.split(x.strip()) for v3 in v1.split('\n') if len(v3.strip()) >= 1] v4 = [self.validate_passwords(policy=v3) for v3 in v2] return sum(v4)
[]
[]
[]
4
import re from typing import NamedTuple from adventofcode2020.utils.abstract import FileReaderSolution class PassPol(NamedTuple): at_least: int at_most: int letter: str password: str class Day02: @staticmethod def split(input_password) -> PassPol: """ Input `7-9 r: rrrkrrrrr...
null
v0
[ "int", "Any" ]
Any
def v0(v1: int, v2): v3 = v2[v1].next v4 = v3 for v5 in range(3): v2[v3].up = True v6 = v3 v3 = v2[v3].next v7 = (v1 - 1) % len(v2) while v2[v7].up: v7 = (v7 - 1) % len(v2) v2[v1].next = v2[v6].next v2[v6].next = v2[v7].next v2[v7].next = v4 v3 = v4 ...
[]
[]
[]
18
class Node: def __init__(self, next: int): self.next = next self.up = False def MakeNodes(data: str): values = [int(ch) - 1 for ch in data] nodes = [] for value in range(len(values)): index = values.index(value) next = values[(index + 1) % len(values)] no...
null
v0
[ "int", "Any" ]
Any
def v0(v1: int, v2): print(f'({v1 + 1})', end='') v3 = v2[v1].next for v4 in range(min(len(v2) - 1, 20)): print(f' {v3 + 1}', end='') v3 = v2[v3].next print()
[]
[]
[]
7
class Node: def __init__(self, next: int): self.next = next self.up = False def MakeNodes(data: str): values = [int(ch) - 1 for ch in data] nodes = [] for value in range(len(values)): index = values.index(value) next = values[(index + 1) % len(values)] no...
null
v0
[ "bool | str" ]
bool
def v0(v1: bool | str) -> bool: if isinstance(v1, bool): return v1 return True
[]
[]
[]
4
"""Validate some things around restore.""" from __future__ import annotations from typing import Any import voluptuous as vol from ..backups.const import BackupType from ..const import ( ATTR_ADDONS, ATTR_COMPRESSED, ATTR_CRYPTO, ATTR_DATE, ATTR_DOCKER, ATTR_FOLDERS, ATTR_HOMEASSISTANT, ...
null
v0
[ "Any", "str" ]
Dict[str, float]
def v0(self, v1, v2: str) -> Dict[str, float]: v3 = {} v4 = self._find_names(v1.lr_schedulers, add_lr_sch_names=False) self._remap_keys(v4) for (v5, v6) in zip(self.lr_sch_names, v1.lr_schedulers): if v6['interval'] == v2 or v2 == 'any': v7 = v6['scheduler'].optimizer v8 ...
[]
[]
[]
16
# 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
[ "Dict[str, Any]", "str" ]
Dict[str, Any]
def v0(self, v1: Dict[str, Any], v2: str) -> Dict[str, Any]: v3 = v1.get('lr') self.lrs[v2].append(v3) return {v2: v3}
[]
[]
[]
4
# 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[str]", "str" ]
None
def v0(self, v1: List[str], v2: str='/pg1') -> None: for v3 in v1: v4 = v3.replace(v2, '') if v2 in v3 and v4 in self.lrs: self.lrs[v3] = self.lrs.pop(v4) elif v3 not in self.lrs: self.lrs[v3] = []
[]
[]
[]
7
# 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
[ "Dict[str, Any]", "str", "bool" ]
Dict[str, float]
def v0(self, v1: Dict[str, Any], v2: str, v3: bool) -> Dict[str, float]: if not self.log_momentum: return {} v4 = v1.get('betas')[0] if v3 else v1.get('momentum', 0) self.last_momentum_values[v2] = v4 return {v2: v4}
[]
[]
[]
6
# 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
[ "str", "Type[Optimizer]", "DefaultDict[Type[Optimizer], int]" ]
str
def v0(self, v1: str, v2: Type[Optimizer], v3: DefaultDict[Type[Optimizer], int]) -> str: if v2 not in v3: return v1 v4 = v3[v2] return v1 + f'-{v4 - 1}' if v4 > 1 else v1
[]
[]
[]
5
# 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
[ "str", "List[Dict]", "int", "bool" ]
str
def v0(self, v1: str, v2: List[Dict], v3: int, v4: bool=True) -> str: if len(v2) > 1: if not v4: return f'{v1}/pg{v3 + 1}' v5 = v2[v3].get('name', f'pg{v3 + 1}') return f'{v1}/{v5}' elif v4: v5 = v2[v3].get('name') return f'{v1}/{v5}' if v5 else v1 return ...
[]
[]
[]
10
# 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[Dict]" ]
Set[str]
def v0(self, v1: List[Dict]) -> Set[str]: v2 = [pg.get('name', f'pg{i}') for (v3, v4) in enumerate(v1, start=1)] v5 = set(v2) if len(v2) == len(v5): return set() return {n for v6 in v2 if v2.count(v6) > 1}
[]
[]
[]
6
# 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
[ "str", "str" ]
Any
def v0(self, v1: str, v2: str): v3 = 0 if v1 == 'char': v3 = 1 elif v1 == 'short': v3 = 2 elif v1 == 'int': v3 = 4 elif v1 == 'long': v3 = 8 elif v1.split()[0] == 'unsigned': if v1.split()[1] == 'char': v3 = 1 elif v1.split()[1] == 'sho...
[]
[ "re" ]
[ "import re" ]
30
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import git import os import re import sys import toml from pathlib import Path from alchemist_py.brokergen import createProject from alchemist_py.deviceinfo import searchDevice from alchemist_py.plugin_manager import PluginManager class Manager(object): def __init_...
null
v11
[ "np.ndarray", "Any", "Any" ]
Any
def v11(v12: np.ndarray, v13=0.23, v14=0.091): (v15, v16) = v12.shape v17 = min(v15, v16) v18 = v13 * v17 v19 = v0(v12, v17 * v14, 1000) v20 = int(v18 / 2) v21 = [] for v22 in v19: (v23, v24) = v22 v25 = (v23 - v20, v23 + v20 + 1, v24 - v20, v24 + v20 + 1) if v25[0] >...
[ { "name": "v0", "input_types": [ "Any", "Any", "Any" ], "output_type": "Any", "code": "def v0(v1, v2, v3):\n (v4, v5, v6, v7) = mask_bbox(v1)\n v8 = v5 - v4\n v9 = v7 - v6\n v10 = np.array(sample_poisson_uniform(v8, v9, v2, v3, v1[v4:v5, v6:v7]))\n v10[:, 0] += v...
[ "numpy" ]
[ "import numpy as np" ]
14
import logging import random from typing import List, Tuple import numpy as np from skimage.transform import resize from scipy.ndimage import zoom from toolbox import images from toolbox.images import crop, mask_bbox from .poisson_disk import sample_poisson_uniform logger = logging.getLogger(__name__) class PatchT...
null
v0
[ "np.ndarray", "Any", "Any", "Any" ]
Any
def v0(v1: np.ndarray, v2=(1.0, 1.0), v3=5, v4=None): (v5, v6) = v1.shape[:2] v7 = min(v5, v6) (v8, v9) = np.where(v1) v10 = [] v11 = [] v12 = 0 while len(v10) < v3: v13 = random.uniform(*v2) v11.append(v13) v14 = v13 * v4 if v4 else int(v13 * v7) v15 = np.ran...
[]
[ "numpy", "random" ]
[ "import random", "import numpy as np" ]
21
import logging import random from typing import List, Tuple import numpy as np from skimage.transform import resize from scipy.ndimage import zoom from toolbox import images from toolbox.images import crop, mask_bbox from .poisson_disk import sample_poisson_uniform logger = logging.getLogger(__name__) class PatchT...
null
v0
[ "Union[str, Path]" ]
str
def v0(self, v1: Union[str, Path]) -> str: if isinstance(v1, Path): v1 = str(v1) if not self._base_dir: return v1 return os.path.relpath(v1, start=self._base_dir)
[]
[ "os", "pathlib" ]
[ "import os", "from pathlib import Path" ]
6
"""Output formatters.""" import os from pathlib import Path from typing import TYPE_CHECKING, Generic, TypeVar, Union import rich if TYPE_CHECKING: from ansiblelint.errors import MatchError T = TypeVar('T', bound='BaseFormatter') class BaseFormatter(Generic[T]): """Formatter of ansible-lint output. Ba...
null
v0
[ "'MatchError'" ]
str
def v0(self, v1: 'MatchError') -> str: v2 = self._format_path(v1.filename or '') v3 = v1.position v4 = u'E{0}'.format(v1.rule.id) v5 = v1.rule.severity v6 = self.escape(str(v1.message)) return f'[filename]{v2}[/]:{v3}: [[error_code]{v4}[/]] [[error_code]{v5}[/]] [dim]{v6}[/]'
[]
[]
[]
7
"""Output formatters.""" import os from pathlib import Path from typing import TYPE_CHECKING, Generic, TypeVar, Union import rich if TYPE_CHECKING: from ansiblelint.errors import MatchError T = TypeVar('T', bound='BaseFormatter') class BaseFormatter(Generic[T]): """Formatter of ansible-lint output. Ba...
null
v0
[ "Hashable", "bool" ]
List[str]
def v0(self, v1: Hashable, v2: bool=False) -> List[str]: v3 = json.dumps(self.atom_energies, indent=4).replace('"', "'").split('\n') v3[0] = f'"{v1}": ' + v3[0] v3[-1] += ',' v3 = [e + '\n' for v4 in v3] if v2: v3 = [' ' + v4 for v4 in v3] return v3
[]
[ "json" ]
[ "import json" ]
8
#!/usr/bin/env python3 ############################################################################### # # # RMG - Reaction Mechanism Generator # # ...
null
v0
[ "str", "int" ]
list
def v0(v1: str, v2: int) -> list: v3 = [0] * v2 (v4, v5) = (1, 0) while v4 < v2: if v1[v4] == v1[v5]: v5 += 1 v3[v4] = v5 v4 += 1 elif v5 > 0: v5 = v3[v5 - 1] else: v4 += 1 return v3
[]
[]
[]
13
""" KMP pattern matching algorithm. Finds matching patterns in text in linear time. Text: A longer string of length n. (n > m) Pattern: Substring to be searched for of length m. Works by precompiling the pattern string to create a LPS string array. LPS: Longest Proper Prefix. Longest prefix string that is also a suffix...
null
v6
[ "str", "str" ]
None
def v6(v7: str, v8: str) -> None: (v9, v10) = (len(v7), len(v8)) v11 = v0(v8, v10) (v12, v13) = (0, 0) while v12 < v9: if v7[v12] == v8[v13]: v12 += 1 v13 += 1 if v13 == v10: print('pattern', v8, 'found at location', v12 - v13) v13 = v11[v1...
[ { "name": "v0", "input_types": [ "str", "int" ], "output_type": "list", "code": "def v0(v1: str, v2: int) -> list:\n v3 = [0] * v2\n (v4, v5) = (1, 0)\n while v4 < v2:\n if v1[v4] == v1[v5]:\n v5 += 1\n v3[v4] = v5\n v4 += 1\n e...
[]
[]
16
""" KMP pattern matching algorithm. Finds matching patterns in text in linear time. Text: A longer string of length n. (n > m) Pattern: Substring to be searched for of length m. Works by precompiling the pattern string to create a LPS string array. LPS: Longest Proper Prefix. Longest prefix string that is also a suffix...
null
v0
[ "int" ]
Any
def v0(self, v1: int): (v2, v3) = self.bar_position self.bar_position = (v2, max(self.position[1], min(self.position[1] + self.scroll_distance, v3 + v1))) if self.on_scroll: self.on_scroll(0, 0, 0, v1, 0, 0, self.get_status())
[]
[]
[]
5
""" mcpython - a minecraft clone written in python licenced under the MIT-licence (https://github.com/mcpython4-coding/core) Contributors: uuk, xkcdjerry (inactive) Based on the game of fogleman (https://github.com/fogleman/Minecraft), licenced under the MIT-licence Original game "minecraft" by Mojang Studios (www.m...
null
v0
[]
float
def v0(self) -> float: if not self.active: return 0 return (self.bar_position[1] - self.position[1]) / self.scroll_distance
[]
[]
[]
4
""" mcpython - a minecraft clone written in python licenced under the MIT-licence (https://github.com/mcpython4-coding/core) Contributors: uuk, xkcdjerry (inactive) Based on the game of fogleman (https://github.com/fogleman/Minecraft), licenced under the MIT-licence Original game "minecraft" by Mojang Studios (www.m...
null
v0
[ "tuple", "int" ]
Any
def v0(self, v1: tuple, v2: int): if not self.active: return v3 = self.get_status() self.position = v1 self.bar_position = (self.position[0], self.position[1] + v3 * v2) self.scroll_distance = v2
[]
[]
[]
7
""" mcpython - a minecraft clone written in python licenced under the MIT-licence (https://github.com/mcpython4-coding/core) Contributors: uuk, xkcdjerry (inactive) Based on the game of fogleman (https://github.com/fogleman/Minecraft), licenced under the MIT-licence Original game "minecraft" by Mojang Studios (www.m...
null
v4
[ "str" ]
str
def v4(v5: str) -> str: v6 = re.compile('^[0-9]{2}') v7 = re.search(v6, v5).group(0) return v0(v7)
[ { "name": "v0", "input_types": [ "str" ], "output_type": "str", "code": "def v0(v1: str) -> str:\n v2 = 'https://chromedriver.storage.googleapis.com'\n for v3 in ('95.0.4638.69', '96.0.4664.45', '97.0.4692.36'):\n if v3.startswith(v1):\n if sys.platform == 'linux':\...
[ "re", "sys" ]
[ "import re", "import sys" ]
4
# Copyright 2021, joshiayus Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and th...
null
v0
[ "np.ndarray", "tuple" ]
np.ndarray
def v0(v1: np.ndarray, v2: tuple=(0, 255)) -> np.ndarray: (v3, v4) = (v1.max(), v1.min()) v5 = (v1 - v4) / (v3 - v4) v6 = v5 * (v2[1] - v2[0]) + v2[0] return v6
[]
[]
[]
5
import copy import logging from functools import partial from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union import numpy as np from skimage.segmentation import felzenszwalb, quickshift, slic from alibi.api.defaults import DEFAULT_DATA_ANCHOR_IMG, DEFAULT_META_ANCHOR from alibi.api.interfaces i...
null
v0
[ "int", "float" ]
np.ndarray
def v0(self, v1: int, v2: float=0.5) -> np.ndarray: v3 = len(self.segment_labels) v4 = np.random.choice([0, 1], v1 * v3, p=[v2, 1 - v2]) v4 = v4.reshape((v1, v3)) return v4
[]
[ "numpy" ]
[ "import numpy as np" ]
5
import copy import logging from functools import partial from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union import numpy as np from skimage.segmentation import felzenszwalb, quickshift, slic from alibi.api.defaults import DEFAULT_DATA_ANCHOR_IMG, DEFAULT_META_ANCHOR from alibi.api.interfaces i...
null
v0
[ "tuple", "int" ]
Tuple[np.ndarray, np.ndarray]
def v0(self, v1: tuple, v2: int) -> Tuple[np.ndarray, np.ndarray]: v3 = self.image v4 = self.segments v5: Union[np.ndarray, List[None]] v6 = self._choose_superpixels(v2, p_sample=self.p_sample) v6[:, v1] = 1 if self.images_background is not None: v5 = np.random.choice(range(len(self.imag...
[]
[ "copy", "numpy" ]
[ "import copy", "import numpy as np" ]
27
import copy import logging from functools import partial from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union import numpy as np from skimage.segmentation import felzenszwalb, quickshift, slic from alibi.api.defaults import DEFAULT_DATA_ANCHOR_IMG, DEFAULT_META_ANCHOR from alibi.api.interfaces i...
null
v0
[ "np.ndarray" ]
np.ndarray
def v0(self, v1: np.ndarray) -> np.ndarray: v2 = self._preprocess_img(v1) return self.segmentation_fn(v2)
[]
[]
[]
3
import copy import logging from functools import partial from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union import numpy as np from skimage.segmentation import felzenszwalb, quickshift, slic from alibi.api.defaults import DEFAULT_DATA_ANCHOR_IMG, DEFAULT_META_ANCHOR from alibi.api.interfaces i...
null
v0
[ "np.ndarray" ]
np.ndarray
def v0(self, v1: np.ndarray) -> np.ndarray: if not self.custom_segmentation and v1.shape[-1] == 1: v2 = np.repeat(v1, 3, axis=2) else: v2 = v1.copy() return v2
[]
[ "numpy" ]
[ "import numpy as np" ]
6
import copy import logging from functools import partial from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union import numpy as np from skimage.segmentation import felzenszwalb, quickshift, slic from alibi.api.defaults import DEFAULT_DATA_ANCHOR_IMG, DEFAULT_META_ANCHOR from alibi.api.interfaces i...
null
v7
[ "np.ndarray", "np.ndarray", "list", "tuple" ]
np.ndarray
def v7(self, v8: np.ndarray, v9: np.ndarray, v10: list, v11: tuple=(0, 255)) -> np.ndarray: v12 = np.zeros(v9.shape) for v13 in v10: v12[v9 == v13] = 1 v8 = v0(v8, scale=v11) v14 = (v8 * np.expand_dims(v12, 2)).astype(int) return v14
[ { "name": "v0", "input_types": [ "np.ndarray", "tuple" ], "output_type": "np.ndarray", "code": "def v0(v1: np.ndarray, v2: tuple=(0, 255)) -> np.ndarray:\n (v3, v4) = (v1.max(), v1.min())\n v5 = (v1 - v4) / (v3 - v4)\n v6 = v5 * (v2[1] - v2[0]) + v2[0]\n return v6", "...
[ "numpy" ]
[ "import numpy as np" ]
7
import copy import logging from functools import partial from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union import numpy as np from skimage.segmentation import felzenszwalb, quickshift, slic from alibi.api.defaults import DEFAULT_DATA_ANCHOR_IMG, DEFAULT_META_ANCHOR from alibi.api.interfaces i...
null
v0
[ "Tuple[Tensor, ...]", "bool" ]
List[bool]
def v0(v1: Tuple[Tensor, ...], v2: bool=True) -> List[bool]: assert isinstance(v1, tuple), 'Inputs should be wrapped in a tuple prior to preparing for gradients' v3 = [] for (v4, v5) in enumerate(v1): assert isinstance(v5, torch.Tensor), 'Given input is not a torch.Tensor' v3.append(v5.requi...
[]
[ "torch", "warnings" ]
[ "import warnings", "import torch", "from torch import Tensor, device", "from torch.nn import Module" ]
15
#!/usr/bin/env python3 import threading import typing import warnings from collections import defaultdict from typing import Any, Callable, Dict, List, Optional, Tuple, Union, cast import torch from captum._utils.common import ( _reduce_list, _run_forward, _sort_key_list, _verify_select_neuron, ) from ...
null
v0
[ "Tuple[Tensor, ...]", "List[bool]" ]
None
def v0(v1: Tuple[Tensor, ...], v2: List[bool]) -> None: assert isinstance(v1, tuple), 'Inputs should be wrapped in a tuple prior to preparing for gradients.' assert len(v1) == len(v2), 'Input tuple length should match gradient mask.' for (v3, v4) in enumerate(v1): assert isinstance(v4, torch.Tensor)...
[]
[ "torch" ]
[ "import torch", "from torch import Tensor, device", "from torch.nn import Module" ]
7
#!/usr/bin/env python3 import threading import typing import warnings from collections import defaultdict from typing import Any, Callable, Dict, List, Optional, Tuple, Union, cast import torch from captum._utils.common import ( _reduce_list, _run_forward, _sort_key_list, _verify_select_neuron, ) from ...
null
v0
[ "Callable", "Dict[Module, Dict[device, Tuple[Tensor, ...]]]", "Union[None, List[int]]" ]
Union[None, List[int]]
def v0(v1: Callable, v2: Dict[Module, Dict[device, Tuple[Tensor, ...]]], v3: Union[None, List[int]]) -> Union[None, List[int]]: if max((len(v2[single_layer]) for v4 in v2)) > 1 and v3 is None: if hasattr(v1, 'device_ids') and cast(Any, v1).device_ids is not None: v3 = cast(Any, v1).device_ids ...
[]
[ "typing" ]
[ "import typing", "from typing import Any, Callable, Dict, List, Optional, Tuple, Union, cast" ]
7
#!/usr/bin/env python3 import threading import typing import warnings from collections import defaultdict from typing import Any, Callable, Dict, List, Optional, Tuple, Union, cast import torch from captum._utils.common import ( _reduce_list, _run_forward, _sort_key_list, _verify_select_neuron, ) from ...
null
v0
[ "Module", "Union[Tuple[Tensor], Tensor]", "Optional[Tensor]", "Optional[Union[Module, Callable]]" ]
Tuple[Tensor, ...]
def v0(v1: Module, v2: Union[Tuple[Tensor], Tensor], v3: Optional[Tensor]=None, v4: Optional[Union[Module, Callable]]=None) -> Tuple[Tensor, ...]: with torch.autograd.set_grad_enabled(True): v5 = v1(v2) assert v5.dim() != 0, 'Please ensure model output has at least one dimension.' if v3 is n...
[]
[ "torch" ]
[ "import torch", "from torch import Tensor, device", "from torch.nn import Module" ]
17
#!/usr/bin/env python3 import threading import typing import warnings from collections import defaultdict from typing import Any, Callable, Dict, List, Optional, Tuple, Union, cast import torch from captum._utils.common import ( _reduce_list, _run_forward, _sort_key_list, _verify_select_neuron, ) from ...
null
v0
[ "Any" ]
None
def v0(self, v1) -> None: v2 = v1.keys() v3 = [layer for v4 in v2 if v4 not in self._layer_pcas] if len(v3) == 0: return v5 = self._pcas(identifier=self._extractor.identifier, layers=v3, n_components=self._n_components, force=self._force, stimuli_identifier=self._stimuli_identifier) self._la...
[]
[]
[]
7
from abc import ABC, abstractmethod import logging import os from typing import Optional, Union, Iterable, Dict import h5py import numpy as np import torch from PIL import Image from tqdm import tqdm from brainio.stimuli import StimulusSet from model_tools.activations import ActivationsModel from model_tools.activati...
null
v0
[ "Dict[str, str]" ]
List[str]
def v0(v1: Dict[str, str]) -> List[str]: v2: List[str] = [] if v1.get('index_url'): v2 += ['--index-url', v1['index_url']] if v1.get('pip_args'): v2 += shlex.split(v1.get('pip_args', '')) if v1.get('editable'): v2 += ['--editable'] return v2
[]
[ "shlex" ]
[ "import shlex" ]
9
# PYTHON_ARGCOMPLETE_OK """The command line interface to pipx""" import argparse import logging import logging.config import os import re import shlex import sys import textwrap import time import urllib.parse from pathlib import Path from typing import Any, Callable, Dict, List import argcomplete # type: ignore fr...
null
v0
[ "Dict[str, str]" ]
List[str]
def v0(v1: Dict[str, str]) -> List[str]: v2: List[str] = [] if v1.get('system_site_packages'): v2 += ['--system-site-packages'] return v2
[]
[]
[]
5
# PYTHON_ARGCOMPLETE_OK """The command line interface to pipx""" import argparse import logging import logging.config import os import re import shlex import sys import textwrap import time import urllib.parse from pathlib import Path from typing import Any, Callable, Dict, List import argcomplete # type: ignore fr...
null
v0
[ "argparse.ArgumentParser" ]
None
def v0(v1: argparse.ArgumentParser) -> None: v1.add_argument('--system-site-packages', action='store_true', help='Give the virtual environment access to the system site-packages dir.') v1.add_argument('--index-url', '-i', help='Base URL of Python Package Index') v1.add_argument('--editable', '-e', help='Ins...
[]
[]
[]
5
# PYTHON_ARGCOMPLETE_OK """The command line interface to pipx""" import argparse import logging import logging.config import os import re import shlex import sys import textwrap import time import urllib.parse from pathlib import Path from typing import Any, Callable, Dict, List import argcomplete # type: ignore fr...
null
v5
[ "Any", "v0" ]
None
def v5(v6, v7: v0) -> None: v8 = v6.add_parser('inject', help='Install packages into an existing Virtual Environment', description='Installs packages to an existing pipx-managed virtual environment.') v8.add_argument('package', help='Name of the existing pipx-managed Virtual Environment to inject into').complet...
[ { "name": "v1", "input_types": [ "argparse.ArgumentParser" ], "output_type": "None", "code": "def v1(v2: argparse.ArgumentParser) -> None:\n v2.add_argument('--include-deps', help='Include apps of dependent packages', action='store_true')", "dependencies": [] }, { "name": "v...
[]
[]
9
# PYTHON_ARGCOMPLETE_OK """The command line interface to pipx""" import argparse import logging import logging.config import os import re import shlex import sys import textwrap import time import urllib.parse from pathlib import Path from typing import Any, Callable, Dict, List import argcomplete # type: ignore fr...
[ "v0 = Callable[[str], List[str]]" ]
v3
[ "Any", "v0" ]
None
def v3(v4, v5: v0) -> None: v6 = v4.add_parser('upgrade', help='Upgrade a package', description="Upgrade a package in a pipx-managed Virtual Environment by running 'pip install --upgrade PACKAGE'") v6.add_argument('package').completer = v5 v6.add_argument('--include-injected', action='store_true', help="Als...
[ { "name": "v1", "input_types": [ "argparse.ArgumentParser" ], "output_type": "None", "code": "def v1(v2: argparse.ArgumentParser) -> None:\n v2.add_argument('--system-site-packages', action='store_true', help='Give the virtual environment access to the system site-packages dir.')\n v...
[]
[]
7
# PYTHON_ARGCOMPLETE_OK """The command line interface to pipx""" import argparse import logging import logging.config import os import re import shlex import sys import textwrap import time import urllib.parse from pathlib import Path from typing import Any, Callable, Dict, List import argcomplete # type: ignore fr...
[ "v0 = Callable[[str], List[str]]" ]
v0
[ "argparse._SubParsersAction" ]
None
def v0(v1: argparse._SubParsersAction) -> None: v2 = v1.add_parser('upgrade-all', help='Upgrade all packages. Runs `pip install -U <pkgname>` for each package.', description="Upgrades all packages within their virtual environments by running 'pip install --upgrade PACKAGE'") v2.add_argument('--include-injected'...
[]
[]
[]
6
# PYTHON_ARGCOMPLETE_OK """The command line interface to pipx""" import argparse import logging import logging.config import os import re import shlex import sys import textwrap import time import urllib.parse from pathlib import Path from typing import Any, Callable, Dict, List import argcomplete # type: ignore fr...
null
v1
[ "Any", "v0" ]
None
def v1(v2, v3: v0) -> None: v4 = v2.add_parser('uninstall', help='Uninstall a package', description='Uninstalls a pipx-managed Virtual Environment by deleting it and any files that point to its apps.') v4.add_argument('package').completer = v3 v4.add_argument('--verbose', action='store_true')
[]
[]
[]
4
# PYTHON_ARGCOMPLETE_OK """The command line interface to pipx""" import argparse import logging import logging.config import os import re import shlex import sys import textwrap import time import urllib.parse from pathlib import Path from typing import Any, Callable, Dict, List import argcomplete # type: ignore fr...
[ "v0 = Callable[[str], List[str]]" ]
v0
[ "argparse._SubParsersAction" ]
None
def v0(v1: argparse._SubParsersAction) -> None: v2 = v1.add_parser('uninstall-all', help='Uninstall all packages', description='Uninstall all pipx-managed packages') v2.add_argument('--verbose', action='store_true')
[]
[]
[]
3
# PYTHON_ARGCOMPLETE_OK """The command line interface to pipx""" import argparse import logging import logging.config import os import re import shlex import sys import textwrap import time import urllib.parse from pathlib import Path from typing import Any, Callable, Dict, List import argcomplete # type: ignore fr...
null
v0
[ "argparse._SubParsersAction" ]
None
def v0(v1: argparse._SubParsersAction) -> None: v2 = v1.add_parser('list', help='List installed packages', description='List packages and apps installed with pipx') v2.add_argument('--include-injected', action='store_true', help="Show packages injected into the main app's environment") v2.add_argument('--js...
[]
[]
[]
5
# PYTHON_ARGCOMPLETE_OK """The command line interface to pipx""" import argparse import logging import logging.config import os import re import shlex import sys import textwrap import time import urllib.parse from pathlib import Path from typing import Any, Callable, Dict, List import argcomplete # type: ignore fr...
null
v1
[ "Any", "v0" ]
None
def v1(v2, v3: v0) -> None: v4 = v2.add_parser('runpip', help='Run pip in an existing pipx-managed Virtual Environment', description='Run pip in an existing pipx-managed Virtual Environment') v4.add_argument('package', help='Name of the existing pipx-managed Virtual Environment to run pip in').completer = v3 ...
[]
[ "argparse" ]
[ "import argparse" ]
5
# PYTHON_ARGCOMPLETE_OK """The command line interface to pipx""" import argparse import logging import logging.config import os import re import shlex import sys import textwrap import time import urllib.parse from pathlib import Path from typing import Any, Callable, Dict, List import argcomplete # type: ignore fr...
[ "v0 = Callable[[str], List[str]]" ]
v0
[ "argparse._SubParsersAction" ]
None
def v0(v1: argparse._SubParsersAction) -> None: v2 = v1.add_parser('ensurepath', help='Ensure directories necessary for pipx operation are in your PATH environment variable.', description="Ensure directory where pipx stores apps is in your PATH environment variable. Also if pipx was installed via `pip install --use...
[]
[]
[]
3
# PYTHON_ARGCOMPLETE_OK """The command line interface to pipx""" import argparse import logging import logging.config import os import re import shlex import sys import textwrap import time import urllib.parse from pathlib import Path from typing import Any, Callable, Dict, List import argcomplete # type: ignore fr...
null
v0
[ "List[Path]", "int" ]
None
def v0(v1: List[Path], v2: int) -> None: v1 = sorted(v1) if len(v1) > v2: for v3 in v1[:-v2]: try: v3.unlink() except FileNotFoundError: pass
[]
[]
[]
8
# PYTHON_ARGCOMPLETE_OK """The command line interface to pipx""" import argparse import logging import logging.config import os import re import shlex import sys import textwrap import time import urllib.parse from pathlib import Path from typing import Any, Callable, Dict, List import argcomplete # type: ignore fr...
null
v0
[ "argparse.Namespace" ]
None
def v0(v1: argparse.Namespace) -> None: if v1.command == 'run': if v1.app_with_args and v1.app_with_args[0] == '--': v1.app_with_args.pop(0) if not v1.app_with_args: v1.subparser.error('the following arguments are required: app')
[]
[]
[]
6
# PYTHON_ARGCOMPLETE_OK """The command line interface to pipx""" import argparse import logging import logging.config import os import re import shlex import sys import textwrap import time import urllib.parse from pathlib import Path from typing import Any, Callable, Dict, List import argcomplete # type: ignore fr...
null
v0
[ "str", "int" ]
List[str]
def v0(self, v1: str, v2: int) -> List[str]: v1 = self._whitespace_matcher.sub(' ', v1).strip() return textwrap.wrap(v1, v2)
[]
[ "textwrap" ]
[ "import textwrap" ]
3
# PYTHON_ARGCOMPLETE_OK """The command line interface to pipx""" import argparse import logging import logging.config import os import re import shlex import sys import textwrap import time import urllib.parse from pathlib import Path from typing import Any, Callable, Dict, List import argcomplete # type: ignore fr...
null
v0
[ "Any" ]
dict
def v0(v1) -> dict: v2 = {} for v3 in v1: if v2.get(v3) is None: v2[v3] = 1 else: v2[v3] = v2[v3] + 1 return v2
[]
[]
[]
8
# qubit number=4 # total number=31 import pyquil from pyquil.api import local_forest_runtime, QVMConnection from pyquil import Program, get_qc from pyquil.gates import * import numpy as np conn = QVMConnection() def make_circuit()-> Program: prog = Program() # circuit begin prog += X(3) # number=1 prog...
null
v0
[ "int", "Sequence[float]", "Union[float, Sequence[float]]" ]
np.ndarray
def v0(v1: int, v2: Sequence[float], v3: Union[float, Sequence[float]]) -> np.ndarray: if isinstance(v3, float): v3 = [v3, 1 - v3] if sum(v3) != 1: raise ValueError('Fractions have to add up to 1!') v4 = (v1 * np.array(v3)).astype(np.int64) v4[-1] += v1 - sum(v4) v5 = [np.full(v1, va...
[]
[ "numpy" ]
[ "import numpy as np" ]
9
# coding: utf-8 # # This code is part of cmpy. # # Copyright (c) 2022, Dylan Jones """This module contains methods for modeling disorder.""" import numpy as np from typing import Union, Sequence def create_subst_array( size: int, values: Sequence[float], conc: Union[float, Sequence[float]] ) -> np.ndarray: ...
null
v0
[ "Sequence[float]", "int", "bool", "int" ]
Any
def v0(v1: Sequence[float], v2: int, v3: bool=False, v4: int=None): v5 = np.random.default_rng(v4) v6 = np.array(v1) v7 = set() v8 = 0 while True: if v8 >= v2: break v5.shuffle(v6) if not v3: v9 = hash(v6.data.tobytes()) if v9 not in v7: ...
[]
[ "numpy" ]
[ "import numpy as np" ]
18
# coding: utf-8 # # This code is part of cmpy. # # Copyright (c) 2022, Dylan Jones """This module contains methods for modeling disorder.""" import numpy as np from typing import Union, Sequence def create_subst_array( size: int, values: Sequence[float], conc: Union[float, Sequence[float]] ) -> np.ndarray: ...
null