name
stringclasses
844 values
input_types
listlengths
0
100
output_type
stringlengths
1
419
code
stringlengths
34
233k
dependencies
listlengths
0
6
lib_used
listlengths
0
11
imports
listlengths
0
66
line_count
int64
3
199
full_code
stringlengths
39
1.01M
input_type_defs
listlengths
1
12
v0
[]
str
def v0(self) -> str: v1 = self.highest() v2 = 'None' if v1: v2 = v1[0][1] return v2
[]
[]
[]
6
# pylint: disable=no-member,too-many-lines from __future__ import annotations import datetime import math import threading import uuid as uuid_lib import dateutil.parser import wx from ninjalooter import config from ninjalooter import constants from ninjalooter import extra_data from ninjalooter import logger # Thi...
null
v0
[]
str
def v0(self) -> str: v1 = [] for v2 in self.highest(): v1.append(v2[0]) v1 = ', '.join(v1) return v1 or ''
[]
[]
[]
6
# pylint: disable=no-member,too-many-lines from __future__ import annotations import datetime import math import threading import uuid as uuid_lib import dateutil.parser import wx from ninjalooter import config from ninjalooter import constants from ninjalooter import extra_data from ninjalooter import logger # Thi...
null
v0
[]
str
def v0(self) -> str: v1 = self.time_remaining() if v1.seconds <= 30: return 'a few moments' v2 = int(v1.seconds / 60) v3 = v1.seconds % 60 if v2: v4 = '{}m{:02d}s'.format(v2, v3) else: v4 = '{}s'.format(v3) return v4
[]
[]
[]
11
# pylint: disable=no-member,too-many-lines from __future__ import annotations import datetime import math import threading import uuid as uuid_lib import dateutil.parser import wx from ninjalooter import config from ninjalooter import constants from ninjalooter import extra_data from ninjalooter import logger # Thi...
null
v0
[ "list", "list" ]
Any
def v0(self, v1: list, v2: list): self.eqn1 = v1 self.eqn2 = v2
[]
[]
[]
3
from formulae import lowest_common_multiple class SimultaneousEquationSolver: """Class to represent a dedicated object to solving (by elimination) linear, 2D simultaneous equations, for example: 3x + 2y = 4 2x + 3y = 6""" def __init__(self): """Constructor method, creates the following ...
null
v0
[ "List[int]", "int" ]
List[int]
def v0(self, v1: List[int], v2: int) -> List[int]: v3 = len(v1) v4 = [x + 1 for v5 in range(v2)] v6: List[int] = list() v7: int = None v8: int = None for v9 in range(v3): v7 = self.simple_scann(v4, v1[v9]) print(v4) v6.append(v7) print(v6) v8 = v4.pop(v7) ...
[]
[]
[]
14
from typing import List class Solution: def processQueries(self, queries: List[int], m: int) -> List[int]: # initialize variables len_queries = len(queries) permutation = [x+1 for x in range(m)] solution: List[int] = list() temp_index: int = None temp_value: int = N...
null
v0
[ "List[int]", "int" ]
List[int]
def v0(self, v1: List[int], v2: int) -> List[int]: v3: int = None for v4 in range(len(v1)): if v1[v4] == v2: v3 = v4 return v3
[]
[]
[]
6
from typing import List class Solution: def processQueries(self, queries: List[int], m: int) -> List[int]: # initialize variables len_queries = len(queries) permutation = [x+1 for x in range(m)] solution: List[int] = list() temp_index: int = None temp_value: int = N...
null
v0
[ "str" ]
Dict
def v0(self, v1: str=None) -> Dict: v2 = f'{self.base_url}/machine/status' v3 = requests.get(v2) v4 = v3.json() if v1 is not None: v5 = v1.split('.') return reduce(operator.getitem, v5, v4) return v4
[]
[ "functools", "operator", "requests" ]
[ "from functools import reduce", "import operator", "import requests" ]
8
import logging import os from typing import Dict, List, Union from io import StringIO, TextIOWrapper, BytesIO from functools import reduce import operator import requests from .base import DuetAPI class DSFAPI(DuetAPI): """ Duet Software Framework REST API Interface. Used with a Duet 3 + SBC. Must ...
null
v0
[ "str" ]
Dict
def v0(self, v1: str) -> Dict: v2 = f'{self.base_url}/machine/code' v3 = requests.post(v2, data=v1) return {'response': v3.text}
[]
[ "requests" ]
[ "import requests" ]
4
import logging import os from typing import Dict, List, Union from io import StringIO, TextIOWrapper, BytesIO from functools import reduce import operator import requests from .base import DuetAPI class DSFAPI(DuetAPI): """ Duet Software Framework REST API Interface. Used with a Duet 3 + SBC. Must ...
null
v0
[ "str", "str", "bool" ]
str
def v0(self, v1: str, v2: str='gcodes', v3: bool=False) -> str: v4 = f'{self.base_url}/rr_download' v5 = requests.get(v4, {'name': f'/{v2}/{v1}'}) if not v5.ok: raise ValueError if v3: return v5.content else: return v5.text
[]
[ "requests" ]
[ "import requests" ]
9
import logging import os from typing import Dict, List, Union from io import StringIO, TextIOWrapper, BytesIO import requests from .base import DuetAPI class DWCAPI(DuetAPI): """ Duet Web Control REST API Interface. Used with a Duet 2/3 in standalone mode. Must use RRF3. """ api_name = 'DWC...
null
v0
[ "Union[str, bytes, StringIO, TextIOWrapper, BytesIO]", "str", "str" ]
Dict
def v0(self, v1: Union[str, bytes, StringIO, TextIOWrapper, BytesIO], v2: str, v3: str='gcodes') -> Dict: v4 = f'{self.base_url}/machine/file/{v3}/{v2}' v5 = requests.put(v4, data=v1, headers={'Content-Type': 'application/octet-stream'}) if not v5.ok: raise ValueError return {'err': 0}
[]
[ "requests" ]
[ "import requests" ]
6
import logging import os from typing import Dict, List, Union from io import StringIO, TextIOWrapper, BytesIO from functools import reduce import operator import requests from .base import DuetAPI class DSFAPI(DuetAPI): """ Duet Software Framework REST API Interface. Used with a Duet 3 + SBC. Must ...
null
v0
[ "str", "str" ]
Dict
def v0(self, v1: str, v2: str='gcodes') -> Dict: v3 = f'{self.base_url}/rr_delete' v4 = requests.get(v3, {'name': f'/{v2}/{v1}'}) if not v4.ok: raise ValueError return v4.json()
[]
[ "requests" ]
[ "import requests" ]
6
import logging import os from typing import Dict, List, Union from io import StringIO, TextIOWrapper, BytesIO import requests from .base import DuetAPI class DWCAPI(DuetAPI): """ Duet Web Control REST API Interface. Used with a Duet 2/3 in standalone mode. Must use RRF3. """ api_name = 'DWC...
null
v0
[ "str", "str" ]
Dict
def v0(self, v1: str, v2: str='gcodes') -> Dict: v3 = f'{self.base_url}/machine/file/{v2}/{v1}' v4 = requests.delete(v3) if not v4.ok: raise ValueError return {'err': 0}
[]
[ "requests" ]
[ "import requests" ]
6
import logging import os from typing import Dict, List, Union from io import StringIO, TextIOWrapper, BytesIO from functools import reduce import operator import requests from .base import DuetAPI class DSFAPI(DuetAPI): """ Duet Software Framework REST API Interface. Used with a Duet 3 + SBC. Must ...
null
v0
[ "str", "str", "bool" ]
Dict
def v0(self, v1: str, v2: str, v3: bool=False) -> Dict: v4 = f'{self.base_url}/machine/file/move' v5 = requests.post(v4, {'from': f'{v1}', 'to': f'{v2}', 'force': v3}) if not v5.ok: raise ValueError return {'err': 0}
[]
[ "requests" ]
[ "import requests" ]
6
import logging import os from typing import Dict, List, Union from io import StringIO, TextIOWrapper, BytesIO from functools import reduce import operator import requests from .base import DuetAPI class DSFAPI(DuetAPI): """ Duet Software Framework REST API Interface. Used with a Duet 3 + SBC. Must ...
null
v0
[ "str" ]
List[Dict]
def v0(self, v1: str) -> List[Dict]: v2 = f'{self.base_url}/machine/directory/{v1}' v3 = requests.get(v2) if not v3.ok: raise ValueError return v3.json()
[]
[ "requests" ]
[ "import requests" ]
6
import logging import os from typing import Dict, List, Union from io import StringIO, TextIOWrapper, BytesIO from functools import reduce import operator import requests from .base import DuetAPI class DSFAPI(DuetAPI): """ Duet Software Framework REST API Interface. Used with a Duet 3 + SBC. Must ...
null
v0
[ "str" ]
Dict
def v0(self, v1: str) -> Dict: v2 = f'{self.base_url}/machine/directory/{v1}' v3 = requests.put(v2) if not v3.ok: raise ValueError return {'err': 0}
[]
[ "requests" ]
[ "import requests" ]
6
import logging import os from typing import Dict, List, Union from io import StringIO, TextIOWrapper, BytesIO from functools import reduce import operator import requests from .base import DuetAPI class DSFAPI(DuetAPI): """ Duet Software Framework REST API Interface. Used with a Duet 3 + SBC. Must ...
null
v0
[ "pd.DataFrame", "pd.DataFrame", "List[str]", "List[str]" ]
pd.DataFrame
def v0(v1: pd.DataFrame, v2: pd.DataFrame, v3: List[str], v4: List[str]) -> pd.DataFrame: v5 = v2.set_index(v3) if not len(v1): for v6 in v4: if v6 not in v5.columns: v5[v6] = None return v5[v4].reset_index() v1 = v1.set_index(v3) v1 = v1.sort_index() v5 =...
[]
[ "pandas" ]
[ "import pandas as pd" ]
24
from typing import List import os import enum import logging import pathlib import pandas as pd from libs.us_state_abbrev import US_STATE_ABBREV if os.getenv("COVID_DATA_PUBLIC"): LOCAL_PUBLIC_DATA_PATH = pathlib.Path(os.getenv("COVID_DATA_PUBLIC")) else: LOCAL_PUBLIC_DATA_PATH = ( pathlib.Path(__file_...
null
v0
[ "bool" ]
Any
def v0(v1: bool): if self.active_pf: self.file_save_dialog(pf=self.active_pf, as_=v1)
[]
[]
[]
3
import os import sys import time import typing from collections import defaultdict, deque from functools import partial, wraps from PyQt5 import uic, QtGui, QtPrintSupport from PyQt5.QtCore import Qt, QSize from PyQt5.QtGui import QPixmap, QCloseEvent from PyQt5.QtWidgets import ( QApplication, QMainWindow, ...
null
v0
[ "bool" ]
Any
def v0(v1: bool): if self.active_pf: self.zoom_in_out(pf=self.active_pf, in_=v1)
[]
[]
[]
3
import os import sys import time import typing from collections import defaultdict, deque from functools import partial, wraps from PyQt5 import uic, QtGui, QtPrintSupport from PyQt5.QtCore import Qt, QSize from PyQt5.QtGui import QPixmap, QCloseEvent from PyQt5.QtWidgets import ( QApplication, QMainWindow, ...
null
v0
[ "int" ]
Any
def v0(v1: int=0, **v2): v3 = datetime.timedelta(v1) v4 = datetime.datetime.now() v5 = f'%Y-%m-%d' if v2: v6 = v2.get('h', '00') v7 = v2.get('m', '00') v8 = v2.get('s', '00') v5 = f'{v5} {v6}:{v7}:{v8}' return (v4 + v3).strftime(v5)
[]
[ "datetime" ]
[ "import datetime" ]
10
# !/usr/bin/python3 # -*- coding: utf-8 -*- # @Author: 花菜 # @File: day.py # @Time : 2020/11/4 14:53 # @Email: lihuacai168@gmail.com import datetime def get_day(days: int = 0, **kwargs): """ >>> get_day() 2020-10-15 # 今天的日期 >>> get_day(1) 2020-10-16 # 明天的日期 >>> get_day(-1) 2020-10-14 # 昨...
null
v0
[ "bool" ]
str
def v0(self, v1: bool=False) -> str: if v1: return 'sudo ' + self.kubeconfig_fmt.format(namespace='admin', cluster=self.cluster) else: return self.kubeconfig_fmt.format(namespace=self.namespace, cluster=self.cluster)
[]
[]
[]
5
import json import shlex import subprocess from typing import List, Optional import attr from k8sh import k8shError @attr.s class RemoteCommand: host: Optional[str] = attr.ib() ssh_opts: Optional[List[str]] = attr.ib(default=None) def _cmd(self, command): if self.host is None: retur...
null
v0
[ "str", "bool" ]
List[str]
def v0(self, v1: str, v2: bool=False) -> List[str]: if self.namespace is not None: v3 = '{} kubectl -n {} {}'.format(self._kubeconfig(v2), self.namespace, v1) else: v3 = '{} kubectl {}'.format(self._kubeconfig(v2), v1) return shlex.split(v3)
[]
[ "shlex" ]
[ "import shlex" ]
6
import json import shlex import subprocess from typing import List, Optional import attr from k8sh import k8shError @attr.s class RemoteCommand: host: Optional[str] = attr.ib() ssh_opts: Optional[List[str]] = attr.ib(default=None) def _cmd(self, command): if self.host is None: retur...
null
v0
[ "str" ]
bool
def v0(self, v1: str) -> bool: v2 = len(v1) for v3 in range(1, v2 // 2 + 1): if v2 % v3 == 0: v4 = True for v5 in range(0, v2 - v3, v3): if v1[v5:v5 + v3] != v1[v5 + v3:v5 + v3 + v3]: v4 = False if v4: return True ...
[]
[]
[]
11
""" Leetcode 459 - Repeated Substring Pattern https://leetcode.com/problems/repeated-substring-pattern/ 1. MINE """ class Solution1: """ 1. MINE """ def repeated_substring_pattern(self, s: str) -> bool: s_len = len(s) for i in range(1, s_len//2+1): if s_len % i == 0: ...
null
v0
[ "np.ndarray", "np.ndarray", "Callable[[np.ndarray], np.ndarray]", "float" ]
np.ndarray
def v0(v1: np.ndarray, v2: np.ndarray, v3: Callable[[np.ndarray], np.ndarray], v4: float=0.95) -> np.ndarray: v5 = norm.ppf(1 - (1 - v4) / 2) v6 = v5 * np.sqrt(v2) v7 = v3(v1 + v6) - v3(v1 - v6) v8 = v3(v1) v9 = (v7 / 2 / v5) ** 2 return (v8, v9)
[]
[ "numpy", "scipy" ]
[ "import numpy as np", "from scipy.stats import norm" ]
7
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations from typing import TYPE_CHECKING, Callable, List, Optional, Tuple import numpy a...
null
v0
[ "np.ndarray", "np.ndarray" ]
Tuple[np.ndarray, np.ndarray]
def v0(v1: np.ndarray, v2: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: v3 = np.log(1 + v2 / np.outer(v1, v1)) v4 = np.log(v1) - 0.5 * np.diag(v3) return (v4, v3)
[]
[ "numpy" ]
[ "import numpy as np" ]
4
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations from typing import TYPE_CHECKING, Callable, List, Optional, Tuple import numpy a...
null
v0
[ "np.ndarray", "np.ndarray" ]
Tuple[np.ndarray, np.ndarray]
def v0(v1: np.ndarray, v2: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: v3 = np.diag(v2) v4 = v1 + 0.5 * v3 v5 = np.exp(v4) v6 = (np.exp(v2) - 1) * np.exp(v4.reshape(-1, 1) + v4.reshape(1, -1)) return (v5, v6)
[]
[ "numpy" ]
[ "import numpy as np" ]
6
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations from typing import TYPE_CHECKING, Callable, List, Optional, Tuple import numpy a...
null
v0
[ "Any", "int" ]
int
def v0(self, v1, v2: int) -> int: v3 = [] for v4 in range(len(v1)): v3.append((v1[v4][0], v4, 0)) heapq.heapify(v3) while v2 > 1: (v5, v6, v7) = heapq.heappop(v3) if v7 + 1 < len(v1[v6]): heapq.heappush(v3, (v1[v6][v7 + 1], v6, v7 + 1)) v2 -= 1 (v8, v5, v5...
[]
[ "heapq" ]
[ "import heapq" ]
12
# Kth Smallest Element in a Sorted Matrix: https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/ # Given an n x n matrix where each of the rows and columns are sorted in ascending order, return the kth smallest element in the matrix. # Note that it is the kth smallest element in the sorted order, not...
null
v0
[]
None
def v0(self) -> None: (v1, v2) = self.aggregator.compute() self.model.initial_probs.copy_(v1) self.model.transition_probs.copy_(v2)
[]
[]
[]
4
import torch from torch.nn.utils.rnn import PackedSequence from torchmetrics import AverageMeter from pycave.bayes.markov_chain.metrics import StateCountAggregator from pycave.core import NonparametricLightningModule from .model import MarkovChainModel class MarkovChainLightningModule(NonparametricLightningModule): ...
null
v0
[ "PackedSequence", "int" ]
None
def v0(self, v1: PackedSequence, v2: int) -> None: v3 = self.model.forward(v1) self.metric_nll.update(-v3) self.log('nll', self.metric_nll)
[]
[]
[]
4
import torch from torch.nn.utils.rnn import PackedSequence from torchmetrics import AverageMeter from pycave.bayes.markov_chain.metrics import StateCountAggregator from pycave.core import NonparametricLightningModule from .model import MarkovChainModel class MarkovChainLightningModule(NonparametricLightningModule): ...
null
v15
[]
None
def v15(self: v0[Any, Any], /) -> None: self._mapping.clear() self._sequence.clear()
[]
[]
[]
3
from __future__ import annotations import collections.abc import sys from abc import ABC, abstractmethod from copy import copy, deepcopy from typing import Any, Generic, Optional, Type, TypeVar, Union, overload if sys.version_info < (3, 9): from typing import AbstractSet, ItemsView, Iterable, Iterator, KeysView, M...
[ "class v0(MutableMapping[KT_co, VT_co], SortedMapping[KT_co, VT_co], Generic[KT_co, VT_co]):\n v1 = ()\n\n def v2(self: v0[KT, Any], v3: KT, /) -> None:\n del self._mapping[v3]\n self._sequence.remove(v3)\n\n def v4(self: v0[KT, VT], v5: KT, v6: VT, /) -> None:\n v7 = len(self)\n ...
v0
[ "Composition" ]
Any
def v0(v1: Composition): v2 = sorted([str(e) for v3 in v1.keys()]) v4 = set([v1[s] for v5 in v2 if v1[v5]]) v6 = [] for v5 in v2: v6.append(v5) if v1[v5] != 1 and len(v4) > 1: v6.append(str(int(v1[v5]))) return ''.join(v6)
[]
[]
[]
9
import string from datetime import datetime from typing import Dict from monty.fractions import gcd from optimade.models import Species, StructureResourceAttributes from pymatgen.core.composition import Composition, formula_double_format from pymatgen.core.structure import Structure from emmet.core.base import BaseMo...
null
v0
[ "Composition" ]
str
def v0(v1: Composition) -> str: v2 = v1.element_composition v3 = sorted([el.symbol for v4 in v2.keys()]) v5 = [] if 'C' in v3: v5.append('C') if 'H' in v3: v5.append('H') v5.extend([v4 for v4 in v3 if v4 != 'C' and v4 != 'H']) else: v5 = v3 v6 = ['%s%s...
[]
[ "pymatgen" ]
[ "from pymatgen.core.composition import Composition, formula_double_format", "from pymatgen.core.structure import Structure" ]
13
import string from datetime import datetime from typing import Dict from monty.fractions import gcd from optimade.models import Species, StructureResourceAttributes from pymatgen.core.composition import Composition, formula_double_format from pymatgen.core.structure import Structure from emmet.core.base import BaseMo...
null
v35
[ "dict" ]
Any
def v35(v36: dict, *v37: str): v38 = v36 for v39 in v37: v38 = v38[v39] return v12(v38, v36)
[ { "name": "v0", "input_types": [ "str", "dict" ], "output_type": "dict", "code": "def v0(v1: str, v2: dict) -> dict:\n if v1 in ('', '#', '#/'):\n return v2\n v3 = v1[2:].split('/')\n v4 = v2\n for v5 in v3:\n try:\n v4 = v4[v5]\n except Ke...
[ "json", "os" ]
[ "import os", "import json" ]
5
""" Main functionality of `dollar-ref` library. """ import os import logging import json import yaml class ResolutionError(Exception): """ General error that happens during resolution. """ pass class InternalResolutionError(ResolutionError): """ Error while resolving internal referenses. ...
null
v0
[ "Packer" ]
None
def v0(self, v1: Packer) -> None: self.tx_changes_before.pack(v1) v1.pack_uint(len(self.operations)) for v2 in self.operations: v2.pack(v1) self.tx_changes_after.pack(v1)
[]
[]
[]
6
# This is an automatically generated file. # DO NOT EDIT or your changes may be overwritten import base64 from typing import List from xdrlib import Packer, Unpacker from .ledger_entry_changes import LedgerEntryChanges from .operation_meta import OperationMeta from ..exceptions import ValueError __all__ = ["Transacti...
null
v0
[]
bytes
def v0(self) -> bytes: v1 = Packer() self.pack(v1) return v1.get_buffer()
[]
[ "xdrlib" ]
[ "from xdrlib import Packer, Unpacker" ]
4
# This is an automatically generated file. # DO NOT EDIT or your changes may be overwritten import base64 from typing import List from xdrlib import Packer, Unpacker from .ledger_entry_changes import LedgerEntryChanges from .operation_meta import OperationMeta from ..exceptions import ValueError __all__ = ["Transacti...
null
v0
[]
str
def v0(self) -> str: v1 = self.to_xdr_bytes() return base64.b64encode(v1).decode()
[]
[ "base64" ]
[ "import base64" ]
3
# This is an automatically generated file. # DO NOT EDIT or your changes may be overwritten import base64 from typing import List from xdrlib import Packer, Unpacker from .ledger_entry_changes import LedgerEntryChanges from .operation_meta import OperationMeta from ..exceptions import ValueError __all__ = ["Transacti...
null
v0
[ "float", "float" ]
np.ndarray
def v0(v1: float, v2: float) -> np.ndarray: v3 = np.zeros(3, dtype=float) v3[0:2] = 25.4 / v2 v3[2] = np.min(v1) return v3
[]
[ "numpy" ]
[ "import numpy as np" ]
5
__author__ = "Marc Wang" __copyright__ = "Copyright (c) 2021 MSAM Lab - University of Waterloo" __license__ = "BSD-3-Clause" __maintainer__ = "Marc Wang" __email__ = "marc.wang@uwaterloo.ca" import numpy as np def compute_spacing(layer_thickness: float, xy_resolution: float) -> np.ndarray: """[summary] Arg...
null
v0
[]
None
def v0(self) -> None: self.discovery.shutdown_server() self.microservice.shutdown_server() super().tearDown()
[]
[]
[]
4
import os from unittest import ( mock, ) import attr from aiohttp.test_utils import ( AioHTTPTestCase, unittest_run_loop, ) from aiohttp_middlewares.cors import ( ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_ORIGIN, DEFAULT_ALLOW_HEADERS, DEFAULT_ALLO...
null
v0
[ "bool" ]
None
def v0(self, v1: bool=True) -> None: v2 = self.output v2.cursor_backward(self._cursor_pos.x) v2.cursor_up(self._cursor_pos.y) v2.erase_down() v2.reset_attributes() v2.enable_autowrap() v2.flush() self.reset(leave_alternate_screen=v1)
[]
[]
[]
9
""" Renders the command line on the console. (Redraws parts of the input line that were changed.) """ from asyncio import FIRST_COMPLETED, Future, ensure_future, sleep, wait from collections import deque from enum import Enum from typing import TYPE_CHECKING, Any, Callable, Deque, Dict, Hashable, Optional, Tuple from ...
null
v0
[]
None
def v0(self) -> None: self.erase() v1 = self.output v1.erase_screen() v1.cursor_goto(0, 0) v1.flush() self.request_absolute_cursor_position()
[]
[]
[]
7
""" Renders the command line on the console. (Redraws parts of the input line that were changed.) """ from asyncio import FIRST_COMPLETED, Future, ensure_future, sleep, wait from collections import deque from enum import Enum from typing import TYPE_CHECKING, Any, Callable, Deque, Dict, Hashable, Optional, Tuple from ...
null
v0
[]
None
def v0() -> None: self._waiting_for_cpr_futures.append(Future()) self.output.ask_for_cpr()
[]
[ "asyncio" ]
[ "from asyncio import FIRST_COMPLETED, Future, ensure_future, sleep, wait" ]
3
""" Renders the command line on the console. (Redraws parts of the input line that were changed.) """ from asyncio import FIRST_COMPLETED, Future, ensure_future, sleep, wait from collections import deque from enum import Enum from typing import TYPE_CHECKING, Any, Callable, Deque, Dict, Hashable, Optional, Tuple from ...
null
v0
[ "tf.Tensor", "int" ]
tf.Tensor
def v0(v1: tf.Tensor, v2: int) -> tf.Tensor: v3 = len(v1.shape) v4 = tf.constant([v2] + [1] * v3, dtype=tf.int32) v5 = tf.expand_dims(v1, axis=0) return tf.tile(v5, v4)
[]
[ "tensorflow" ]
[ "import tensorflow as tf" ]
5
# python3 # Copyright 2018 DeepMind Technologies Limited. 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-2.0 # # Unless re...
null
v0
[]
None
def v0(self, **v1) -> None: self._temporary_file_url = v1['TemporaryFileURL'] v2 = ('TemporaryFileURL',) v3 = v1.copy() for v4 in v2: del v3[v4] super()._init(**v3)
[]
[]
[]
7
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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 applicab...
null
v0
[ "Any", "Any", "int", "Any" ]
Any
def v0(v1, v2, v3: int=10, v4=np.log): v5 = (v3 - 1) / v3 v6 = -v4(1 - v5) / (v2 - v1) v7 = tuple(-v4(1 - np.arange(0, 1, 1 / v3)) / v6 + v1) assert isinstance(v7, tuple), 'is not tuple' return v7
[]
[ "numpy" ]
[ "import numpy as np" ]
6
import pandas as pd import numpy as np import matplotlib.pyplot as plt from models.ijssel_system import test_ijsselmeer_cc from ema_workbench import RealParameter, CategoricalParameter, ScalarOutcome, Model from ema_workbench.analysis import prim, cart import time np.warnings.filterwarnings('ignore') # set model model...
null
v5
[ "list" ]
Any
def v5(v6: list): v7 = None v8 = 'monokai' v9 = v10 = v11 = False if '-i' in v6 or '--inline-code-lexer' in v6: v7 = v0(v6, '-i') or v0(v6, '--inline-code-lexer') if '-t' in v6 or '--code-theme' in v6: v8 = v0(v6, '-t') or v0(v6, '--code-theme') if '-y' in v6 or '--hyperlinks' in...
[ { "name": "v0", "input_types": [ "Any", "Any" ], "output_type": "Any", "code": "def v0(v1, v2):\n v3 = None\n try:\n v4 = v1.index(v2)\n if v4 + 1 < len(v1):\n v3 = v1[v4 + 1]\n except ValueError:\n pass\n return v3", "dependencies": []...
[]
[]
16
#!/usr/bin/env python # coding: utf-8 import os import sys from rich import get_console from rich.color import ColorParseError from rich.markdown import Markdown from rich.syntax import Syntax if __package__ is None and not hasattr(sys, "frozen"): # direct call of shell.py path = os.path.realpath(os.path.abs...
null
v5
[ "list" ]
Any
def v5(v6: list): v7 = None v8 = 'monokai' v9 = v10 = v11 = False if '-l' in v6 or '--line-numbers' in v6: v9 = True if '-r' in v6 or '--wrap' in v6: v10 = True if '-t' in v6 or '--code-theme' in v6: v8 = v0(v6, '-t') or v0(v6, '--code-theme') if '-b' in v6 or '--back...
[ { "name": "v0", "input_types": [ "Any", "Any" ], "output_type": "Any", "code": "def v0(v1, v2):\n v3 = None\n try:\n v4 = v1.index(v2)\n if v4 + 1 < len(v1):\n v3 = v1[v4 + 1]\n except ValueError:\n pass\n return v3", "dependencies": []...
[]
[]
14
#!/usr/bin/env python # coding: utf-8 import os import sys from rich import get_console from rich.color import ColorParseError from rich.markdown import Markdown from rich.syntax import Syntax if __package__ is None and not hasattr(sys, "frozen"): # direct call of shell.py path = os.path.realpath(os.path.abs...
null
v0
[ "Any" ]
None
def v0(self, v1) -> None: self._userpool = self._get_required_setting(v1, 'userpools', self._userpool_name) self._jwt_header_name = self._get_required_setting(v1, 'jwt_header_name') self._jwt_header_prefix = self._get_required_setting(v1, 'jwt_header_prefix') self._check_expiration = self._get_required_...
[]
[]
[]
5
from typing import Dict from cognitojwt import CognitoJWTException, decode as cognito_jwt_decode from fastapi.exceptions import HTTPException from jose import JWTError from pydantic import BaseSettings from requests.exceptions import ConnectionError as HttpConnectionError from starlette.requests import Request from ....
null
v9
[ "List[int]", "int" ]
int
def v9(self, v10: List[int], v11: int) -> int: if len(v10) == 1: return 1 v12 = [None] * len(v10) def v13(v14): if v14 == 0 and v10[v14] <= v10[v14 + 1]: return True if v14 == len(v10) - 1 and v10[v14 - 1] >= v10[v14]: return True if v10[v14 - 1] >= v...
[ { "name": "v0", "input_types": [ "Any" ], "output_type": "Any", "code": "def v0(v1):\n if v1 is None:\n return 0\n if cache[v1] is not None:\n return cache[v1]\n if finished(v1):\n return 1\n v2 = []\n v3 = None\n for v4 in range(v1 - 1, v1 - d - 1, -...
[]
[]
51
from typing import List class Solution: def maxJumps(self, arr: List[int], d: int) -> int: if len(arr) == 1: return 1 cache = [None] * len(arr) def finished(i): if i == 0 and arr[i] <= arr[i+1]: return True if i == len(arr)-1 and arr[i-...
null
v0
[ "Any" ]
'Index'
def v0(self, v1) -> 'Index': if self._recache: self._update_array_cache() if isinstance(v1, np.ndarray): v2 = v1 else: v2 = v1.values v3 = self.__class__ return v3.from_labels(v3._UFUNC_INTERSECTION(self._labels, v2))
[]
[ "numpy" ]
[ "import numpy as np" ]
9
import typing as tp import numpy as np from static_frame.core.util import mloc from static_frame.core.util import FilePathOrFileLike from static_frame.core.util import write_optional_file from static_frame.core.display import DisplayFormats from static_frame.core.display import DisplayActive from static_frame.core.di...
null
v0
[ "List[int]", "int" ]
bool
def v0(self, v1: List[int], v2: int) -> bool: for v3 in range(len(v1)): for v4 in range(len(v1)): if v3 != v4 and v1[v3] == v1[v4] and (abs(v3 - v4) <= v2): return True return False
[]
[]
[]
6
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # author: bigfoolliu """ 给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的 绝对值 至多为 k。   示例 1: 输入: nums = [1,2,3,1], k = 3 输出: true 示例 2: 输入: nums = [1,0,1,1], k = 1 输出: true 示例 3: 输入: nums = [1,2,3,1,2,3], k = 2 输出: false 来源:力扣(LeetCode) 链接:...
null
v0
[ "Any", "str", "str" ]
Any
def v0(v1, v2: str, v3: str): v4 = v2 v1({'message': v4, 'category': v3})
[]
[]
[]
3
""" A custom class to send formatted logs to Stackdriver """ import logging from typing import List import sendgrid from sendgrid.helpers.mail import ( Email, To, From, Content, Mail, Personalization, SandBoxMode, MailSettings, ) from pythonjsonlogger import jsonlogger def add_recipien...
null
v0
[ "str", "str", "List[str]" ]
None
def v0(self, v1: str, v2: str, v3: List[str]) -> None: self._send_from_email = v2 self._sendgrid_api_key = v1 self._to_emails = v3
[]
[]
[]
4
""" A custom class to send formatted logs to Stackdriver """ import logging from typing import List import sendgrid from sendgrid.helpers.mail import ( Email, To, From, Content, Mail, Personalization, SandBoxMode, MailSettings, ) from pythonjsonlogger import jsonlogger def add_recipien...
null
v0
[]
None
def v0() -> None: nonlocal retPW nonlocal tf if tf: v1 = tf.text tf.release() v2 = None
[]
[]
[]
7
#!/usr/bin/env python3 # # ViLight - lightweight Vitae client # Copyright (C) 2012 thomasv@gitorious # # This file is: # Copyright (C) 2018 Calin Culianu <calin.culianu@gmail.com> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files #...
null
v8
[]
None
def v8() -> None: nonlocal tf v0() if callable(v5): v5()
[ { "name": "v0", "input_types": [], "output_type": "None", "code": "def v0() -> None:\n nonlocal alert, tf\n for (v1, v2) in enumerate(_extant_pw_dialogs):\n if v2[0].ptr.value == alert.ptr.value:\n _extant_pw_dialogs.pop(v1)\n break\n tf.release()\n v3 = None...
[]
[]
5
#!/usr/bin/env python3 # # ViLight - lightweight Vitae client # Copyright (C) 2012 thomasv@gitorious # # This file is: # Copyright (C) 2018 Calin Culianu <calin.culianu@gmail.com> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files #...
null
v0
[ "Callable", "Any", "int", "bool" ]
Any
def v0(v1: Callable, v2, *, v3: int, v4: bool): v5 = v2.shape[v3] if v5 == 0: return v2 v6 = [(0, 0)] * v2.ndim v6[v3] = (0, v5 - 1) if v4 else (v5 - 1, 0) v7 = [1] * v2.ndim v8 = [1] * v2.ndim v8[v3] = v5 return v1(v2, v8, v7, v6)
[]
[]
[]
10
# Copyright 2022 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
[ "int", "str" ]
str
def v0(v1: int, v2: str) -> str: v1 = '%012d' % v1 if v2: return '%s-%s' % (v2, v1) return v1
[]
[]
[]
5
import math import random import time from datetime import datetime from typing import Iterator, List, Tuple import numpy as np import spooky from fastdocgen import build_achievements from perfrunner.workloads.bigfun import query_gen from spring.dictionary import ( CATEGORIES, COUNTIES, EDUCATION_STATUSES...
null
v0
[ "str" ]
str
def v0(self, v1: str) -> str: if self.is_random: return self.build_alt_email(v1) else: return super().build_email(v1)
[]
[]
[]
5
import math import random import time from datetime import datetime from typing import Iterator, List, Tuple import numpy as np import spooky from fastdocgen import build_achievements from perfrunner.workloads.bigfun import query_gen from spring.dictionary import ( CATEGORIES, COUNTIES, EDUCATION_STATUSES...
null
v3
[ "int" ]
str
def v3(self, v4: int) -> str: v5 = v4 % (self.num_docs // 4) return v0(v5, self.prefix)
[ { "name": "v0", "input_types": [ "int", "str" ], "output_type": "str", "code": "def v0(v1: int, v2: str) -> str:\n v1 = '%012d' % v1\n if v2:\n return '%s-%s' % (v2, v1)\n return v1", "dependencies": [] } ]
[]
[]
3
import math import random import time from datetime import datetime from typing import Iterator, List, Tuple import numpy as np import spooky from fastdocgen import build_achievements from perfrunner.workloads.bigfun import query_gen from spring.dictionary import ( CATEGORIES, COUNTIES, EDUCATION_STATUSES...
null
v0
[ "str", "int", "int" ]
str
def v0(self, v1: str, v2: int, v3: int) -> str: v4 = v2 % (self.num_docs // 4) return self.build_capped(v1, v4, v3)
[]
[]
[]
3
import math import random import time from datetime import datetime from typing import Iterator, List, Tuple import numpy as np import spooky from fastdocgen import build_achievements from perfrunner.workloads.bigfun import query_gen from spring.dictionary import ( CATEGORIES, COUNTIES, EDUCATION_STATUSES...
null
v0
[ "int" ]
List[int]
def v0(self, v1: int) -> List[int]: v2 = v1 // self.ARRAY_CAP * self.array_size if self.is_random: v2 = self.num_docs * self.array_size v2 += 2 * v1 // self.ARRAY_CAP * self.array_size v2 += random.randint(1, self.array_size) return [int(v2 + i) for v3 in range(self.array_size)]
[]
[ "random" ]
[ "import random" ]
7
import math import random import time from datetime import datetime from typing import Iterator, List, Tuple import numpy as np import spooky from fastdocgen import build_achievements from perfrunner.workloads.bigfun import query_gen from spring.dictionary import ( CATEGORIES, COUNTIES, EDUCATION_STATUSES...
null
v0
[ "int" ]
str
def v0(self, v1: int) -> str: if self.is_random: v2 = random.randint(70000, 90000) else: v2 = 70000 + v1 % 20000 return str(v2)
[]
[ "random" ]
[ "import random" ]
6
import math import random import time from datetime import datetime from typing import Iterator, List, Tuple import numpy as np import spooky from fastdocgen import build_achievements from perfrunner.workloads.bigfun import query_gen from spring.dictionary import ( CATEGORIES, COUNTIES, EDUCATION_STATUSES...
null
v0
[ "str", "int" ]
Any
def v0(self, v1: str, v2: int): if v1 == '': return [] if len(v1) < v2: return [v1] * 5 v3 = sorted(random.sample(range(len(v1)), v2)) v4 = [v1[0 if i == 0 else v3[i - 1]:i + v3[i]] for v5 in range(v2)] return v4
[]
[ "random" ]
[ "import random" ]
8
import math import random import time from datetime import datetime from typing import Iterator, List, Tuple import numpy as np import spooky from fastdocgen import build_achievements from perfrunner.workloads.bigfun import query_gen from spring.dictionary import ( CATEGORIES, COUNTIES, EDUCATION_STATUSES...
null
v0
[ "int" ]
Any
def v0(self, v1: int): v2 = random.randint(0, 4) v1 = v1 - 2 + v2 return ' '.join(random.sample(self.words, v1))
[]
[ "random" ]
[ "import random" ]
4
import math import random import time from datetime import datetime from typing import Iterator, List, Tuple import numpy as np import spooky from fastdocgen import build_achievements from perfrunner.workloads.bigfun import query_gen from spring.dictionary import ( CATEGORIES, COUNTIES, EDUCATION_STATUSES...
null
v0
[ "List[Dict]", "str" ]
pd.DataFrame
def v0(v1: List[Dict], v2: str) -> pd.DataFrame: v3 = {} for v4 in v1: v5 = v4['date'] if v5 in v3: v3[v5][v4['factor']] = v4[v2] else: v3[v5] = {'date': v5, v4['factor']: v4[v2]} return pd.DataFrame(v3.values())
[]
[ "pandas" ]
[ "import pandas as pd" ]
9
""" Copyright 2019 Goldman Sachs. 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 in writing, software di...
null
v0
[ "str" ]
set
def v0(v1: str) -> set: v2 = set('aeiou') v3 = v2.intersection(set(v1)) for v2 in v3: print(v2)
[]
[]
[]
5
def search4vowels(word: str) -> set: """ Display any vowel found in an asked-for word. """ vowels = set("aeiou") found = vowels.intersection(set(word)) for vowels in found: print(vowels) if __name__ == "__main__": word = input("Provide a word to search for vowels: ") search4vowels(word...
null
v0
[ "datetime" ]
datetime
def v0(v1: datetime) -> datetime: v2 = v1 - timedelta(days=v1.weekday()) return v2.replace(hour=0, minute=0, second=0, microsecond=0)
[]
[ "datetime" ]
[ "from datetime import datetime, timedelta" ]
3
from datetime import datetime, timedelta def today_str() -> str: return datetime.today().strftime('%Y%m%d') def get_date_monday(date: datetime) -> datetime: monday = date - timedelta(days=date.weekday()) return monday.replace(hour=0, minute=0, second=0, microsecond=0) def get_current_monday() -> datetime...
null
v0
[ "Union[Pattern, str]", "str" ]
Any
def v0(v1: Union[Pattern, str], v2: str): if isinstance(v1, Pattern): if v1.search(v2): return True elif v1 in v2: return True return False
[]
[ "typing" ]
[ "from typing import Dict, List, Pattern, Union" ]
7
import itertools import shutil import subprocess import sys from argparse import ArgumentParser from collections import defaultdict from distutils import spawn from typing import Dict, List, Pattern, Union from scripts.enabled_test_modules import EXTERNAL_MODULES, IGNORED_ERRORS, IGNORED_MODULES, MOCK_OBJECTS from scr...
null
v0
[]
list
async def v0(self) -> list: v1: dict = self.api_health_roles_table.scan() v2 = v1.get('Items', []) while 'LastEvaluatedKey' in v1: v1 = self.api_health_roles_table.scan(ExclusiveStartKey=v1['LastEvaluatedKey']) v2.extend(self._data_from_dynamo_replace(v1['Items'])) return v2
[]
[]
[]
7
import asyncio import sys import time import uuid import zlib from datetime import datetime # used as a placeholder for empty SID to work around this: # https://github.com/aws/aws-sdk-js/issues/833 from decimal import Decimal from typing import Any, Dict, List, Optional, Union import boto3 import sentry_sdk import si...
null
v0
[ "Any" ]
dict
async def v0(self, v1) -> dict: v2: dict = await sync_to_async(self.api_health_roles_table.get_item)(Key={'appName': v1}) return v2.get('Item', None)
[]
[]
[]
3
import asyncio import sys import time import uuid import zlib from datetime import datetime # used as a placeholder for empty SID to work around this: # https://github.com/aws/aws-sdk-js/issues/833 from decimal import Decimal from typing import Any, Dict, List, Optional, Union import boto3 import sentry_sdk import si...
null
v0
[ "Optional[str]" ]
List[Dict[str, Union[int, List[str], str]]]
async def v0(self, v1: Optional[str]='pending') -> List[Dict[str, Union[int, List[str], str]]]: v2 = await sync_to_async(self.parallel_scan_table)(self.policy_requests_table) v2 = await self.convert_policy_requests_to_v3(v2) v3 = [] if v1: for v4 in v2: if v1 and v4['status'] == v1: ...
[]
[]
[]
11
import asyncio import os import sys import time import uuid import zlib from collections import defaultdict from datetime import datetime # used as a placeholder for empty SID to work around this: # https://github.com/aws/aws-sdk-js/issues/833 from decimal import Decimal from typing import Any, Dict, List, Optional, U...
null
v0
[]
List[Dict[str, Union[int, None, str]]]
async def v0(self) -> List[Dict[str, Union[int, None, str]]]: v1 = await sync_to_async(self.group_log.scan)() v2 = [] if v1 and 'Items' in v1: v2 = self._data_from_dynamo_replace(v1['Items']) while 'LastEvaluatedKey' in v1: v1 = await sync_to_async(self.group_log.scan)(ExclusiveStartKey=...
[]
[]
[]
9
import asyncio import sys import time import uuid import zlib from datetime import datetime # used as a placeholder for empty SID to work around this: # https://github.com/aws/aws-sdk-js/issues/833 from decimal import Decimal from typing import Any, Dict, List, Optional, Union import boto3 import sentry_sdk import si...
null
v0
[ "Tuple[Tensor, Optional[Dict[str, List[Optional[Tensor]]]]]", "bool", "Optional[Dict[str, Tensor]]", "Any" ]
Any
def v0(self, v1: Tuple[Tensor, Optional[Dict[str, List[Optional[Tensor]]]]], v2: bool, v3: Optional[Dict[str, Tensor]]=None, v4='ctc'): v5 = self.get_normalized_probs_scriptable(v1, v2, v3, tag=v4) v5.batch_first = True return v5
[]
[]
[]
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 logging import os import sys import math from typing import List, Optional, Dict, Tuple from pathlib import Path import torch from tor...
null
v0
[ "Any", "Optional[Dict[str, List[Tensor]]]", "Optional[Dict[str, Dict[str, Optional[Tensor]]]]", "bool", "Optional[int]", "Optional[int]" ]
Any
def v0(self, v1, v2: Optional[Dict[str, List[Tensor]]]=None, v3: Optional[Dict[str, Dict[str, Optional[Tensor]]]]=None, v4: bool=False, v5: Optional[int]=None, v6: Optional[int]=None): (v7, v8) = self.extract_features_scriptable(v1, v2, v3, v4, v5, v6) v9 = {'encoder_out': v2} if v3 is None else None return...
[]
[]
[]
4
#!/usr/bin/env python3 import logging import math from pathlib import Path from typing import Dict, List, Optional, Tuple import torch import torch.nn as nn from torch import Tensor from fairseq import checkpoint_utils, utils from fairseq.data.data_utils import lengths_to_padding_mask from fairseq.models import ( ...
null
v0
[ "int" ]
Any
def v0(self, v1: int): v2 = self.get_by_id(id=v1) if v2 is not None: self.data_integration_connection_database_repository.delete_by_id(v1)
[]
[]
[]
4
from injector import inject from pdip.data import RepositoryProvider from pdip.dependency import IScoped from pdi.application.operation.CreateDataOperation.CreateDataIntegrationConnectionDatabaseRequest import \ CreateDataIntegrationConnectionDatabaseRequest from pdi.domain.integration import DataIntegrationConnec...
null
v0
[ "t.Tuple[t.AnyStr, ...]" ]
None
def v0(v1: t.Tuple[t.AnyStr, ...]) -> None: if not v1: return v2 = str if isinstance(v1[0], str) else bytes if any((not isinstance(item, v2) for v3 in v1)): raise TypeError(f'Cannot mix str and bytes arguments (got {v1!r})')
[]
[]
[]
6
import logging import operator import re import string import sys import typing import typing as t from datetime import date from datetime import datetime from datetime import timezone from itertools import chain from weakref import WeakKeyDictionary if t.TYPE_CHECKING: from _typeshed.wsgi import StartResponse ...
null
v0
[ "t.Union[str, bytes]", "str", "str" ]
bytes
def v0(v1: t.Union[str, bytes], v2: str=_default_encoding, v3: str='strict') -> bytes: if v1 is None or isinstance(v1, bytes): return v1 if isinstance(v1, (bytearray, memoryview)): return bytes(v1) if isinstance(v1, str): return v1.encode(v2, v3) raise TypeError('Expected bytes')
[]
[]
[]
8
import logging import operator import re import string import sys import typing import typing as t from datetime import date from datetime import datetime from datetime import timezone from itertools import chain from weakref import WeakKeyDictionary if t.TYPE_CHECKING: from _typeshed.wsgi import StartResponse ...
null
v0
[ "t.Optional[t.Any]", "t.Optional[str]", "str", "bool" ]
t.Optional[t.Union[str, bytes]]
def v0(v1: t.Optional[t.Any], v2: t.Optional[str]=_default_encoding, v3: str='strict', v4: bool=False) -> t.Optional[t.Union[str, bytes]]: if v1 is None or isinstance(v1, str): return v1 if not isinstance(v1, (bytes, bytearray)): return str(v1) if v2 is None: if v4: retur...
[]
[]
[]
9
import logging import operator import re import string import sys import typing import typing as t from datetime import date from datetime import datetime from datetime import timezone from itertools import chain from weakref import WeakKeyDictionary if t.TYPE_CHECKING: from _typeshed.wsgi import StartResponse ...
null
v0
[ "str", "str", "str" ]
str
def v0(v1: str, v2: str='utf-8', v3: str='replace') -> str: if isinstance(v1, bytes): return v1.decode('latin1', v3) return v1.encode(v2).decode('latin1', v3)
[]
[]
[]
4
import logging import operator import re import string import sys import typing import typing as t from datetime import date from datetime import datetime from datetime import timezone from itertools import chain from weakref import WeakKeyDictionary if t.TYPE_CHECKING: from _typeshed.wsgi import StartResponse ...
null
v0
[ "t.Union['WSGIEnvironment', 'Request']" ]
'WSGIEnvironment'
def v0(v1: t.Union['WSGIEnvironment', 'Request']) -> 'WSGIEnvironment': v2 = getattr(v1, 'environ', v1) assert isinstance(v2, dict), f'{type(v1).__name__!r} is not a WSGI environment (has to be a dict)' return v2
[]
[]
[]
4
import logging import operator import re import string import sys import typing import typing as t from datetime import date from datetime import datetime from datetime import timezone from itertools import chain from weakref import WeakKeyDictionary if t.TYPE_CHECKING: from _typeshed.wsgi import StartResponse ...
null
v0
[ "logging.Logger" ]
bool
def v0(v1: logging.Logger) -> bool: v2 = v1.getEffectiveLevel() v3 = v1 while v3: if any((handler.level <= v2 for v4 in v3.handlers)): return True if not v3.propagate: break v3 = v3.parent return False
[]
[]
[]
10
import logging import operator import re import string import sys import typing import typing as t from datetime import date from datetime import datetime from datetime import timezone from itertools import chain from weakref import WeakKeyDictionary if t.TYPE_CHECKING: from _typeshed.wsgi import StartResponse ...
null
v0
[ "t.Optional[datetime]" ]
t.Optional[datetime]
def v0(v1: t.Optional[datetime]) -> t.Optional[datetime]: if v1 is None: return v1 if v1.tzinfo is None: return v1.replace(tzinfo=timezone.utc) elif v1.tzinfo != timezone.utc: return v1.astimezone(timezone.utc) return v1
[]
[ "datetime" ]
[ "from datetime import date", "from datetime import datetime", "from datetime import timezone" ]
8
import logging import operator import re import string import sys import typing import typing as t from datetime import date from datetime import datetime from datetime import timezone from itertools import chain from weakref import WeakKeyDictionary if t.TYPE_CHECKING: from _typeshed.wsgi import StartResponse ...
null
v0
[ "str" ]
bytes
def v0(v1: str) -> bytes: if isinstance(v1, bytes): v1.decode('ascii') return v1 try: return v1.encode('ascii') except UnicodeError: pass return b'.'.join((p.encode('idna') for v2 in v1.split('.')))
[]
[]
[]
9
import logging import operator import re import string import sys import typing import typing as t from datetime import date from datetime import datetime from datetime import timezone from itertools import chain from weakref import WeakKeyDictionary if t.TYPE_CHECKING: from _typeshed.wsgi import StartResponse ...
null
v2
[ "t.Union[str, bytes]" ]
str
def v2(v3: t.Union[str, bytes]) -> str: if isinstance(v3, str): try: v3 = v3.encode('ascii') except UnicodeError: return v3 def v4(v5: bytes) -> str: try: return v5.decode('idna') except UnicodeError: return v5.decode('ascii', 'ign...
[ { "name": "v0", "input_types": [ "bytes" ], "output_type": "str", "code": "def v0(v1: bytes) -> str:\n try:\n return v1.decode('idna')\n except UnicodeError:\n return v1.decode('ascii', 'ignore')", "dependencies": [] } ]
[]
[]
13
import logging import operator import re import string import sys import typing import typing as t from datetime import date from datetime import datetime from datetime import timezone from itertools import chain from weakref import WeakKeyDictionary if t.TYPE_CHECKING: from _typeshed.wsgi import StartResponse ...
null
v3
[ "t.Optional[str]" ]
t.Optional[bytes]
def v3(v4: t.Optional[str]) -> t.Optional[bytes]: if v4 is None: return None v4 = v0(v4) if b':' in v4: v4 = v4.split(b':', 1)[0] if b'.' in v4: return v4 raise ValueError("Setting 'domain' for a cookie on a server running locally (ex: localhost) is not supported by complying...
[ { "name": "v0", "input_types": [ "str" ], "output_type": "bytes", "code": "def v0(v1: str) -> bytes:\n if isinstance(v1, bytes):\n v1.decode('ascii')\n return v1\n try:\n return v1.encode('ascii')\n except UnicodeError:\n pass\n return b'.'.join((p.e...
[]
[]
9
import logging import operator import re import string import sys import typing import typing as t from datetime import date from datetime import datetime from datetime import timezone from itertools import chain from weakref import WeakKeyDictionary if t.TYPE_CHECKING: from _typeshed.wsgi import StartResponse ...
null
v0
[ "bytes" ]
str
def v0(self, v1: bytes) -> str: try: return v1.decode('utf-8') except UnicodeDecodeError: return v1.decode('ansi')
[]
[]
[]
5
# Copyright (c) 2017, George Tokmaji # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL W...
null
v0
[ "np.ndarray" ]
str
def v0(self, v1: np.ndarray) -> str: v2 = '' for v3 in v1: try: v4 = np.argmax(v3) v2 += self.charset[v4] except IndexError: v2 += '' return v2
[]
[ "numpy" ]
[ "import numpy as np" ]
9
import logging from typing import List import numpy as np from deepchem.utils.typing import RDKitMol from deepchem.utils.molecule_feature_utils import one_hot_encode from deepchem.feat.base_classes import MolecularFeaturizer logger = logging.getLogger(__name__) ZINC_CHARSET = [ '#', ')', '(', '+', '-', '/', '1'...
null
v0
[ "int" ]
Any
def v0(v1: int): v1 = v1 if v1 != -1 else torch.seed() if v1 > 2 ** 32 - 1: v1 = v1 >> 32 random.seed(v1) np.random.seed(v1) torch.manual_seed(v1) torch.cuda.manual_seed_all(v1) print(f'Global seed set to {v1}.')
[]
[ "numpy", "random", "torch" ]
[ "import random", "import numpy as np", "import torch", "import torch.optim as optim", "from torch.optim.lr_scheduler import CosineAnnealingWarmRestarts" ]
9
import json import random import numpy as np import torch import torch.optim as optim from torch.optim.lr_scheduler import CosineAnnealingWarmRestarts from PIL import Image from core.taming.models import vqgan from core.optimizer import DiffGrad, AdamP, RAdam def resize_image(image, out_size): ratio = image.s...
null
v0
[]
None
def v0(self) -> None: self.skipIfNoFSMonitor() self.root = self.mkdtemp() self.hg(['init'], cwd=self.root) self.touchRelative(self.root, 'foo') self.hg(['book', 'initial'], cwd=self.root) self.hg(['addremove'], cwd=self.root) self.hg(['commit', '-m', 'initial'], cwd=self.root) self.touch...
[]
[]
[]
14
# vim:ts=4:sw=4:et: # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import pywatchman from watchman.integration.lib import WatchmanSCMTestCase from watchman.integration.lib import Watchma...
null
v0
[ "etree.ElementBase", "str" ]
str
def v0(v1: etree.ElementBase, v2: str) -> str: v3 = [] v4 = v1.xpath(v2) for v5 in v4: for v6 in v5.iter(): if v6.tag == 'p' and len(v3) > 0: v3.append('\n') for v7 in [v6.text, v6.tail]: v8 = v7 == v6.tail if v7 is not None and...
[]
[]
[]
18
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import re import requests import numpy as np import urllib.parse as parse from typing import Optional, List, Union, Dict, Tuple from io import StringIO from lxml import etree from slacktools import BlockKitBuilder as bkb class Linguistics: """Language methods""" ...
null
v9
[ "etree.ElementBase" ]
Tuple[str, str]
def v9(v10: etree.ElementBase) -> Tuple[str, str]: v11 = v0(v10, './div/a') v12 = v0(v10, './div/section') return (v11, v12)
[ { "name": "v0", "input_types": [ "etree.ElementBase", "str" ], "output_type": "str", "code": "def v0(v1: etree.ElementBase, v2: str) -> str:\n v3 = []\n v4 = v1.xpath(v2)\n for v5 in v4:\n for v6 in v5.iter():\n if v6.tag == 'p' and len(v3) > 0:\n ...
[]
[]
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import re import requests import numpy as np import urllib.parse as parse from typing import Optional, List, Union, Dict, Tuple from io import StringIO from lxml import etree from slacktools import BlockKitBuilder as bkb class Linguistics: """Language methods""" ...
null
v0
[]
List[str]
async def v0(self) -> List[str]: if self.puppet_stub is None: raise Exception('puppet_stub should not be none') v1 = await self.puppet_stub.room_list() if v1 is None: raise ValueError('can"t get room_list response') return v1.ids
[]
[]
[]
7
""" Python Wechaty - https://github.com/wechaty/python-wechaty Authors: Huan LI (李卓桓) <https://github.com/huan> Jingjing WU (吴京京) <https://github.com/wj-Mcat> 2020-now @ Copyright Wechaty Licensed under the Apache License, Version 2.0 (the 'License'); you may not use this file except in compliance wit...
null
v0
[ "str" ]
int
def v0(self, v1: str) -> int: v2 = self._event_stream.listeners(v1) return len(v2)
[]
[]
[]
3
""" Python Wechaty - https://github.com/wechaty/python-wechaty Authors: Huan LI (李卓桓) <https://github.com/huan> Jingjing WU (吴京京) <https://github.com/wj-Mcat> 2020-now @ Copyright Wechaty Licensed under the Apache License, Version 2.0 (the 'License'); you may not use this file except in compliance wit...
null
v0
[ "str" ]
None
async def v0(self, v1: str) -> None: if self.puppet_stub is None: raise Exception('puppet_stub should not be none') await self.puppet_stub.tag_contact_delete(id=v1) return None
[]
[]
[]
5
""" Python Wechaty - https://github.com/wechaty/python-wechaty Authors: Huan LI (李卓桓) <https://github.com/huan> Jingjing WU (吴京京) <https://github.com/wj-Mcat> 2020-now @ Copyright Wechaty Licensed under the Apache License, Version 2.0 (the 'License'); you may not use this file except in compliance wit...
null
v0
[ "str", "str" ]
Any
async def v0(self, v1: str, v2: str): if self.puppet_stub is None: raise Exception('puppet_stub should not be none') await self.puppet_stub.tag_contact_add(id=v1, contact_id=v2)
[]
[]
[]
4
""" Python Wechaty - https://github.com/wechaty/python-wechaty Authors: Huan LI (李卓桓) <https://github.com/huan> Jingjing WU (吴京京) <https://github.com/wj-Mcat> 2020-now @ Copyright Wechaty Licensed under the Apache License, Version 2.0 (the 'License'); you may not use this file except in compliance wit...
null
v0
[]
None
def v0(self) -> None: self.working_dir = tempfile.TemporaryDirectory(prefix='test_run_utils_', suffix='temp', dir=os.curdir) os.chdir(self.working_dir.name)
[]
[ "os", "tempfile" ]
[ "import os", "import tempfile", "from os.path import abspath" ]
3
#!/usr/bin/env python """ ================= test_run_utils.py ================= Unit tests for the util/run_utils.py module. """ import os import shutil import tempfile import unittest from os.path import abspath from unittest.mock import patch from pkg_resources import resource_filename from opera.util.logger imp...
null
v0
[]
None
def v0(self) -> None: os.chdir(self.test_dir) self.input_file.close() self.working_dir.cleanup()
[]
[ "os" ]
[ "import os", "from os.path import abspath, join" ]
4
#!/usr/bin/env python3 # # Copyright 2021, by the California Institute of Technology. # ALL RIGHTS RESERVED. # United States Government sponsorship acknowledged. # Any commercial use must be negotiated with the Office of Technology Transfer # at the California Institute of Technology. # This software may be subject to ...
null
v0
[ "tf.Tensor" ]
Any
def v0(self, v1: tf.Tensor): if self._params.is_training: v2 = {'inputs': tf.io.VarLenFeature(tf.int64), 'targets': tf.io.VarLenFeature(tf.int64)} v3 = tf.io.parse_single_example(v1, v2) v3['inputs'] = tf.sparse.to_dense(v3['inputs']) v3['targets'] = tf.sparse.to_dense(v3['targets'])...
[]
[ "tensorflow" ]
[ "import tensorflow as tf" ]
16
# Copyright 2020 The TensorFlow Authors. 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-2.0 # # Unless required by applica...
null
v0
[ "Any", "Optional[tf.distribute.InputContext]" ]
Any
def v0(self, v1, v2: Optional[tf.distribute.InputContext]=None): v3 = {} for (v4, v5) in v1.element_spec.items(): if v4 == 'unique_id': v3[v4] = [] else: v3[v4] = [self._max_seq_length] if self._static_batch else [None] v6 = v2.get_per_replica_batch_size(self._global_...
[]
[]
[]
9
# Copyright 2020 The TensorFlow Authors. 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-2.0 # # Unless required by applica...
null
v2
[ "Any" ]
str
def v2(v3) -> str: if inspect.isfunction(v3): return v0(v3) return '{0}.{1}'.format(v3.__class__.__module__, v3.__class__.__name__)
[ { "name": "v0", "input_types": [ "Any" ], "output_type": "str", "code": "def v0(v1) -> str:\n return inspect.getmodule(v1).__name__ + '.' + v1.__name__", "dependencies": [] } ]
[ "inspect" ]
[ "import inspect" ]
4
# ======================================================================== # Copyright 2020 Emory University # # 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/lice...
null
v0
[ "Any" ]
str
def v0(v1) -> str: v2 = str(v1) assert v2.startswith("<class '"), 'illegal input' v2 = v2[len("<class '"):] assert v2.endswith("'>"), 'illegal input' v2 = v2[:-len("'>")] return v2
[]
[]
[]
7
# ======================================================================== # Copyright 2020 Emory University # # 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/lice...
null
v0
[ "Any", "Any" ]
None
def v0(v1, v2) -> None: v3 = 1.0 / np.sqrt(v1.size(1)) init.uniform_(v1, -v3, v3) init.uniform_(v2, -v3, v3)
[]
[ "numpy", "torch" ]
[ "import numpy as np", "import torch", "import torch.nn as nn", "import torch.nn.functional as F", "import torch.nn.init as init", "from torch.autograd import Variable" ]
4
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. from copy import deepcopy from typing import Dict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.init as init from ml.rl.preprocessing.identify_types import CONTINUOUS ...
null