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
[ "object" ]
bool
def v0(v1: object) -> bool: try: return v1.__repr__.__code__.co_filename == dataclasses.__file__ except Exception: return False
[]
[ "dataclasses" ]
[ "import dataclasses", "from dataclasses import dataclass, fields, is_dataclass" ]
5
import builtins import os from rich.repr import RichReprResult import sys from array import array from collections import Counter, defaultdict, deque, UserDict, UserList import dataclasses from dataclasses import dataclass, fields, is_dataclass from inspect import isclass from itertools import islice import re from typ...
null
v0
[]
Iterable[str]
def v0(self) -> Iterable[str]: if self.key_repr: yield self.key_repr yield self.key_separator if self.value_repr: yield self.value_repr elif self.children is not None: if self.children: yield self.open_brace if self.is_tuple and (not self.is_namedtuple...
[]
[]
[]
20
import builtins import collections import dataclasses import inspect import os import sys from array import array from collections import Counter, UserDict, UserList, defaultdict, deque from dataclasses import dataclass, fields, is_dataclass from inspect import isclass from itertools import islice from types import Map...
null
v0
[ "Any" ]
Iterable[Union[Any, Tuple[str, Any]]]
def v0(v1: Any) -> Iterable[Union[Any, Tuple[str, Any]]]: for v2 in v1: if isinstance(v2, tuple): if len(v2) == 3: (v3, v4, v5) = v2 if v5 == v4: continue yield (v3, v4) elif len(v2) == 2: (v3, v4) = ...
[]
[]
[]
15
import builtins import os from rich.repr import RichReprResult import sys from array import array from collections import Counter, defaultdict, deque, UserDict, UserList import dataclasses from dataclasses import dataclass, fields, is_dataclass from inspect import isclass from itertools import islice import re from typ...
null
v3
[ "float", "float", "int", "float" ]
np.ndarray
def v3(v4: float, v5: float, v6: int=1, v7: float=np.exp(1)) -> np.ndarray: if v5 <= 0: raise ValueError('scale parameter for Gumbel distribution must be > 0') v8 = np.random.rand(int(v6)) return v4 - v5 * v0(-v0(v8, base=v7), base=v7)
[ { "name": "v0", "input_types": [ "Any", "Any" ], "output_type": "Any", "code": "def v0(v1, v2=np.exp(1)):\n return np.log(v1) / np.log(v2)", "dependencies": [] } ]
[ "numpy" ]
[ "import numpy as np" ]
5
import numpy as np from typing import Union, List, Callable import logging from multiBatelo.score_functions import create_exponential_score_function DEFAULT_K_VALUE = 32 DEFAULT_D_VALUE = 400 DEFAULT_SCORING_FUNCTION_BASE = 1 _default_logger = logging.getLogger("multielo.multielo") class MultiElo: """ Gen...
null
v0
[ "Union[List[float], np.ndarray]", "List[int]" ]
np.ndarray
def v0(self, v1: Union[List[float], np.ndarray], v2: List[int]=None) -> np.ndarray: if not isinstance(v1, np.ndarray): v1 = np.array(v1) v3 = len(v1) v4 = self.get_actual_scores(v3, v2) v5 = self.get_expected_scores(v1) v6 = self.k * (v3 - 1) return v1 + v6 * (v4 - v5)
[]
[ "numpy" ]
[ "import numpy as np" ]
8
import numpy as np from typing import Union, List, Callable import logging from multiBatelo.score_functions import create_exponential_score_function DEFAULT_K_VALUE = 32 DEFAULT_D_VALUE = 400 DEFAULT_SCORING_FUNCTION_BASE = 1 _default_logger = logging.getLogger("multielo.multielo") class MultiElo: """ Gen...
null
v0
[ "int", "List[int]" ]
np.ndarray
def v0(self, v1: int, v2: List[int]=None) -> np.ndarray: v2 = v2 or list(range(v1)) v3 = self._score_func(v1) v3 = v3[np.argsort(np.argsort(v2))] v4 = set(v2) if len(v4) != v1: for v5 in v4: v6 = [i for (v7, v8) in enumerate(v2) if v8 == v5] v3[v6] = v3[v6].mean() ...
[]
[ "numpy" ]
[ "import numpy as np" ]
11
import numpy as np from typing import Union, List, Callable import logging from multiBatelo.score_functions import create_exponential_score_function DEFAULT_K_VALUE = 32 DEFAULT_D_VALUE = 400 DEFAULT_SCORING_FUNCTION_BASE = 1 _default_logger = logging.getLogger("multielo.multielo") class MultiElo: """ Gen...
null
v0
[ "Union[List[float], np.ndarray]" ]
np.ndarray
def v0(self, v1: Union[List[float], np.ndarray]) -> np.ndarray: if not isinstance(v1, np.ndarray): v1 = np.array(v1) if v1.ndim > 1: raise ValueError(f'ratings should be 1-dimensional array (received {v1.ndim})') v2 = v1 - v1[:, np.newaxis] print(f'diff_mx = \n{v2}') v3 = 1 / (1 + se...
[]
[ "numpy" ]
[ "import numpy as np" ]
16
import numpy as np from typing import Union, List, Callable import logging from multiBatelo.score_functions import create_exponential_score_function DEFAULT_K_VALUE = 32 DEFAULT_D_VALUE = 400 DEFAULT_SCORING_FUNCTION_BASE = 1 _default_logger = logging.getLogger("multielo.multielo") class MultiElo: """ Gen...
null
v9
[ "Union[List[float], np.ndarray]", "int", "int" ]
np.ndarray
def v9(self, v10: Union[List[float], np.ndarray], v11: int=int(100000.0), v12: int=None) -> np.ndarray: if v12 is not None: np.random.seed(v12) v13 = np.argsort(v10) v10 = sorted(v10) v14 = len(v10) v11 = int(v11) v15 = np.zeros((v14, v11)) for (v16, v17) in enumerate(v10): v...
[ { "name": "v0", "input_types": [ "float", "float", "int", "float" ], "output_type": "np.ndarray", "code": "def v0(v1: float, v2: float, v3: int=1, v4: float=np.exp(1)) -> np.ndarray:\n if v2 <= 0:\n raise ValueError('scale parameter for Gumbel distribution must ...
[ "numpy" ]
[ "import numpy as np" ]
12
import numpy as np from typing import Union, List, Callable import logging from multiBatelo.score_functions import create_exponential_score_function DEFAULT_K_VALUE = 32 DEFAULT_D_VALUE = 400 DEFAULT_SCORING_FUNCTION_BASE = 1 _default_logger = logging.getLogger("multielo.multielo") class MultiElo: """ Gen...
null
v0
[]
None
def v0(self) -> None: self.actor = self.policy.actor self.actor_target = self.policy.actor_target self.critic = self.policy.critic self.critic_target = self.policy.critic_target
[]
[]
[]
5
from typing import Any, Dict, List, Optional, Tuple, Type, Union import gym import numpy as np import torch as th from torch.nn import functional as F from stable_baselines3.common.buffers import ReplayBuffer from stable_baselines3.common.noise import ActionNoise, OrnsteinUhlenbeckActionNoise from stable_baselines3.c...
null
v0
[]
Tuple[List[str], List[str]]
def v0(self) -> Tuple[List[str], List[str]]: v1 = ['policy', 'actor.optimizer', 'critic.optimizer', 'discriminator'] v2 = ['log_ent_coef'] if self.ent_coef_optimizer is not None: v1.append('ent_coef_optimizer') else: v2.append('ent_coef_tensor') return (v1, v2)
[]
[]
[]
8
import io import pathlib import sys import time from collections import deque from logging import log from types import FunctionType as function from typing import Any, Dict, List, Optional, Tuple, Type, Union import gym import numpy as np import torch as th from numpy.core.fromnumeric import mean from numpy.lib.index...
null
v0
[ "list", "int" ]
list
def v0(self, v1: list, v2: int) -> list: v3 = self._curr_step_result if v3 is not None: self.trainer.logger_connector.cache_training_step_metrics(v3) self.trainer.hiddens = self.process_hiddens(v3) if self.trainer.terminate_on_nan: self.trainer.detect_nan_tensors(v3.loss) ...
[]
[]
[]
13
# 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
[ "int" ]
Any
def v0(self, v1: int=2): self.num_teams = v1 self.teams: Dict[int, int] = {}
[]
[]
[]
3
from typing import Dict from twitchio.dataclasses import Message class TeamData: def __init__(self, num_teams: int = 2): self.num_teams = num_teams self.teams: Dict[int, int] = {} async def handle_join(self, msg: Message) -> None: if msg.author.id in self.teams: # User al...
null
v0
[]
Tuple[str, str]
def v0() -> Tuple[str, str]: v1 = input('email: ') v2 = getpass('password: ') return (v1, v2)
[]
[ "getpass" ]
[ "from getpass import getpass" ]
4
#!/usr/bin/env python3 import argparse import os import pickle from getpass import getpass from typing import Tuple import requests from appdirs import user_cache_dir from mysodexo import api from mysodexo.constants import APPLICATION_NAME, SESSION_CACHE_FILENAME def prompt_login() -> Tuple[str, str]: """Prompt...
null
v1
[]
Tuple[requests.cookies.RequestsCookieJar, str]
def v1() -> Tuple[requests.cookies.RequestsCookieJar, str]: v2 = v0() with open(v2, 'rb') as v3: v4 = pickle.load(v3) v5 = v4['cookies'] v6 = v4['dni'] return (v5, v6)
[ { "name": "v0", "input_types": [], "output_type": "str", "code": "def v0() -> str:\n return os.path.join(user_cache_dir(appname=APPLICATION_NAME), SESSION_CACHE_FILENAME)", "dependencies": [] } ]
[ "os", "pickle" ]
[ "import os", "import pickle" ]
7
#!/usr/bin/env python3 import argparse import os import pickle from getpass import getpass from typing import Tuple import requests from appdirs import user_cache_dir from mysodexo import api from mysodexo.constants import APPLICATION_NAME, SESSION_CACHE_FILENAME def prompt_login() -> Tuple[str, str]: """Prompt...
null
v1
[ "requests.cookies.RequestsCookieJar", "str" ]
None
def v1(v2: requests.cookies.RequestsCookieJar, v3: str) -> None: v4 = v0() v5 = {'cookies': v2, 'dni': v3} os.makedirs(os.path.dirname(v4), exist_ok=True) with open(v4, 'wb') as v6: pickle.dump(v5, v6)
[ { "name": "v0", "input_types": [], "output_type": "str", "code": "def v0() -> str:\n return os.path.join(user_cache_dir(appname=APPLICATION_NAME), SESSION_CACHE_FILENAME)", "dependencies": [] } ]
[ "os", "pickle" ]
[ "import os", "import pickle" ]
6
#!/usr/bin/env python3 import argparse import os import pickle from getpass import getpass from typing import Tuple import requests from appdirs import user_cache_dir from mysodexo import api from mysodexo.constants import APPLICATION_NAME, SESSION_CACHE_FILENAME def prompt_login() -> Tuple[str, str]: """Prompt...
null
v16
[]
Tuple[requests.sessions.Session, str]
def v16() -> Tuple[requests.sessions.Session, str]: (v17, v18) = v7() v0(v17.cookies, v18) return (v17, v18)
[ { "name": "v0", "input_types": [ "requests.cookies.RequestsCookieJar", "str" ], "output_type": "None", "code": "def v0(v1: requests.cookies.RequestsCookieJar, v2: str) -> None:\n v3 = get_session_cache_path()\n v4 = {'cookies': v1, 'dni': v2}\n os.makedirs(os.path.dirname(v3...
[ "getpass", "os", "pickle" ]
[ "import os", "import pickle", "from getpass import getpass" ]
4
#!/usr/bin/env python3 import argparse import os import pickle from getpass import getpass from typing import Tuple import requests from appdirs import user_cache_dir from mysodexo import api from mysodexo.constants import APPLICATION_NAME, SESSION_CACHE_FILENAME def prompt_login() -> Tuple[str, str]: """Prompt...
null
v25
[]
Tuple[requests.sessions.Session, str]
def v25() -> Tuple[requests.sessions.Session, str]: try: (v26, v27) = v6() v28 = requests.session() v28.cookies.update(v26) except FileNotFoundError: (v28, v27) = v19() return (v28, v27)
[ { "name": "v0", "input_types": [ "requests.cookies.RequestsCookieJar", "str" ], "output_type": "None", "code": "def v0(v1: requests.cookies.RequestsCookieJar, v2: str) -> None:\n v3 = get_session_cache_path()\n v4 = {'cookies': v1, 'dni': v2}\n os.makedirs(os.path.dirname(v3...
[ "getpass", "os", "pickle", "requests" ]
[ "import os", "import pickle", "from getpass import getpass", "import requests" ]
8
#!/usr/bin/env python3 import argparse import os import pickle from getpass import getpass from typing import Tuple import requests from appdirs import user_cache_dir from mysodexo import api from mysodexo.constants import APPLICATION_NAME, SESSION_CACHE_FILENAME def prompt_login() -> Tuple[str, str]: """Prompt...
null
v0
[]
List[int]
def v0(self) -> List[int]: self.array = [*self.origin] return self.array
[]
[]
[]
3
''' Description: Shuffle a set of numbers without duplicates. Example: // Init an array with set 1, 2, and 3. int[] nums = {1,2,3}; Solution solution = new Solution(nums); // Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned. solution.shuffle(); // Rese...
null
v0
[]
List[int]
def v0(self) -> List[int]: v0(self.array) return self.array
[]
[ "random" ]
[ "from random import shuffle" ]
3
''' Description: Shuffle a set of numbers without duplicates. Example: // Init an array with set 1, 2, and 3. int[] nums = {1,2,3}; Solution solution = new Solution(nums); // Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned. solution.shuffle(); // Rese...
null
v0
[ "t.Any", "str", "t.Any" ]
t.Any
def v0(v1: t.Any, v2: str, v3: t.Any) -> t.Any: if v2 == 'INCLUDES': return v3.any(v3.contains(v1)) return None
[]
[]
[]
4
from __future__ import annotations import typing as t from functools import singledispatch from inflection import underscore from sqlalchemy import Date from sqlalchemy import DateTime from sqlalchemy import Text from sqlalchemy import Time from sqlalchemy import Unicode from sqlalchemy import UnicodeText from sqlalc...
null
v2
[ "Any", "Any", "Any", "Any", "str", "Any" ]
Any
def v2(v3, v4=None, v5='https://lol.wat', v6=False, v7: str=None, v8=None): if v8 is None: v8 = [('origin', v5)] if v7: shutil.copytree(v7, v3) subprocess.check_call(['git', 'init', '.'], cwd=v3) Path(v3).joinpath('README').write_text('Best upstream project ever!') v0(v3) subproc...
[ { "name": "v0", "input_types": [ "Any" ], "output_type": "Any", "code": "def v0(v1):\n subprocess.check_call(['git', 'config', 'user.email', 'test@example.com'], cwd=v1)\n subprocess.check_call(['git', 'config', 'user.name', 'Packit Test Suite'], cwd=v1)", "dependencies": [] } ...
[ "pathlib", "shutil", "subprocess" ]
[ "import shutil", "import subprocess", "from pathlib import Path" ]
17
# MIT License # # Copyright (c) 2018-2019 Red Hat, Inc. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, m...
null
v0
[ "Any", "int" ]
Any
def v0(self, v1: Any, v2: int=1) -> Any: v3 = v1.flatten() if self.buffer.ready_to_predict(): v4 = self.target_network.top_k_actions_for_state(v3, k=v2) else: v4 = self.random_state.choice(self.actions, size=v2) self._check_update_network() return v4
[]
[]
[]
8
from numpy.random import RandomState from typing import Any, Optional, List from numpy import arange from copy import deepcopy from pydeeprecsys.rl.neural_networks.dueling import DuelingDDQN from pydeeprecsys.rl.experience_replay.priority_replay_buffer import ( PrioritizedExperienceReplayBuffer, ) from pydeeprecsys...
null
v0
[ "Any", "Any", "float", "bool", "Any" ]
Any
def v0(self, v1: Any, v2: Any, v3: float, v4: bool, v5: Any): v6 = v1.flatten() v7 = v5.flatten() self.buffer.store_experience(v6, v2, v3, v4, v7)
[]
[]
[]
4
from numpy.random import RandomState from typing import Any, Optional, List from numpy import arange from copy import deepcopy from pydeeprecsys.rl.neural_networks.dueling import DuelingDDQN from pydeeprecsys.rl.experience_replay.priority_replay_buffer import ( PrioritizedExperienceReplayBuffer, ) from pydeeprecsys...
null
v0
[ "str", "Path", "str" ]
dict
def v0(self, v1: str, v2: Path, v3: str) -> dict: v4 = dict(atlas=v1, resolution=v3, **self.DEFAULT_PARCELLATION_NAMING.copy()) v5 = dict() for (v6, v7) in zip(['whole_brain', 'gm_cropped'], ['', 'GM']): v8 = v4.copy() v8['label'] = v7 v5[v6] = self.data_grabber.build_path(v2, v8) ...
[]
[]
[]
8
""" Definition of the :class:`NativeRegistration` class. """ from pathlib import Path from typing import Tuple from typing import Union import nibabel as nib from brain_parts.parcellation.parcellations import ( Parcellation as parcellation_manager, ) from nilearn.image.resampling import resample_to_img from nipype...
null
v0
[ "str", "str", "float", "bool" ]
dict
def v0(self, v1: str, v2: str, v3: float=None, v4: bool=False) -> dict: (v5, v6, v7) = self.initiate_subject(v2) (v8, v9) = [self.build_output_dictionary(v1, v6, 'anat').get(key) for v10 in ['whole_brain', 'gm_cropped']] self.parcellation_manager.register_parcellation_scheme(v1, v2, v6, v5.get('mni2native')...
[]
[]
[]
6
""" Definition of the :class:`NativeRegistration` class. """ from pathlib import Path from typing import Tuple from typing import Union import nibabel as nib from brain_parts.parcellation.parcellations import ( Parcellation as parcellation_manager, ) from nilearn.image.resampling import resample_to_img from nipype...
null
v0
[ "str", "str", "Union[str, list]", "float", "bool" ]
dict
def v0(self, v1: str, v2: str, v3: Union[str, list]=None, v4: float=None, v5: bool=False) -> dict: v6 = {} (v7, v8) = self.register_to_anatomical(v1, v2, v4, v5) v6['anat'] = {'whole_brain': v7, 'gm_cropped': v8} v9 = self.subjects.get(v2) or v3 if isinstance(v9, str): v9 = [v9] for v3 i...
[]
[]
[]
11
""" Definition of the :class:`NativeRegistration` class. """ from pathlib import Path from typing import Tuple from typing import Union import nibabel as nib from brain_parts.parcellation.parcellations import ( Parcellation as parcellation_manager, ) from nilearn.image.resampling import resample_to_img from nipype...
null
v0
[ "FilePath | ReadBuffer[bytes] | WriteBuffer[bytes]", "Any", "StorageOptions", "str", "bool" ]
tuple[FilePath | ReadBuffer[bytes] | WriteBuffer[bytes], IOHandles[bytes] | None, Any]
def v0(v1: FilePath | ReadBuffer[bytes] | WriteBuffer[bytes], v2: Any, v3: StorageOptions=None, v4: str='rb', v5: bool=False) -> tuple[FilePath | ReadBuffer[bytes] | WriteBuffer[bytes], IOHandles[bytes] | None, Any]: v6 = stringify_path(v1) if is_fsspec_url(v6) and v2 is None: v7 = import_optional_depen...
[]
[ "os", "pandas" ]
[ "import os", "from pandas._typing import FilePath, ReadBuffer, StorageOptions, WriteBuffer", "from pandas.compat._optional import import_optional_dependency", "from pandas.errors import AbstractMethodError", "from pandas.util._decorators import doc", "from pandas import DataFrame, MultiIndex, get_option",...
13
""" parquet compat """ from __future__ import annotations import io import os from typing import Any from warnings import catch_warnings from pandas._typing import ( FilePath, ReadBuffer, StorageOptions, WriteBuffer, ) from pandas.compat._optional import import_optional_dependency from pandas.errors i...
null
v0
[ "DataFrame", "Any", "Any", "Any", "Any", "StorageOptions" ]
Any
def v0(self, v1: DataFrame, v2, v3='snappy', v4=None, v5=None, v6: StorageOptions=None, **v7): self.validate_dataframe(v1) if 'partition_on' in v7 and v5 is not None: raise ValueError('Cannot use both partition_on and partition_cols. Use partition_cols for partitioning data') elif 'partition_on' in ...
[]
[ "pandas", "warnings" ]
[ "from warnings import catch_warnings", "from pandas._typing import FilePath, ReadBuffer, StorageOptions, WriteBuffer", "from pandas.compat._optional import import_optional_dependency", "from pandas.errors import AbstractMethodError", "from pandas.util._decorators import doc", "from pandas import DataFrame...
16
""" parquet compat """ from __future__ import annotations import io import os from typing import Any from warnings import catch_warnings from pandas._typing import ( FilePath, ReadBuffer, StorageOptions, WriteBuffer, ) from pandas.compat._optional import import_optional_dependency from pandas.errors i...
null
v0
[ "Any", "Any", "StorageOptions" ]
Any
def v0(self, v1, v2=None, v3: StorageOptions=None, **v4): v5: dict[str, Any] = {} v6 = v4.pop('use_nullable_dtypes', False) if Version(self.api.__version__) >= Version('0.7.1'): v5['pandas_nulls'] = False if v6: raise ValueError("The 'use_nullable_dtypes' argument is not supported for th...
[]
[ "os", "pandas" ]
[ "import os", "from pandas._typing import FilePath, ReadBuffer, StorageOptions, WriteBuffer", "from pandas.compat._optional import import_optional_dependency", "from pandas.errors import AbstractMethodError", "from pandas.util._decorators import doc", "from pandas import DataFrame, MultiIndex, get_option",...
23
""" parquet compat """ from __future__ import annotations import io import os from typing import Any from warnings import catch_warnings from pandas._typing import ( FilePath, ReadBuffer, StorageOptions, WriteBuffer, ) from pandas.compat._optional import import_optional_dependency from pandas.errors i...
null
v0
[ "int", "int" ]
Any
def v0(v1: int=3, v2: int=5): v3 = 1000 v4 = [x for v5 in range(1, v3) if (v5 % 3 == 0) | (v5 % 5 == 0)] return sum(v4)
[]
[]
[]
4
""" If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def mul_sum(a: int=3, b: int=5): max_num = 1000 all_nums = [x for x in range(1, max_num) if (x % 3 == 0) | (x % 5 ==...
null
v0
[ "int" ]
Any
def v0(self, v1: int): if self.progress_controll_enabled: self.thread_animate_progress.set_progress(v1)
[]
[]
[]
3
import logging import operator import time import traceback from pathlib import Path from typing import List, Type, Set, Tuple, Optional from PyQt5.QtCore import QEvent, Qt, pyqtSignal from PyQt5.QtGui import QIcon, QWindowStateChangeEvent, QCursor from PyQt5.QtWidgets import QWidget, QVBoxLayout, QCheckBox, QHeaderVi...
null
v0
[ "dict" ]
Any
def v0(self, v1: dict): self._update_table(pkgs_info=v1, signal=True) if self.pkgs: self._update_state_when_pkgs_ready() self.stop_notifying_package_states() self.thread_notify_pkgs_ready.pkgs = self.pkgs self.thread_notify_pkgs_ready.work = True self.thread_notify_pkgs_r...
[]
[]
[]
8
import logging import operator import time import traceback from pathlib import Path from typing import List, Type, Set, Tuple, Optional from PyQt5.QtCore import QEvent, Qt, pyqtSignal from PyQt5.QtGui import QIcon, QWindowStateChangeEvent, QCursor from PyQt5.QtWidgets import QWidget, QVBoxLayout, QCheckBox, QHeaderVi...
null
v0
[ "int" ]
Any
def v0(self, v1: int): self.filter_only_apps = v1 == 2 self.begin_apply_filters()
[]
[]
[]
3
import logging import operator import time import traceback from pathlib import Path from typing import List, Type, Set, Tuple, Optional from PyQt5.QtCore import QEvent, Qt, pyqtSignal from PyQt5.QtGui import QIcon, QWindowStateChangeEvent, QCursor from PyQt5.QtWidgets import QWidget, QVBoxLayout, QCheckBox, QHeaderVi...
null
v0
[ "int" ]
Any
def v0(self, v1: int): self.type_filter = self.combo_filter_type.itemData(v1) self.combo_filter_type.adjustSize() self.begin_apply_filters()
[]
[]
[]
4
import logging import operator import time import traceback from pathlib import Path from typing import List, Type, Set, Tuple, Optional from PyQt5.QtCore import QEvent, Qt, pyqtSignal from PyQt5.QtGui import QIcon, QWindowStateChangeEvent, QCursor from PyQt5.QtWidgets import QWidget, QVBoxLayout, QCheckBox, QHeaderVi...
null
v0
[ "int" ]
Any
def v0(self, v1: int): self.category_filter = self.combo_categories.itemData(v1) self.begin_apply_filters()
[]
[]
[]
3
import logging import operator import time import traceback from pathlib import Path from typing import List, Type, Set, Tuple, Optional from PyQt5.QtCore import QEvent, Qt, pyqtSignal from PyQt5.QtGui import QIcon, QWindowStateChangeEvent, QCursor from PyQt5.QtWidgets import QWidget, QVBoxLayout, QCheckBox, QHeaderVi...
null
v0
[ "bool" ]
Any
def v0(self, v1: bool): if v1: self.textarea_details.show() else: self.textarea_details.hide()
[]
[]
[]
5
import logging import operator import time import traceback from pathlib import Path from typing import List, Type, Set, Tuple, Optional from PyQt5.QtCore import QEvent, Qt, pyqtSignal from PyQt5.QtGui import QIcon, QWindowStateChangeEvent, QCursor from PyQt5.QtWidgets import QWidget, QVBoxLayout, QCheckBox, QHeaderVi...
null
v0
[ "bool" ]
Any
def v0(self, v1: bool): self.search_bar.clear() self._begin_action(self.i18n['manage_window.status.suggestions']) self._handle_console_option(False) self.comp_manager.set_components_visible(False) self.suggestions_requested = True self.thread_suggestions.filter_installed = v1 self.thread_sug...
[]
[]
[]
8
import logging import operator import time import traceback from pathlib import Path from typing import List, Type, Set, Tuple, Optional from PyQt5.QtCore import QEvent, Qt, pyqtSignal from PyQt5.QtGui import QIcon, QWindowStateChangeEvent, QCursor from PyQt5.QtWidgets import QWidget, QVBoxLayout, QCheckBox, QHeaderVi...
null
v0
[ "str" ]
Any
def v0(self, v1: str): self.label_substatus.setText('<p>{}</p>'.format(v1)) if not v1: self.toolbar_substatus.hide() elif not self.toolbar_substatus.isVisible() and self.progress_bar.isVisible(): self.toolbar_substatus.show()
[]
[]
[]
6
import logging import operator import time import traceback from pathlib import Path from typing import List, Type, Set, Tuple, Optional from PyQt5.QtCore import QEvent, Qt, pyqtSignal from PyQt5.QtGui import QIcon, QWindowStateChangeEvent, QCursor from PyQt5.QtWidgets import QWidget, QVBoxLayout, QCheckBox, QHeaderVi...
null
v0
[ "str" ]
Any
def v0(self, v1: str): v2 = self.i18n.get('category.{}'.format(v1), self.i18n.get(v1, v1)) self.combo_categories.addItem(v2.capitalize(), v1)
[]
[]
[]
3
import logging import operator import time import traceback from pathlib import Path from typing import List, Type, Set, Tuple, Optional from PyQt5.QtCore import QEvent, Qt, pyqtSignal from PyQt5.QtGui import QIcon, QWindowStateChangeEvent, QCursor from PyQt5.QtWidgets import QWidget, QVBoxLayout, QCheckBox, QHeaderVi...
null
v0
[]
Set[str]
def v0(self) -> Set[str]: if self.combo_categories.count() > 1: return {self.combo_categories.itemData(idx) for v1 in range(self.combo_categories.count()) if v1 > 0}
[]
[]
[]
3
import logging import operator import time import traceback from pathlib import Path from typing import List, Type, Set, Tuple, Optional from PyQt5.QtCore import QEvent, Qt, pyqtSignal from PyQt5.QtGui import QIcon, QWindowStateChangeEvent, QCursor from PyQt5.QtWidgets import QWidget, QVBoxLayout, QCheckBox, QHeaderVi...
null
v0
[ "bool" ]
Any
def v0(self, v1: bool=True): v2 = self.table_apps.get_width() v3 = self.toolbar_filters.sizeHint().width() v4 = self.toolbar_status.sizeHint().width() v5 = max(v2, v3, v4) v5 *= 1.05 if self.pkgs and v1 or v5 > self.width(): self.resize(int(v5), self.height())
[]
[]
[]
8
import logging import operator import time import traceback from pathlib import Path from typing import List, Type, Set, Tuple, Optional from PyQt5.QtCore import QEvent, Qt, pyqtSignal from PyQt5.QtGui import QIcon, QWindowStateChangeEvent, QCursor from PyQt5.QtWidgets import QWidget, QVBoxLayout, QCheckBox, QHeaderVi...
null
v0
[ "Any", "int" ]
Any
def v0(self, v1, v2: int=None): self.filter_updates = False self._begin_action('{} {}'.format(self.i18n['manage_window.status.searching'], v1 if v1 else ''), action_id=v2)
[]
[]
[]
3
import logging import operator import time import traceback from pathlib import Path from typing import List, Type, Set, Tuple, Optional from PyQt5.QtCore import QEvent, Qt, pyqtSignal from PyQt5.QtGui import QIcon, QWindowStateChangeEvent, QCursor from PyQt5.QtWidgets import QWidget, QVBoxLayout, QCheckBox, QHeaderVi...
null
v0
[ "np.ndarray", "np.ndarray", "Optional[int]", "bool" ]
np.ndarray
def v0(v1: np.ndarray, v2: np.ndarray, v3: Optional[int]=None, v4: bool=False) -> np.ndarray: if np.shape(v2) != np.shape(v1): raise ValueError('`labels` and `scores` must have same shape') if v3 is None: v3 = len(v2) v5 = np.where(v1[1:] != v1[:-1])[0] + 1 v6 = v1[0] == 1 v7 = np.co...
[]
[ "numpy" ]
[ "import numpy as np" ]
21
import bagel import numpy as np from sklearn.metrics import precision_recall_curve from typing import Sequence, Tuple, Dict, Optional def _adjust_scores(labels: np.ndarray, scores: np.ndarray, delay: Optional[int] = None, inplace: bool = False) -> np.ndarray: ...
null
v0
[ "Sequence", "np.ndarray" ]
Tuple[np.ndarray, ...]
def v0(v1: Sequence, v2: np.ndarray) -> Tuple[np.ndarray, ...]: v3 = [] for v4 in v1: v4 = np.copy(v4) v3.append(v4[v2 != 1]) return tuple(v3)
[]
[ "numpy" ]
[ "import numpy as np" ]
6
import bagel import numpy as np from sklearn.metrics import precision_recall_curve from typing import Sequence, Tuple, Dict, Optional def _adjust_scores(labels: np.ndarray, scores: np.ndarray, delay: Optional[int] = None, inplace: bool = False) -> np.ndarray: ...
null
v0
[ "np.ndarray", "np.ndarray" ]
Tuple[float, float, float, float]
def v0(v1: np.ndarray, v2: np.ndarray) -> Tuple[float, float, float, float]: (v3, v4, v5) = precision_recall_curve(y_true=v1, probas_pred=v2) v6 = 2 * v3 * v4 / np.clip(v3 + v4, a_min=1e-08, a_max=None) v7 = v5[np.argmax(v6)] v8 = v3[np.argmax(v6)] v9 = v4[np.argmax(v6)] return (v7, v8, v9, np.m...
[]
[ "numpy", "sklearn" ]
[ "import numpy as np", "from sklearn.metrics import precision_recall_curve" ]
7
import bagel import numpy as np from sklearn.metrics import precision_recall_curve from typing import Sequence, Tuple, Dict, Optional def _adjust_scores(labels: np.ndarray, scores: np.ndarray, delay: Optional[int] = None, inplace: bool = False) -> np.ndarray: ...
null
v26
[ "np.ndarray", "np.ndarray", "np.ndarray", "int", "Optional[int]" ]
Dict
def v26(v27: np.ndarray, v28: np.ndarray, v29: np.ndarray, v30: int, v31: Optional[int]=None) -> Dict: v27 = v27[v30 - 1:] v28 = v28[v30 - 1:] v29 = v29[v30 - 1:] v32 = v0(labels=v27, scores=v28, delay=v31) (v33, v32) = v21([v27, v32], missing=v29) (v34, v35, v36, v37) = v11(labels=v33, scores=v...
[ { "name": "v0", "input_types": [ "np.ndarray", "np.ndarray", "Optional[int]", "bool" ], "output_type": "np.ndarray", "code": "def v0(v1: np.ndarray, v2: np.ndarray, v3: Optional[int]=None, v4: bool=False) -> np.ndarray:\n if np.shape(v2) != np.shape(v1):\n raise...
[ "numpy", "sklearn" ]
[ "import numpy as np", "from sklearn.metrics import precision_recall_curve" ]
8
import bagel import numpy as np from sklearn.metrics import precision_recall_curve from typing import Sequence, Tuple, Dict, Optional def _adjust_scores(labels: np.ndarray, scores: np.ndarray, delay: Optional[int] = None, inplace: bool = False) -> np.ndarray: ...
null
v0
[ "str", "str", "Any" ]
bool
def v0(v1: str, v2: str, v3) -> bool: print('Converting %s to %s' % (v1, v2)) return True
[]
[]
[]
3
# -*- coding: utf-8 -*- # Copyright (c) 2015, Mayo Clinic # 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...
null
v0
[ "cmd2.plugin.PostparsingData" ]
cmd2.plugin.PostparsingData
def v0(self, v1: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData: self.called_postparsing += 1 v1.stop = True return v1
[]
[]
[]
4
# coding=utf-8 # flake8: noqa E302 """ Test plugin infrastructure and hooks. """ import sys import pytest # Python 3.5 had some regressions in the unitest.mock module, so use 3rd party mock if available try: import mock except ImportError: from unittest import mock import cmd2 from cmd2 import plugin class...
null
v0
[ "bool", "cmd2.Statement" ]
bool
def v0(self, v1: bool, v2: cmd2.Statement) -> bool: self.called_postcmd += 1 return v1
[]
[]
[]
3
# coding=utf-8 # flake8: noqa E302 """ Test plugin infrastructure and hooks. """ import sys import pytest # Python 3.5 had some regressions in the unitest.mock module, so use 3rd party mock if available try: import mock except ImportError: from unittest import mock import cmd2 from cmd2 import plugin class...
null
v0
[ "plugin.PrecommandData" ]
plugin.PrecommandData
def v0(self, v1: plugin.PrecommandData) -> plugin.PrecommandData: self.called_precmd += 1 raise ValueError
[]
[]
[]
3
# coding=utf-8 # flake8: noqa E302 """ Test plugin infrastructure and hooks. """ import sys import pytest # Python 3.5 had some regressions in the unitest.mock module, so use 3rd party mock if available try: import mock except ImportError: from unittest import mock import cmd2 from cmd2 import plugin class...
null
v0
[ "plugin.PostcommandData" ]
plugin.PostcommandData
def v0(self, v1: plugin.PostcommandData) -> plugin.PostcommandData: self.called_postcmd += 1 return v1
[]
[]
[]
3
# coding=utf-8 # flake8: noqa E302 """ Test plugin infrastructure and hooks. """ import sys import pytest # Python 3.5 had some regressions in the unitest.mock module, so use 3rd party mock if available try: import mock except ImportError: from unittest import mock import cmd2 from cmd2 import plugin class...
null
v0
[ "plugin.PostcommandData" ]
plugin.PostcommandData
def v0(self, v1: plugin.PostcommandData) -> plugin.PostcommandData: self.called_postcmd += 1 raise ZeroDivisionError
[]
[]
[]
3
# coding=utf-8 # flake8: noqa E302 """ Test plugin infrastructure and hooks. """ import sys import pytest # Python 3.5 had some regressions in the unitest.mock module, so use 3rd party mock if available try: import mock except ImportError: from unittest import mock import cmd2 from cmd2 import plugin class...
null
v0
[ "plugin.CommandFinalizationData" ]
plugin.CommandFinalizationData
def v0(self, v1: plugin.CommandFinalizationData) -> plugin.CommandFinalizationData: self.called_cmdfinalization += 1 return v1
[]
[]
[]
3
# coding=utf-8 # flake8: noqa E302 """ Test plugin infrastructure and hooks. """ import sys import pytest # Python 3.5 had some regressions in the unitest.mock module, so use 3rd party mock if available try: import mock except ImportError: from unittest import mock import cmd2 from cmd2 import plugin class...
null
v0
[ "cmd2.plugin.CommandFinalizationData" ]
cmd2.plugin.CommandFinalizationData
def v0(self, v1: cmd2.plugin.CommandFinalizationData) -> cmd2.plugin.CommandFinalizationData: self.called_cmdfinalization += 1 v1.stop = True return v1
[]
[]
[]
4
# coding=utf-8 # flake8: noqa E302 """ Test plugin infrastructure and hooks. """ import sys import pytest # Python 3.5 had some regressions in the unitest.mock module, so use 3rd party mock if available try: import mock except ImportError: from unittest import mock import cmd2 from cmd2 import plugin class...
null
v4
[ "Any", "v0" ]
Any
def v4(self, v5, v6: v0): if len(self._clause) == 0: self._single = True else: self._single = False self._clause.append(v6) self._clause.append(v5) return self
[]
[]
[]
8
"""Encoder Description: This module encodes Planning Problem to Propositional Formulas in CNF (Conjunctive Normal Form) License: Copyright 2021 Debby Nirwan Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may...
[ "class v0(Enum):\n v1 = (0,)\n v2 = (1,)\n v3 = 2" ]
v0
[ "list" ]
Any
def v0(v1: list, **v2): if len(v1) == 1: return v1[0] return Concatenate(**v2)(v1)
[]
[]
[]
4
import logging import json from typing import List, Type, Union from keras.models import Model from keras.layers.merge import Concatenate from keras.layers import ( Dense, LSTM, Bidirectional, Embedding, Input, Dropout, TimeDistributed ) import delft.sequenceLabelling.wrapper from delft.utilities.layers impor...
null
v0
[]
np.ndarray
def v0(self) -> np.ndarray: with self.to_pil() as v1: return np.asarray(v1)
[]
[ "numpy" ]
[ "import numpy as np" ]
3
# # 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 # distributed un...
null
v0
[ "str" ]
Any
def v0(v1: str): v2 = '' for v3 in range(len(v1)): v2 += v1[~v3] return v2
[]
[]
[]
5
def reverse_string(a_string: str): """Take the input a_string and return it reversed (e.g. "hello" becomes "olleh".""" reversed_string = "" for i in range(len(a_string)): reversed_string += a_string[~i] return reversed_string
null
v1
[ "v0" ]
v0
def v1(v2: v0) -> v0: v2._dectest_before = True return v2
[]
[]
[]
3
from typing import TypeVar, Callable import unittest from ._types import TestMethod _F = TypeVar("_F", bound=TestMethod) def test(method: _F) -> _F: """Decorator that flags a method as a test method.""" method._dectest_test = True # type: ignore return method def before(method: _F) -> _F: """Deco...
[ "v0 = TypeVar('_F', bound=TestMethod)" ]
v5
[ "str" ]
Callable[[v0], v0]
def v5(v6: str) -> Callable[[v0], v0]: if not isinstance(v6, str): raise TypeError('first argument to @skip must be a reason string') def v7(v8: v0) -> v0: return unittest.skip(v6)(v3(v8)) return v7
[ { "name": "v1", "input_types": [ "v0" ], "output_type": "v0", "code": "def v1(v2: v0) -> v0:\n return unittest.skipUnless(condition, reason)(test(v2))", "dependencies": [ "v3" ] }, { "name": "v3", "input_types": [ "v0" ], "output_type": "v0", ...
[]
[]
7
from typing import TypeVar, Callable import unittest from ._types import TestMethod _F = TypeVar("_F", bound=TestMethod) def test(method: _F) -> _F: """Decorator that flags a method as a test method.""" method._dectest_test = True # type: ignore return method def before(method: _F) -> _F: """Deco...
[ "v0 = TypeVar('_F', bound=TestMethod)" ]
v5
[ "bool", "str" ]
Callable[[v0], v0]
def v5(v6: bool, v7: str) -> Callable[[v0], v0]: def v8(v9: v0) -> v0: return unittest.skipUnless(v6, v7)(v3(v9)) return v8
[ { "name": "v1", "input_types": [ "v0" ], "output_type": "v0", "code": "def v1(v2: v0) -> v0:\n return unittest.skipUnless(condition, reason)(test(v2))", "dependencies": [ "v3" ] }, { "name": "v3", "input_types": [ "v0" ], "output_type": "v0", ...
[]
[]
5
from typing import TypeVar, Callable import unittest from ._types import TestMethod _F = TypeVar("_F", bound=TestMethod) def test(method: _F) -> _F: """Decorator that flags a method as a test method.""" method._dectest_test = True # type: ignore return method def before(method: _F) -> _F: """Deco...
[ "v0 = TypeVar('_F', bound=TestMethod)" ]
v0
[ "str" ]
None
def v0(v1: str) -> None: try: os.remove(v1) except OSError: pass
[]
[ "os" ]
[ "import os" ]
5
import os import re import sys import time from subprocess import PIPE, run from types import ModuleType from typing import Union import docker import requests import storm.__main__ as storm from lazycluster import Runtime, RuntimeGroup, RuntimeManager, RuntimeTask from .config import RUNTIME_DOCKER_IMAGE, RUNTIME_N...
null
v0
[ "dict", "int" ]
str
def v0(self, v1: dict, v2: int=0) -> str: v3 = ''.join([' ' for v4 in range(0, v2)]) v5 = '' for (v6, v7) in v1.items(): for v8 in v7: if isinstance(v8, dict): v5 += '{}{}:\n'.format(v3, v6) v5 += self.generate_err_msg(v8, v2 + 1) pass ...
[]
[]
[]
13
from enum import Enum from typing import Any from importlib import import_module class ValidationError(Exception): """ Error class for validation failed """ def __init__(self, payload: dict): """ :param message: error message """ self.payload = payload def generate...
null
v0
[ "str" ]
Any
def v0(self, v1: str): if v1 == 'json': self._parser = import_module('json') elif v1 == 'toml': try: self._parser = import_module('toml') except ImportError: raise Exception('CatConfig needs toml parser to work, please add `toml` module to your project') elif ...
[]
[ "importlib" ]
[ "from importlib import import_module" ]
16
from enum import Enum from typing import Any from importlib import import_module class ValidationError(Exception): """ Error class for validation failed """ def __init__(self, payload: dict): """ :param message: error message """ self.payload = payload def generate...
null
v0
[ "str", "'str'" ]
None
def v0(self, v1: str, v2: 'str'=None) -> None: with open(v1, 'r') as v3: self.load_from_string(v3.read(), v2)
[]
[]
[]
3
from enum import Enum from typing import Any from importlib import import_module class ValidationError(Exception): """ Error class for validation failed """ def __init__(self, payload: dict): """ :param message: error message """ self.payload = payload def generate...
null
v0
[ "str", "'str'" ]
None
def v0(self, v1: str, v2: 'str'=None) -> None: if v2: self._import_parser(v2) return self.load(self._parser.loads(v1))
[]
[]
[]
4
from enum import Enum from typing import Any from importlib import import_module class ValidationError(Exception): """ Error class for validation failed """ def __init__(self, payload: dict): """ :param message: error message """ self.payload = payload def generate...
null
v0
[ "dict" ]
None
def v0(self, v1: dict) -> None: if self._validator_schema: self.validate(v1) self._data.update(v1)
[]
[]
[]
4
from enum import Enum from typing import Any from importlib import import_module class ValidationError(Exception): """ Error class for validation failed """ def __init__(self, payload: dict): """ :param message: error message """ self.payload = payload def generate...
null
v0
[]
pd.DataFrame
def v0() -> pd.DataFrame: v1 = 'http://www.nanhua.net/ianalysis/plate-variety.json' v2 = requests.get(v1) v3 = v2.json() v4 = pd.DataFrame(v3) v4['firstday'] = pd.to_datetime(v4['firstday']).dt.date return v4
[]
[ "pandas", "requests" ]
[ "import requests", "import pandas as pd" ]
7
#!/usr/bin/env python # -*- coding:utf-8 -*- """ Date: 2021/12/20 14:52 Desc: 南华期货-商品指数历史走势-价格指数-数值 http://www.nanhua.net/nhzc/varietytrend.html 1000 点开始, 用收益率累计 http://www.nanhua.net/ianalysis/varietyindex/price/A.json?t=1574932974280 """ import time import requests import pandas as pd def futures_nh_index_symbol_t...
null
v0
[ "torch.nn.Module" ]
None
def v0(v1: torch.nn.Module) -> None: for v2 in v1.modules(): v2._backward_hooks = OrderedDict() v2._is_full_backward_hook = None v2._forward_hooks = OrderedDict() v2._forward_pre_hooks = OrderedDict() v2._state_dict_hooks = OrderedDict() v2._load_state_dict_pre_hooks ...
[]
[ "collections" ]
[ "from collections import OrderedDict" ]
8
# 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
[]
None
def v0(self) -> None: os.environ['MASTER_ADDR'] = self.cluster_environment.master_address() os.environ['MASTER_PORT'] = str(self.cluster_environment.master_port()) os.environ['RANK'] = str(self.global_rank) os.environ['WORLD_SIZE'] = str(self.world_size) os.environ['LOCAL_RANK'] = str(self.local_ran...
[]
[ "os" ]
[ "import os" ]
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
[ "bool", "bool", "Union[str, int]", "bool", "bool", "bool", "bool", "bool", "bool", "str", "str", "int", "int", "int", "str", "int", "bool", "int", "int", "bool", "bool", "int" ]
Dict
def v0(self, v1: bool, v2: bool, v3: Union[str, int], v4: bool, v5: bool, v6: bool, v7: bool, v8: bool, v9: bool, v10: str, v11: str, v12: int, v13: int, v14: int, v15: str, v16: int, v17: bool, v18: int, v19: int, v20: bool, v21: bool, v22: int, **v23) -> Dict: v24 = {'activation_checkpointing': {'partition_activa...
[]
[]
[]
12
# 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
[ "Mapping[str, Any]" ]
None
def v0(self, v1: Mapping[str, Any]) -> None: if self.load_full_weights and self.zero_stage_3: self.model_to_device() self._restore_zero_state(v1)
[]
[]
[]
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
[ "str" ]
float
def v0(self, v1: str) -> float: v1 = v1.lower() v2 = urljoin(self.base_url, f'/api/v3/simple/price?ids={v1}&vs_currencies=usd') return self._get_price(v2, v1)
[]
[ "urllib" ]
[ "from urllib.parse import urljoin" ]
4
import logging from urllib.parse import urljoin import requests from eth_typing import ChecksumAddress from safe_transaction_service.tokens.clients.exceptions import CannotGetPrice logger = logging.getLogger(__name__) class CoingeckoClient: base_url = 'https://api.coingecko.com/' def __init__(self): ...
null
v0
[ "str", "bool" ]
Any
def v0(v1: str, v2: bool=False): v3 = '[DRY RUN] ' if v2 else '' print(f'{v3}{v1}', file=sys.stderr)
[]
[ "sys" ]
[ "import sys" ]
3
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2019, 2020 Matt Post <post@cs.jhu.edu> # # 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/LICE...
null
v0
[ "str" ]
Dict[str, Any]
def v0(v1: str) -> Dict[str, Any]: v2 = {'chairs': []} with open(v1) as v3: for v4 in v3: if re.match('^\\s*$', v4): continue (v5, v6) = v4.rstrip().split(' ', maxsplit=1) if v5.startswith('chair'): v2['chairs'].append(v6) e...
[]
[ "re" ]
[ "import re" ]
14
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2019, 2020 Matt Post <post@cs.jhu.edu> # # 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/LICE...
null
v0
[ "int" ]
None
def v0(self, v1: int=1) -> None: self._check_acquired() for v2 in range(v1): try: v3 = self._waiters.popleft() except IndexError: break v3.set()
[]
[]
[]
8
from collections import deque from dataclasses import dataclass from types import TracebackType from typing import Deque, Optional, Tuple, Type from warnings import warn from ..lowlevel import cancel_shielded_checkpoint, checkpoint, checkpoint_if_cancelled from ._compat import DeprecatedAwaitable from ._eventloop impo...
null
v0
[]
None
def v0(self) -> None: self._check_acquired() for v1 in self._waiters: v1.set() self._waiters.clear()
[]
[]
[]
5
from collections import deque from dataclasses import dataclass from types import TracebackType from typing import Deque, Optional, Tuple, Type from warnings import warn from ..lowlevel import cancel_shielded_checkpoint, checkpoint, checkpoint_if_cancelled from ._compat import DeprecatedAwaitable from ._eventloop impo...
null
v0
[ "float" ]
None
async def v0(self, v1: float) -> None: warn('CapacityLimiter.set_total_tokens has been deprecated. Set the value of the"total_tokens" attribute directly.', DeprecationWarning) self.total_tokens = v1
[]
[ "warnings" ]
[ "from warnings import warn" ]
3
from collections import deque from dataclasses import dataclass from types import TracebackType from typing import Deque, Optional, Tuple, Type from warnings import warn from ..lowlevel import cancel_shielded_checkpoint, checkpoint, checkpoint_if_cancelled from ._compat import DeprecatedAwaitable from ._eventloop impo...
null
v5
[ "int", "torch.Tensor", "torch.Tensor", "v0" ]
Any
def v5(self, v6: int, v7: torch.Tensor, v8: torch.Tensor, v9: v0): v10 = [] v11 = [] for v12 in range(v6): (v13, v14) = self.representation_model(v7[v12], v8[v12], v9) v10.append(v13) v11.append(v14) v9 = v14 v15 = v1(v10, dim=0) v16 = v1(v11, dim=0) return (v15, ...
[ { "name": "v1", "input_types": [ "list", "Any" ], "output_type": "Any", "code": "def v1(v2: list, v3):\n return v0(torch.stack([state.mean for v4 in v2], dim=v3), torch.stack([v4.std for v4 in v2], dim=v3), torch.stack([v4.stoch for v4 in v2], dim=v3), torch.stack([v4.deter for v4...
[ "torch" ]
[ "import torch", "import torch.distributions as td", "import torch.nn as nn", "import torch.nn.functional as tf" ]
11
import torch import torch.distributions as td import torch.nn as nn import torch.nn.functional as tf from rlpyt.utils.collections import namedarraytuple from rlpyt.utils.buffer import buffer_method from dreamer.utils.module import FreezeParameters RSSMState = namedarraytuple('RSSMState', ['mean', 'std', 'stoch', 'det...
[ "v0 = namedarraytuple('RSSMState', ['mean', 'std', 'stoch', 'deter'])" ]
v5
[ "int", "torch.Tensor", "v0" ]
Any
def v5(self, v6: int, v7: torch.Tensor, v8: v0): v9 = [] v10 = v8 for v11 in range(v6): v10 = self.transition_model(v7[v11], v10) v9.append(v10) return v1(v9, dim=0)
[ { "name": "v1", "input_types": [ "list", "Any" ], "output_type": "Any", "code": "def v1(v2: list, v3):\n return v0(torch.stack([state.mean for v4 in v2], dim=v3), torch.stack([v4.std for v4 in v2], dim=v3), torch.stack([v4.stoch for v4 in v2], dim=v3), torch.stack([v4.deter for v4...
[ "torch" ]
[ "import torch", "import torch.distributions as td", "import torch.nn as nn", "import torch.nn.functional as tf" ]
7
import torch import torch.distributions as td import torch.nn as nn import torch.nn.functional as tf from rlpyt.utils.collections import namedarraytuple from rlpyt.utils.buffer import buffer_method from dreamer.utils.module import FreezeParameters RSSMState = namedarraytuple('RSSMState', ['mean', 'std', 'stoch', 'det...
[ "v0 = namedarraytuple('RSSMState', ['mean', 'std', 'stoch', 'deter'])" ]
v0
[]
None
def v0(self) -> None: self.__ui.volumeComboBox.currentTextChanged.connect(self.__on_change_mount_point) self.__ui.createPushButton.clicked.connect(self.__on_click_create_push_button)
[]
[]
[]
3
from os import listdir from os.path import isfile, join from re import compile from typing import Dict from PyQt5.QtCore import QRegularExpression from PyQt5.QtGui import QRegularExpressionValidator from PyQt5.QtWidgets import QDialog, QMessageBox from dbus import DBusException from snapper.SnapperConnection import S...
null
v0
[ "pd.DataFrame" ]
bool
def v0(self, v1: pd.DataFrame) -> bool: v2 = v1.query("kind == 'total' and name != 'total_revenue'") v2 = v2.filter(regex=f'^{self.month_name}', axis=1) for v3 in v2.columns: v4 = v1.query("name == 'total_revenue'")[v3].squeeze() v5 = v2[v3].sum() - v4 assert v5 < 5 return True
[]
[]
[]
8
"""Module for parsing montly school collections data.""" from typing import ClassVar import pandas as pd import pdfplumber from ...utils.misc import rename_tax_rows from ...utils.pdf import extract_words, words_to_table from .core import COLLECTION_TYPES, MonthlyCollectionsReport, get_column_names class SchoolTaxCo...
null
v0
[ "pd.DataFrame" ]
None
def v0(self, v1: pd.DataFrame) -> None: v2 = self.get_data_directory('processed') v3 = v2 / f'{self.year}-{self.month:02d}-tax.csv' super()._load_csv_data(v1, v3)
[]
[]
[]
4
"""Module for parsing montly school collections data.""" from typing import ClassVar import pandas as pd import pdfplumber from ...utils.misc import rename_tax_rows from ...utils.pdf import extract_words, words_to_table from .core import COLLECTION_TYPES, MonthlyCollectionsReport, get_column_names class SchoolTaxCo...
null
v0
[ "dict" ]
Any
def v0(v1: dict): v2 = '' v3 = '🌶️' v4 = '🍹' v5 = '🍩' v6 = '🍖' v7 = '🥖' v8 = '🥦' v9 = '🥣' v10 = '🥗' v11 = ', ' if v1['beverage']: v2 += v4 + ' Beverage' + v11 if v1['dessert']: v2 += v5 + ' Dessert' + v11 if v1['dip']: v2 += v9 + ' Dip'...
[]
[]
[]
28
import json import boto3 from datetime import datetime import ast class S3DAO: USERS_DISHES_S3_KEY = 'users-dishes' PAGE_CONTENT_S3_KEY = 'page-content' BRINE_DATA_BUCKET_NAME = 'brine-data' def __init__(self): self.s3_client = None self.users_dishes_last_modified = None self.p...
null
v0
[ "str", "Any" ]
Any
def v0(self, v1: str, v2=None): if v2 is None: v3 = self.__getS3Client() v2 = v3.get_object(Bucket=self.BRINE_DATA_BUCKET_NAME, Key=v1) v4 = self.__getTimeStampFromS3Object(v2) return v4
[]
[]
[]
6
import json import boto3 from datetime import datetime import ast class S3DAO: USERS_DISHES_S3_KEY = 'users-dishes' PAGE_CONTENT_S3_KEY = 'page-content' BRINE_DATA_BUCKET_NAME = 'brine-data' def __init__(self): self.s3_client = None self.users_dishes_last_modified = None self.p...
null
v0
[ "dict" ]
Any
def v0(self, v1: dict): v2 = self.__getS3Client() v3 = json.dumps(v1) v2.put_object(Bucket=self.BRINE_DATA_BUCKET_NAME, Key=self.USERS_DISHES_S3_KEY, Body=v3)
[]
[ "json" ]
[ "import json" ]
4
import json import boto3 from datetime import datetime import ast class S3DAO: USERS_DISHES_S3_KEY = 'users-dishes' PAGE_CONTENT_S3_KEY = 'page-content' BRINE_DATA_BUCKET_NAME = 'brine-data' def __init__(self): self.s3_client = None self.users_dishes_last_modified = None self.p...
null
v0
[ "str" ]
Any
def v0(self, v1: str): v2 = self.__getUsersDishesFromS3() for v3 in v2: if v3 == v1: return True return False
[]
[]
[]
6
import json import boto3 from datetime import datetime import ast class S3DAO: USERS_DISHES_S3_KEY = 'users-dishes' PAGE_CONTENT_S3_KEY = 'page-content' BRINE_DATA_BUCKET_NAME = 'brine-data' def __init__(self): self.s3_client = None self.users_dishes_last_modified = None self.p...
null
v0
[ "str", "str" ]
Any
def v0(self, v1: str, v2: str): v3 = self.__getUsersDishesFromS3() v4 = self.__isUserInDb(v1) if not v4: self.__createNewUserInUsersDishes(v1) v3[v1].append(v2)
[]
[]
[]
6
import json import boto3 from datetime import datetime import ast class S3DAO: USERS_DISHES_S3_KEY = 'users-dishes' PAGE_CONTENT_S3_KEY = 'page-content' BRINE_DATA_BUCKET_NAME = 'brine-data' def __init__(self): self.s3_client = None self.users_dishes_last_modified = None self.p...
null
v0
[ "str", "str" ]
Any
def v0(self, v1: str, v2: str): v3 = self.isDishNew(v1, v2) if v3: return self.users_dishes[v1].remove(v2)
[]
[]
[]
5
import json import boto3 from datetime import datetime import ast class S3DAO: USERS_DISHES_S3_KEY = 'users-dishes' PAGE_CONTENT_S3_KEY = 'page-content' BRINE_DATA_BUCKET_NAME = 'brine-data' def __init__(self): self.s3_client = None self.users_dishes_last_modified = None self.p...
null
v0
[ "str", "str" ]
Any
def v0(self, v1: str, v2: str): v3 = self.__getUsersDishesFromS3()[v1] if v2 in v3: return False return True
[]
[]
[]
5
import json import boto3 from datetime import datetime import ast class S3DAO: USERS_DISHES_S3_KEY = 'users-dishes' PAGE_CONTENT_S3_KEY = 'page-content' BRINE_DATA_BUCKET_NAME = 'brine-data' def __init__(self): self.s3_client = None self.users_dishes_last_modified = None self.p...
null
v0
[ "str" ]
Any
def v0(self, v1: str): v2 = self.__getTimeStampOfLastUpdateFromS3(self.USERS_DISHES_S3_KEY) v3 = dict(self.users_dishes) if v2 < self.users_dishes_last_modified: v3 = self.__getUsersDishesFromS3() v3[v1] = self.users_dishes[v1] print('users dishes to save') print(v3) self.__saveU...
[]
[]
[]
9
import json import boto3 from datetime import datetime import ast class S3DAO: USERS_DISHES_S3_KEY = 'users-dishes' PAGE_CONTENT_S3_KEY = 'page-content' BRINE_DATA_BUCKET_NAME = 'brine-data' def __init__(self): self.s3_client = None self.users_dishes_last_modified = None self.p...
null
v0
[ "str" ]
List[str]
def v0(v1: str) -> List[str]: v2 = v1 + 'evaluation/' return [o for v3 in os.listdir(v2) if os.path.isdir(os.path.join(v2, v3))]
[]
[ "os" ]
[ "import os" ]
3
#!/usr/bin/env python """MIT - CSAIL - Gifford Lab - seqgra seqgra complete pipeline: 1. generate data based on data definition (once), see run_simulator.py 2. train model on data (once), see run_learner.py 3. evaluate model performance with SIS, see run_sis.py @author: Konstantin Krismer """ import argparse import...
null
v0
[ "str", "List[str]" ]
List[str]
def v0(v1: str, v2: List[str]) -> List[str]: v3: List[str] = [] for v4 in v2: v5 = v1 + 'evaluation/' + v4 + '/' v3 += [o for v6 in os.listdir(v5) if os.path.isdir(os.path.join(v5, v6))] return list(set(v3))
[]
[ "os" ]
[ "import os" ]
6
#!/usr/bin/env python """MIT - CSAIL - Gifford Lab - seqgra seqgra complete pipeline: 1. generate data based on data definition (once), see run_simulator.py 2. train model on data (once), see run_learner.py 3. evaluate model performance with SIS, see run_sis.py @author: Konstantin Krismer """ import argparse import...
null
v4
[ "Iterable" ]
int
def v4(v5: Iterable) -> int: v5 = list(v5) v6 = 10000 v7 = 70 / 100000000 v8 = 100 v9: Number v9 = len(v5) - v6 v9 = v9 ** 2 v9 *= -1 v9 *= v7 v9 += v8 return v0(int(v9), lower=30, upper=100)
[ { "name": "v0", "input_types": [ "SLTT", "Optional[SLTT]", "Optional[SLTT]" ], "output_type": "SLTT", "code": "def v0(v1: SLTT, v2: Optional[SLTT]=None, v3: Optional[SLTT]=None) -> SLTT:\n if v2 is None and v3 is None:\n raise ValueError(\"Of the parameters 'lower' an...
[]
[]
12
# -*- coding: utf-8 -*- """Standard utility functions used throughout AlphaGradient""" # Standard Imports from __future__ import annotations from abc import ABC, abstractmethod import builtins from datetime import ( date, datetime, time, timedelta, ) import math from pathlib import Path # Third Party...
null
v11
[ "v0" ]
dict[str, float]
def v11(v12: v0) -> dict[str, float]: v13 = ['year', 'month', 'day'] v14 = ['hour', 'minute', 'second', 'microsecond'] v15 = [] if isinstance(v12, str): v12 = v1(v12) if isinstance(v12, datetime): v15 = v13 + v14 elif isinstance(v12, time): v15 = v14 elif isinstance(v...
[ { "name": "v1", "input_types": [ "str" ], "output_type": "time", "code": "def v1(v2: str) -> time:\n try:\n return read_twelve_hour_timestring(v2)\n except (TypeError, ValueError) as e:\n return time.fromisoformat(v2)", "dependencies": [ "v3" ] }, { ...
[ "datetime" ]
[ "from datetime import date, datetime, time, timedelta" ]
18
# -*- coding: utf-8 -*- """Standard utility functions used throughout AlphaGradient""" # Standard Imports from __future__ import annotations from abc import ABC, abstractmethod import builtins from datetime import ( date, datetime, time, timedelta, ) import math from pathlib import Path # Third Party...
[ "v0 = Union[DatetimeLike, time]" ]
v0
[ "Iterable", "int" ]
Generator
def v0(v1: Iterable, v2: int=100) -> Generator: v1 = list(v1) v3 = len(v1) for v4 in range(math.ceil(v3 / v2)): v5 = v4 * v2 v6 = v5 + v2 v6 = v6 if v6 < v3 else v3 yield v1[v5:v6]
[]
[ "math" ]
[ "import math" ]
8
# -*- coding: utf-8 -*- """Standard utility functions used throughout AlphaGradient""" # Standard Imports from __future__ import annotations from abc import ABC, abstractmethod import builtins from datetime import ( date, datetime, time, timedelta, ) import math from pathlib import Path # Third Party...
null
v17
[ "v0" ]
time
def v17(v18: v0) -> time: if isinstance(v18, (time, str)): return v15(v18) return v13(v18).time()
[ { "name": "v3", "input_types": [ "str" ], "output_type": "time", "code": "def v3(v4: str) -> time:\n try:\n return read_twelve_hour_timestring(v4)\n except (TypeError, ValueError) as e:\n return time.fromisoformat(v4)", "dependencies": [ "v5" ] }, { ...
[ "datetime", "numpy", "pandas" ]
[ "from datetime import date, datetime, time, timedelta", "import numpy as np", "import pandas as pd" ]
4
# -*- coding: utf-8 -*- """Standard utility functions used throughout AlphaGradient""" # Standard Imports from __future__ import annotations from abc import ABC, abstractmethod import builtins from datetime import ( date, datetime, time, timedelta, ) import math from pathlib import Path # Third Party...
[ "v0 = Union[DatetimeLike, time]", "v1 = Union[pd.Timestamp, np.datetime64, date, datetime, str]", "v2 = Union[time, str]" ]
v3
[ "v0" ]
str
def v3(v4: v0) -> str: v5 = {0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thursday', 4: 'Friday', 5: 'Saturday', 6: 'Sunday'} return v5[v1(v4).weekday()]
[ { "name": "v1", "input_types": [ "v0" ], "output_type": "datetime", "code": "def v1(v2: v0) -> datetime:\n if isinstance(v2, datetime):\n return v2\n elif isinstance(v2, pd.Timestamp):\n return v2.to_pydatetime()\n elif isinstance(v2, np.datetime64):\n return ...
[ "datetime", "numpy", "pandas" ]
[ "from datetime import date, datetime, time, timedelta", "import numpy as np", "import pandas as pd" ]
3
# -*- coding: utf-8 -*- """Standard utility functions used throughout AlphaGradient""" # Standard Imports from __future__ import annotations from abc import ABC, abstractmethod import builtins from datetime import ( date, datetime, time, timedelta, ) import math from pathlib import Path # Third Party...
[ "v0 = Union[pd.Timestamp, np.datetime64, date, datetime, str]" ]
v25
[ "v1", "Literal['after', 'before', 'both']" ]
datetime
def v25(v26: v1, v27: Literal['after', 'before', 'both']='after') -> datetime: v26 = v23(v26) v26 = v19(v26, '4:00 PM') if v26.weekday() > 4: if v27 == 'after': v28 = 7 - v26.weekday() v26 += timedelta(days=v28) elif v27 == 'before': v28 = v26.weekday() - ...
[ { "name": "v2", "input_types": [ "v0" ], "output_type": "dict[str, float]", "code": "def v2(v3: v0) -> dict[str, float]:\n v4 = ['year', 'month', 'day']\n v5 = ['hour', 'minute', 'second', 'microsecond']\n v6 = []\n if isinstance(v3, str):\n v3 = read_timestring(v3)\n ...
[ "datetime", "numpy", "pandas" ]
[ "from datetime import date, datetime, time, timedelta", "import numpy as np", "import pandas as pd" ]
18
# -*- coding: utf-8 -*- """Standard utility functions used throughout AlphaGradient""" # Standard Imports from __future__ import annotations from abc import ABC, abstractmethod import builtins from datetime import ( date, datetime, time, timedelta, ) import math from pathlib import Path # Third Party...
[ "v0 = Union[DatetimeLike, time]", "v1 = Union[pd.Timestamp, np.datetime64, date, datetime, str]" ]
v0
[ "Any", "list[int]" ]
None
def v0(v1: Any, v2: list[int]=[0]) -> None: print('\r' + ' ' * v2[0], end='\r', flush=True) print(v1, end='', flush=True) v2[0] = len(str(v1))
[]
[]
[]
4
# -*- coding: utf-8 -*- """Standard utility functions used throughout AlphaGradient""" # Standard Imports from __future__ import annotations from abc import ABC, abstractmethod import builtins from datetime import ( date, datetime, time, timedelta, ) import math from pathlib import Path # Third Party...
null