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
[]
float
def v0() -> float: torch.cuda.synchronize() return timeit.default_timer()
[]
[ "timeit", "torch" ]
[ "import timeit", "import torch", "from torch.utils.benchmark.utils import common, cpp_jit", "from torch.utils.benchmark.utils._stubs import TimerClass, TimeitModuleType", "from torch.utils.benchmark.utils.valgrind_wrapper import timer_interface as valgrind_timer_interface" ]
3
"""Timer class based on the timeit.Timer class, but torch aware.""" import enum import timeit import textwrap from typing import Any, Callable, Dict, List, NoReturn, Optional, Type, Union import numpy as np import torch from torch.utils.benchmark.utils import common, cpp_jit from torch.utils.benchmark.utils._stubs imp...
null
v0
[ "int" ]
common.Measurement
def v0(self, v1: int=1000000) -> common.Measurement: with common.set_torch_threads(self._task_spec.num_threads): self._timer.timeit(number=max(int(v1 // 100), 1)) return common.Measurement(number_per_run=v1, raw_times=[self._timer.timeit(number=v1)], task_spec=self._task_spec)
[]
[ "torch" ]
[ "import torch", "from torch.utils.benchmark.utils import common, cpp_jit", "from torch.utils.benchmark.utils._stubs import TimerClass, TimeitModuleType", "from torch.utils.benchmark.utils.valgrind_wrapper import timer_interface as valgrind_timer_interface" ]
4
"""Timer class based on the timeit.Timer class, but torch aware.""" import enum import timeit import textwrap from typing import Any, Callable, Dict, List, NoReturn, Optional, Type, Union import numpy as np import torch from torch.utils.benchmark.utils import common, cpp_jit from torch.utils.benchmark.utils._stubs imp...
null
v0
[ "int", "Callable[[], float]", "Callable[[List[float]], bool]", "float", "Optional[float]", "Optional[Callable[[int, float], NoReturn]]" ]
List[float]
def v0(self, v1: int, v2: Callable[[], float], v3: Callable[[List[float]], bool], v4: float, v5: Optional[float]=None, v6: Optional[Callable[[int, float], NoReturn]]=None) -> List[float]: v7 = 0.0 v8 = False v9: List[float] = [] with common.set_torch_threads(self._task_spec.num_threads): while v...
[]
[ "torch" ]
[ "import torch", "from torch.utils.benchmark.utils import common, cpp_jit", "from torch.utils.benchmark.utils._stubs import TimerClass, TimeitModuleType", "from torch.utils.benchmark.utils.valgrind_wrapper import timer_interface as valgrind_timer_interface" ]
15
"""Timer class based on the timeit.Timer class, but torch aware.""" import enum import timeit import textwrap from typing import Any, Callable, Dict, List, NoReturn, Optional, Type, Union import numpy as np import torch from torch.utils.benchmark.utils import common, cpp_jit from torch.utils.benchmark.utils._stubs imp...
null
v0
[ "float" ]
int
def v0(self, v1: float) -> int: with common.set_torch_threads(self._task_spec.num_threads): v2 = np.median([self._timer.timeit(0) for v3 in range(5)]) v4 = 1 while True: v5 = self._timer.timeit(v4) v6 = v2 / v5 if v6 <= 0.0001 and v5 >= v1 / 1000: ...
[]
[ "numpy", "torch" ]
[ "import numpy as np", "import torch", "from torch.utils.benchmark.utils import common, cpp_jit", "from torch.utils.benchmark.utils._stubs import TimerClass, TimeitModuleType", "from torch.utils.benchmark.utils.valgrind_wrapper import timer_interface as valgrind_timer_interface" ]
13
"""Timer class based on the timeit.Timer class, but torch aware.""" import enum import timeit import textwrap from typing import Any, Callable, Dict, List, NoReturn, Optional, Type, Union import numpy as np import torch from torch.utils.benchmark.utils import common, cpp_jit from torch.utils.benchmark.utils._stubs imp...
null
v3
[ "float", "float", "float", "Optional[Callable[[int, float], NoReturn]]" ]
common.Measurement
def v3(self, v4: float=0.1, *, v5: float=0.01, v6: float=10.0, v7: Optional[Callable[[int, float], NoReturn]]=None) -> common.Measurement: v8 = self._estimate_block_size(min_run_time=0.05) def v9() -> float: return self._timer.timeit(v8) def v10(v11: List[float]) -> bool: if len(v11) > 3: ...
[ { "name": "v0", "input_types": [ "List[float]" ], "output_type": "bool", "code": "def v0(v1: List[float]) -> bool:\n return True", "dependencies": [] }, { "name": "v2", "input_types": [], "output_type": "float", "code": "def v2() -> float:\n return self._timer...
[ "torch" ]
[ "import torch", "from torch.utils.benchmark.utils import common, cpp_jit", "from torch.utils.benchmark.utils._stubs import TimerClass, TimeitModuleType", "from torch.utils.benchmark.utils.valgrind_wrapper import timer_interface as valgrind_timer_interface" ]
12
"""Timer class based on the timeit.Timer class, but torch aware.""" import enum import timeit import textwrap from typing import Any, Callable, Dict, List, NoReturn, Optional, Type, Union import numpy as np import torch from torch.utils.benchmark.utils import common, cpp_jit from torch.utils.benchmark.utils._stubs imp...
null
v3
[ "Optional[Callable[[int, float], NoReturn]]", "float" ]
common.Measurement
def v3(self, v4: Optional[Callable[[int, float], NoReturn]]=None, v5: float=0.2) -> common.Measurement: v6 = self._estimate_block_size(v5) def v7() -> float: return self._timer.timeit(v6) def v8(v9: List[float]) -> bool: return True v10 = self._threaded_measurement_loop(v6, v7, v8, min...
[ { "name": "v0", "input_types": [ "List[float]" ], "output_type": "bool", "code": "def v0(v1: List[float]) -> bool:\n return True", "dependencies": [] }, { "name": "v2", "input_types": [], "output_type": "float", "code": "def v2() -> float:\n return self._timer...
[ "torch" ]
[ "import torch", "from torch.utils.benchmark.utils import common, cpp_jit", "from torch.utils.benchmark.utils._stubs import TimerClass, TimeitModuleType", "from torch.utils.benchmark.utils.valgrind_wrapper import timer_interface as valgrind_timer_interface" ]
10
"""Timer class based on the timeit.Timer class, but torch aware.""" import enum import timeit import textwrap from typing import Any, Callable, Dict, List, NoReturn, Optional, Type, Union import numpy as np import torch from torch.utils.benchmark.utils import common, cpp_jit from torch.utils.benchmark.utils._stubs imp...
null
v0
[]
None
def v0(self) -> None: if self._cfg_path and os.path.isfile(self._cfg_path): if self.run_as_user: subprocess.call(['sudo', 'rm', self._cfg_path], close_fds=True) else: os.remove(self._cfg_path) try: self._error_file.close() except FileNotFoundError: pas...
[]
[ "os", "subprocess" ]
[ "import os", "import subprocess" ]
10
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
null
v0
[ "torch.Tensor", "int", "bool" ]
WeightedRandomSampler
def v0(v1: torch.Tensor, v2: int=10, v3: bool=False) -> WeightedRandomSampler: v4 = pd.qcut if v3 else pd.cut v5 = torch.LongTensor(v4(v1.tolist(), v2, labels=False, duplicates='drop')) v6 = torch.LongTensor([(v5 == t).sum() for v7 in torch.arange(v2)]) v8 = 1.0 / v6.float() v9 = torch.zeros_like(v1...
[]
[ "pandas", "torch" ]
[ "import pandas as pd", "import torch", "from torch import optim", "from torch.utils.data import DataLoader, Subset, TensorDataset, WeightedRandomSampler" ]
9
"""Train (basic) densely-connected oracle.""" import os import time import multiprocessing as mp import pandas as pd import torch from torch import optim from torch.utils.data import DataLoader, Subset, TensorDataset, WeightedRandomSampler from profit.dataset.splitters import split_method_dict from profit.models.to...
null
v3
[ "str", "v0" ]
None
def v3(v4: str, v5: v0=os.environ) -> None: if not v1(v5): return v6 = json.loads(v5['VCAP_SERVICES']) for v7 in v6.get('user-provided', []): if v7['name'] == v4: for (v8, v9) in v7['credentials'].items(): v5[v8] = v9
[ { "name": "v1", "input_types": [ "v0" ], "output_type": "bool", "code": "def v1(v2: v0=os.environ) -> bool:\n return 'VCAP_SERVICES' in v2", "dependencies": [] } ]
[ "json" ]
[ "import json" ]
8
import os import json Environ = os._Environ def is_on_cloudfoundry(env: Environ=os.environ) -> bool: return 'VCAP_SERVICES' in env def load_cups_from_vcap_services(name: str, env: Environ=os.environ) -> None: ''' Detects if VCAP_SERVICES exists in the environment; if so, parses it and imports all t...
[ "v0 = os._Environ" ]
v3
[ "str", "str", "v0" ]
str
def v3(v4: str, v5: str, v6: v0=os.environ) -> str: if not v1(v6): return v7 = json.loads(v6['VCAP_SERVICES']) v6['DATABASE_URL'] = v7[v5][0]['credentials']['uri']
[ { "name": "v1", "input_types": [ "v0" ], "output_type": "bool", "code": "def v1(v2: v0=os.environ) -> bool:\n return 'VCAP_SERVICES' in v2", "dependencies": [] } ]
[ "json" ]
[ "import json" ]
5
import os import json Environ = os._Environ def is_on_cloudfoundry(env: Environ=os.environ) -> bool: return 'VCAP_SERVICES' in env def load_cups_from_vcap_services(name: str, env: Environ=os.environ) -> None: ''' Detects if VCAP_SERVICES exists in the environment; if so, parses it and imports all t...
[ "v0 = os._Environ" ]
v0
[ "str" ]
Any
def v0(v1: str): v1 = f'''{os.getenv('SHELL')} -c "{v1}"''' v2 = subprocess.Popen(v1, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) v3 = '' if v2.stdout is not None: v3 = ''.join([line.decode('utf-8') for v4 in iter(v2.stdout.readline, b'')]) v2.stdout.close() v5 = v2...
[]
[ "os", "subprocess" ]
[ "import os", "import subprocess" ]
10
""" Input: tsv file in the form Input Video filename | topic | subtopic | title greek | title english | start time | end time | delete segments input.mp4 | 1 | 1 | έξοδος | output | 00:10:05 | 00:30:10 | 00:11:15-00:12:30,00:20:35-00:22:10 """ import os import subprocess import sys...
null
v0
[ "str" ]
Any
def v0(self, v1: str): v2 = self.layer.edge_color_mode try: self.layer.edge_color = v1 self.layer.edge_color_mode = v2 except TypeError: self._on_edge_color_mode_change() raise
[]
[]
[]
8
import numpy as np from qtpy.QtCore import Qt from qtpy.QtWidgets import QComboBox, QDoubleSpinBox, QLabel from ...layers.utils._color_manager_constants import ColorMode from ...utils.translations import trans from ..utils import qt_signals_blocked from ..widgets.qt_color_swatch import QColorSwatchEdit from .qt_layer_...
null
v0
[ "str" ]
Any
def v0(self, v1: str): v2 = self.layer.edge_color_mode with self.layer.events.edge_color_mode.blocker(): try: self.layer.edge_color_mode = v1 self._update_edge_color_gui(v1) except ValueError: self.layer.edge_color_mode = v2 raise
[]
[]
[]
9
import numpy as np from qtpy.QtCore import Qt from qtpy.QtWidgets import QComboBox, QDoubleSpinBox, QLabel from ...layers.utils._color_manager_constants import ColorMode from ...utils.translations import trans from ..utils import qt_signals_blocked from ..widgets.qt_color_swatch import QColorSwatchEdit from .qt_layer_...
null
v0
[ "str" ]
Any
def v0(self, v1: str): if v1 in ('cycle', 'colormap'): self.edgeColorEdit.setHidden(True) self.edge_color_label.setHidden(True) self.color_prop_box.setHidden(False) self.edge_prop_label.setHidden(False) elif v1 == 'direct': self.edgeColorEdit.setHidden(False) self...
[]
[]
[]
11
import numpy as np from qtpy.QtCore import Qt from qtpy.QtWidgets import QComboBox, QDoubleSpinBox, QLabel from ...layers.utils._color_manager_constants import ColorMode from ...utils.translations import trans from ..utils import qt_signals_blocked from ..widgets.qt_color_swatch import QColorSwatchEdit from .qt_layer_...
null
v0
[]
None
def v0(self) -> None: self.strategy = None self.bars = {} self.datetime = None self.limit_order_count = 0 self.limit_orders.clear() self.active_limit_orders.clear() self.trade_count = 0 self.trades.clear() self.logs.clear() self.daily_results.clear() self.daily_df = None
[]
[]
[]
12
from collections import defaultdict from datetime import date, datetime, timedelta from typing import Dict, List, Set, Tuple from functools import lru_cache from copy import copy import traceback import numpy as np import plotly.graph_objects as go from plotly.subplots import make_subplots from pandas import DataFrame...
null
v0
[]
None
def v0(self) -> None: self.strategy.on_init() v1 = list(self.dts) v1.sort() v2 = 0 v3 = 0 for (v3, v4) in enumerate(v1): if self.datetime and v4.day != self.datetime.day: v2 += 1 if v2 >= self.days: break try: self.new_bars(v4) ...
[]
[ "traceback" ]
[ "import traceback" ]
30
from collections import defaultdict from datetime import date, datetime, timedelta from typing import Dict, List, Set, Tuple from functools import lru_cache from copy import copy import traceback import numpy as np import plotly.graph_objects as go from plotly.subplots import make_subplots from pandas import DataFrame...
null
v0
[]
None
def v0(self) -> None: self.output('开始计算逐日盯市盈亏') if not self.trades: self.output('成交记录为空,无法计算') return for v1 in self.trades.values(): v2 = v1.datetime.date() v3 = self.daily_results[v2] v3.add_trade(v1) v4 = {} v5 = {} for v3 in self.daily_results.values()...
[]
[ "collections", "pandas" ]
[ "from collections import defaultdict", "from pandas import DataFrame" ]
24
from collections import defaultdict from datetime import date, datetime, timedelta from typing import Dict, List, Set, Tuple from functools import lru_cache from copy import copy import traceback import numpy as np import plotly.graph_objects as go from plotly.subplots import make_subplots from pandas import DataFrame...
null
v0
[ "DataFrame", "Any" ]
Any
def v0(self, v1: DataFrame=None, v2=True): self.output('开始计算策略统计指标') if v1 is None: v1 = self.daily_df if v1 is None: v3 = '' v4 = '' v5 = 0 v6 = 0 v7 = 0 v8 = 0 v9 = 0 v10 = 0 v11 = 0 v12 = 0 v13 = 0 v14...
[]
[ "datetime", "numpy" ]
[ "from datetime import date, datetime, timedelta", "import numpy as np" ]
107
from collections import defaultdict from datetime import date, datetime, timedelta from typing import Callable from itertools import product from functools import lru_cache from time import time import multiprocessing import random import traceback from platform import system import numpy as np from pandas import Data...
null
v0
[ "DataFrame" ]
Any
def v0(self, v1: DataFrame=None): if v1 is None: v1 = self.daily_df if v1 is None: return v2 = make_subplots(rows=4, cols=1, subplot_titles=['Balance', 'Drawdown', 'Daily Pnl', 'Pnl Distribution'], vertical_spacing=0.06) v3 = go.Scatter(x=v1.index, y=v1['balance'], mode='lines', name='Ba...
[]
[ "platform", "plotly" ]
[ "from platform import system", "import plotly.graph_objects as go", "from plotly.subplots import make_subplots" ]
19
from collections import defaultdict from datetime import date, datetime, timedelta from typing import Callable from itertools import product from functools import lru_cache from time import time import multiprocessing import random import traceback from platform import system import numpy as np from pandas import Data...
null
v0
[ "Dict[str, float]", "Dict[str, float]", "Dict[str, float]", "Dict[str, float]", "Dict[str, float]" ]
None
def v0(self, v1: Dict[str, float], v2: Dict[str, float], v3: Dict[str, float], v4: Dict[str, float], v5: Dict[str, float]) -> None: self.pre_closes = v1 for (v6, v7) in self.contract_results.items(): v7.calculate_pnl(v1.get(v6, 0), v2.get(v6, 0), v3[v6], v4[v6], v5[v6]) self.trade_count += v7.tr...
[]
[]
[]
13
from collections import defaultdict from datetime import date, datetime, timedelta from typing import Dict, List, Set, Tuple from functools import lru_cache from copy import copy import traceback import numpy as np import plotly.graph_objects as go from plotly.subplots import make_subplots from pandas import DataFrame...
null
v0
[ "Dict[str, float]" ]
None
def v0(self, v1: Dict[str, float]) -> None: self.close_prices = v1 for (v2, v3) in v1.items(): v4 = self.contract_results.get(v2, None) if v4: v4.update_close_price(v3)
[]
[]
[]
6
from collections import defaultdict from datetime import date, datetime, timedelta from typing import Dict, List, Set, Tuple from functools import lru_cache from copy import copy import traceback import numpy as np import plotly.graph_objects as go from plotly.subplots import make_subplots from pandas import DataFrame...
null
v0
[ "Any", "int", "bool" ]
Any
def v0(v1, v2: int, v3: bool=False): v4 = v1.ne(v2).int() return (torch.cumsum(v4, dim=1).type_as(v4) * v4).long() + v2
[]
[ "torch" ]
[ "import torch", "import torch.nn.functional as F", "from torch import Tensor" ]
3
# 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 contextlib import copy import importlib.util import logging import math import os import sys import warnings from collections import de...
null
v0
[ "Any", "Any", "bool", "bool" ]
Any
def v0(v1, v2, v3: bool=False, v4: bool=False): assert v3 ^ v4 v5 = v1.eq(v2) if not v5.any(): return v1 if v4 and (not v5[:, 0].any()): return v1 if v3 and (not v5[:, -1].any()): return v1 v6 = v1.size(1) v7 = torch.empty(0).long() if v6 > 0: torch.arange...
[]
[ "torch" ]
[ "import torch", "import torch.nn.functional as F", "from torch import Tensor" ]
20
# 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 contextlib import copy import importlib.util import logging import math import os import sys import warnings from collections import de...
null
v0
[ "Any", "int", "bool" ]
Any
def v0(v1, v2: int, v3: bool=False): if v3: return F.log_softmax(v1.float(), dim=v2) else: return F.log_softmax(v1, dim=v2, dtype=torch.float32)
[]
[ "torch" ]
[ "import torch", "import torch.nn.functional as F", "from torch import Tensor" ]
5
# 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 contextlib import copy import importlib.util import logging import math import os import sys import warnings from collections import de...
null
v0
[ "'AtomicInput'", "'TaskConfig'" ]
'AtomicResult'
def v0(self, v1: 'AtomicInput', v2: 'TaskConfig') -> 'AtomicResult': self.found(raise_error=True) v3 = self.build_input(v1, v2) (v4, v5) = self.execute(v3) if v4: v5['outfiles']['stdout'] = v5['stdout'] v5['outfiles']['stderr'] = v5['stderr'] return self.parse_output(v5['outfiles...
[]
[]
[]
8
""" Calls the Turbomole executable. """ import os import re from decimal import Decimal from pathlib import Path from typing import Any, Dict, Optional, Tuple from qcelemental.models import AtomicResult, Provenance, BasisSet from qcelemental.util import safe_version, which from ...exceptions import InputError from .....
null
v0
[ "str" ]
Tuple[List[str], Dict[Tuple[str, str], str]]
def v0(v1: str) -> Tuple[List[str], Dict[Tuple[str, str], str]]: v2 = v1.splitlines() v3 = list(v2[0].strip()) v4 = {} for v5 in v2[2:]: if (v6 := v5.strip()): (v7, v8) = v6.split(' -> ', 1) v4[v7[0], v7[1]] = v8 return (v3, v4)
[]
[]
[]
9
import collections import functools from typing import Dict, List, Tuple, Counter from tool.runners.python import SubmissionPy def parse(s: str) -> Tuple[List[str], Dict[Tuple[str, str], str]]: lines = s.splitlines() initial = list(lines[0].strip()) mapping = {} for line in lines[2:]: if strip...
null
v9
[ "str" ]
int
def v9(self, v10: str) -> int: self.dfs.cache_clear() (v11, self.mapping) = v0(v10) v12 = collections.Counter(v11) for (v13, v14) in zip(v11, v11[1:]): v12 += self.dfs(v13, v14, 0) return max(v12.values()) - min(v12.values())
[ { "name": "v0", "input_types": [ "str" ], "output_type": "Tuple[List[str], Dict[Tuple[str, str], str]]", "code": "def v0(v1: str) -> Tuple[List[str], Dict[Tuple[str, str], str]]:\n v2 = v1.splitlines()\n v3 = list(v2[0].strip())\n v4 = {}\n for v5 in v2[2:]:\n if (v6 := ...
[ "collections" ]
[ "import collections" ]
7
import collections import functools from typing import Dict, List, Tuple, Counter from tool.runners.python import SubmissionPy def parse(s: str) -> Tuple[List[str], Dict[Tuple[str, str], str]]: lines = s.splitlines() initial = list(lines[0].strip()) mapping = {} for line in lines[2:]: if strip...
null
v0
[ "MutableMapping[str, Any]" ]
Any
def v0(self, v1: MutableMapping[str, Any]): if not self._enabled: return if 'pool_size' not in v1: v1['pool_size'] = 0 if 'max_overflow' not in v1: v1['max_overflow'] = -1
[]
[]
[]
7
import abc import enum import itertools import logging import uuid from copy import deepcopy from typing import Any, Dict, List, MutableMapping, Optional, Union from ruamel.yaml import YAML from ruamel.yaml.comments import CommentedMap from ruamel.yaml.compat import StringIO import great_expectations.exceptions as ge...
null
v0
[ "str", "str" ]
List[str]
def v0(v1: str, v2: str='master') -> List[str]: v3 = os.getcwd() with tempfile.TemporaryDirectory() as v4: os.chdir(v4) v5 = ['git', 'clone', '--filter=tree:0', '--no-checkout', f'--branch={v2}', v1, v4] v6 = ['git', 'log', '-n', '10', '--pretty=format:%H'] subprocess.check_outpu...
[]
[ "os", "subprocess", "sys", "tempfile" ]
[ "import os", "import subprocess", "import sys", "import tempfile" ]
10
""" This is an end to end release test automation script used to kick off periodic release tests, running on Anyscale. The tool leverages app configs and compute templates. Calling this script will run a single release test. Example: python e2e.py --test-config ~/ray/release/xgboost_tests/xgboost_tests.yaml --test-...
null
v0
[ "Optional[str]" ]
Any
def v0(v1: Optional[str]=None): if not v1: v2 = 'python -c \'import ray; print("No commit sanity check available, but this is the Ray wheel commit:", ray.__commit__)\'' else: v2 = f"""python -c 'import ray; assert ray.__commit__ == "{v1}", ray.__commit__'""" os.environ['RAY_WHEELS_SANITY_CHE...
[]
[ "os" ]
[ "import os" ]
6
""" This is an end to end release test automation script used to kick off periodic release tests, running on Anyscale. The tool leverages app configs and compute templates. Calling this script will run a single release test. Example: python e2e.py --test-config ~/ray/release/xgboost_tests/xgboost_tests.yaml --test-...
null
v0
[ "Dict[Any, Any]" ]
str
def v0(v1: Dict[Any, Any]) -> str: v2 = json.dumps(v1, sort_keys=True, ensure_ascii=True) v3 = hashlib.sha256() v3.update(v2.encode()) return v3.hexdigest()
[]
[ "hashlib", "json" ]
[ "import hashlib", "import json" ]
5
""" This is an end to end release test automation script used to kick off periodic release tests, running on Anyscale. The tool leverages app configs and compute templates. Calling this script will run a single release test. Example: python e2e.py --test-config ~/ray/release/xgboost_tests/xgboost_tests.yaml --test-...
null
v0
[ "Dict[Any, Any]" ]
Any
def v0(v1: Dict[Any, Any]): os.environ.update(v1.get('env_vars', {})) v2 = v1['python']['pip_packages'] for v3 in v2: subprocess.check_output(['pip', 'install', '-U', v3], text=True)
[]
[ "os", "subprocess" ]
[ "import os", "import subprocess" ]
5
""" This is an end to end release test automation script used to kick off periodic release tests, running on Anyscale. The tool leverages app configs and compute templates. Calling this script will run a single release test. Example: python e2e.py --test-config ~/ray/release/xgboost_tests/xgboost_tests.yaml --test-...
null
v0
[]
Generator
def v0(self) -> Generator: while True: v1 = self.line_chunks() yield v1
[]
[]
[]
4
from __future__ import annotations from typing import Generator, NoReturn class StdReader: def __init__( self, ) -> NoReturn: import sys self.buf = sys.stdin.buffer self.lines = self.async_readlines() self.chunks: Generator def async_readlines( self, ...
null
v0
[]
typing.Iterator[bytes]
def v0(self) -> typing.Iterator[bytes]: while 1: v1 = self.__buf.readline() for v2 in v1.split(): yield v2
[]
[]
[]
5
import typing class ReadStdin: def __call__( self, ) -> bytes: return next(self.__chunks) def __init__( self, ) -> typing.NoReturn: import sys self.__buf = ( sys.stdin.buffer ) self.__chunks = ( self.__read_chunks() ) def int( self, ) -> int: re...
null
v0
[]
v0
def v0(self) -> v0: v1 = self() return v1.decode()
[]
[]
[]
3
from __future__ import annotations from typing import Generator, NoReturn class StdReader: def __init__( self, ) -> NoReturn: import sys self.buf = sys.stdin.buffer self.lines = self.async_readlines() self.chunks: Generator def async_readlines( self, ...
null
v0
[ "str" ]
Any
async def v0(self, v1: str): v2 = {'cmd': 'auth', 'api_key': v1} await self._deliver(json.dumps(v2)) self._authed = True self._api_key = v1
[]
[ "json" ]
[ "import json" ]
5
import asyncio import json import logging from datetime import datetime from typing import Any, Dict, Iterable, List, Optional, Set, Union import httpx import websockets from websockets import exceptions logger = logging.getLogger("yufuquantsdk") class WebsocketAPIClient: def __init__(self, uri: str, ws: websoc...
null
v0
[ "Iterable[str]" ]
Any
async def v0(self, v1: Iterable[str]): if not isinstance(v1, set): v1 = set(v1) v2 = {'cmd': 'unsub', 'topics': list(v1)} await self._deliver(json.dumps(v2)) self._sub_topics = self._sub_topics - v1
[]
[ "json" ]
[ "import json" ]
6
import asyncio import json import logging from datetime import datetime from typing import Any, Dict, Iterable, List, Optional, Set, Union import httpx import websockets from websockets import exceptions logger = logging.getLogger("yufuquantsdk") class WebsocketAPIClient: def __init__(self, uri: str, ws: websoc...
null
v0
[ "str", "str" ]
Any
async def v0(self, v1: str, v2: str='info'): v3 = {'text': v1, 'level': v2, 'timestamp': int(datetime.now().timestamp()) * 1000} v4 = {'category': 'robotLog', 'data': v3} await self._broadcast(v4)
[]
[ "datetime" ]
[ "from datetime import datetime" ]
4
import asyncio import json import logging from datetime import datetime from typing import Any, Dict, Iterable, List, Optional, Set, Union import httpx import websockets from websockets import exceptions logger = logging.getLogger("yufuquantsdk") class WebsocketAPIClient: def __init__(self, uri: str, ws: websoc...
null
v0
[ "Dict" ]
Any
async def v0(self, v1: Dict): v2 = {'cmd': 'broadcast', 'message': v1} await self._deliver(json.dumps(v2))
[]
[ "json" ]
[ "import json" ]
3
import asyncio import json import logging from datetime import datetime from typing import Any, Dict, Iterable, List, Optional, Set, Union import httpx import websockets from websockets import exceptions logger = logging.getLogger("yufuquantsdk") class WebsocketAPIClient: def __init__(self, uri: str, ws: websoc...
null
v0
[ "Any" ]
bool
def v0(v1: Any) -> bool: if isinstance(v1, torch.Size): return True elif isinstance(v1, tuple): return True elif isinstance(v1, list): return True else: raise TypeError('Input sizes for inputs are required to be a List, tuple or torch.Size or a Dict of three sizes (min, o...
[]
[ "torch" ]
[ "import torch" ]
9
from typing import List, Dict, Any import torch import trtorch._C from trtorch import _types def _supported_input_size_type(input_size: Any) -> bool: if isinstance(input_size, torch.Size): return True elif isinstance(input_size, tuple): return True elif isinstance(input_size, list): ...
null
v15
[ "Dict[str, Any]" ]
Any
def v15(v16: Dict[str, Any]): v17 = v0(v16) v18 = torch.classes.tensorrt.CompileSpec() for v19 in v17.input_ranges: v20 = torch.classes.tensorrt.InputRange() v20.set_min(v19.min) v20.set_opt(v19.opt) v20.set_max(v19.max) v18.append_input_range(v20) v18.set_op_prec...
[ { "name": "v0", "input_types": [ "Dict[str, Any]" ], "output_type": "trtorch._C.CompileSpec", "code": "def v0(v1: Dict[str, Any]) -> trtorch._C.CompileSpec:\n v2 = trtorch._C.CompileSpec()\n if 'input_shapes' not in v1:\n raise KeyError('Input shapes for inputs are required as...
[ "torch" ]
[ "import torch" ]
22
from typing import List, Dict, Any import torch import trtorch._C from trtorch import _types def _supported_input_size_type(input_size: Any) -> bool: if isinstance(input_size, torch.Size): return True elif isinstance(input_size, tuple): return True elif isinstance(input_size, list): ...
null
v9
[ "str" ]
Optional[v0]
def v9(self, v10: str) -> Optional[v0]: for v11 in self.oneOf: if v11.name == v10: return v11 return None
[]
[]
[]
5
from dataclasses import dataclass from dataclasses import field from typing import Any from typing import Callable from typing import Mapping from typing import Optional from typing import Sequence from typing import Type from svarog import forge from svarog import register_forge from svarog.types import Forge JSONMa...
[ "@dataclass\nclass v0:\n v1: str\n v2: Optional[JSONSchema] = None\n v3: Optional[str] = None\n v4: Optional[MessageAck] = None\n\n @staticmethod\n def v5(v6: Type['Message'], v7: JSONMapping, v8: Forge) -> 'Message':\n return v6(name=v8(v6.__annotations__['name'], v7['name']), payload=v8(v...
v0
[ "str" ]
Any
def v0(v1: str): v2 = {} v3 = v1.split(' ') v4 = '' v5 = '' v6 = '"' for v7 in v3: if '=' in v7: (v8, v9) = v7.split('=') if v9[0] in ('"', "'"): v6 = v9[0] if v9.endswith(v6): v2[v8] = v9[1:-1] else: ...
[]
[]
[]
23
#!/usr/bin/env python3 # XML API, for dealing with XML strings # -*- coding: utf-8 -*- __all__ = ['parseargs', 'collect'] '<users>\n\t<user>\n\t\t<id>1</id>\n\t\t<name>Fred</name>\n\t\t<salary>500000</salary>\n\t</user>\n\t<user>\n\t\t<id>1</id>\n\t\t<name>ScienceCat</name>\n\t\t<salary>500000</salary>\n\t</user>\n\t...
null
v0
[ "Any" ]
int
def v0(self, v1) -> int: v2 = sum([p['alloc_point'] for v3 in self.dapp_pools_infos(v1)]) return v2
[]
[]
[]
3
from abc import abstractmethod from .apr_fetcher import APRFetcher from typing import Dict, List, Union, Any from .dapp_apr_fetcher import DappAPRFetcher from .utils.utils import ( calculate_lp_token_price, get_block_average_time, get_token_price_from_dexs, open_contract, usdt_address, platform_...
null
v0
[ "str", "str", "str" ]
str
def v0(self, v1: str, v2: str, v3: str) -> str: v4 = re.compile(f'\\b{re.escape(v2)}\\b') return v4.sub(v3, v1)
[]
[ "re" ]
[ "import re" ]
3
import copy import re from collections import defaultdict from typing import List, Dict from .substitution_augmenter import SubstitutionAugmenter from ..actions import Chemical from ..utils import extract_chemicals from paragraph2actions.misc import TextWithActions class CompoundNameAugmenter(SubstitutionAugmenter):...
null
v0
[]
Dict
def v0(self) -> Dict: v1 = {} if hasattr(self, 'cell_id') and self.cell_id is not None: v1['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: v1['location'] = self.location._to_dict() if hasattr(self, 'text') and self.text is not None: v1['text'...
[]
[]
[]
9
# coding: utf-8 # (C) Copyright IBM Corp. 2019, 2020. # # 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 la...
null
v0
[ "str", "bool", "bool" ]
List[dict]
def v0(self, v1: str, v2: bool, v3: bool=False) -> List[dict]: v4: List[str] = asyncio.run(self._get_comments(v1, v2)) for v5 in v4: if not re.match('<[^>]*>', v5.replace('<!--', '').replace('-->', '')) or v3: for v6 in self.might_sensitive_words: if v6.replace('O: ', '').low...
[]
[ "asyncio", "re" ]
[ "import parsel, requests, asyncio, re" ]
7
import parsel, requests, asyncio, re from typing import List class InComment: def __init__(self, optional_words: List[str]=[], remove_words: List[str]=[]) -> None: self.might_sensitive_words = [ 'user', 'password', 'import', 'login', '.php', ...
null
v0
[ "float", "pd.DataFrame" ]
float
def v0(v1: float, v2: pd.DataFrame) -> float: v3 = v2[v2.index < v1][['OI_call']] v3['loss'] = (v1 - v3.index) * v3['OI_call'] v4 = v3['loss'].sum() v5 = v2[v2.index > v1][['OI_put']] v5['loss'] = (v5.index - v1) * v5['OI_put'] v6 = v5.loss.sum() v7 = v4 + v6 return v7
[]
[]
[]
9
"""Option helper functions""" __docformat__ = "numpy" import argparse from typing import List import pandas as pd import numpy as np from gamestonk_terminal.helper_funcs import ( parse_known_args_and_warn, check_non_negative, ) # pylint: disable=R1710 def load(other_args: List[str]) -> str: """Load ti...
null
v8
[ "pd.DataFrame" ]
int
def v8(v9: pd.DataFrame) -> int: v10 = np.array(v9.index) if 'OI_call' not in v9.columns or 'OI_put' not in v9.columns: print('Incorrect columns. Unable to parse max pain') return np.nan v11 = [] for v12 in v10: v11.append(v0(v12, v9)) v9['loss'] = v11 v13 = v9['loss'].i...
[ { "name": "v0", "input_types": [ "float", "pd.DataFrame" ], "output_type": "float", "code": "def v0(v1: float, v2: pd.DataFrame) -> float:\n v3 = v2[v2.index < v1][['OI_call']]\n v3['loss'] = (v1 - v3.index) * v3['OI_call']\n v4 = v3['loss'].sum()\n v5 = v2[v2.index > v1]...
[ "numpy" ]
[ "import numpy as np" ]
11
"""Option helper functions""" __docformat__ = "numpy" import argparse from typing import List import pandas as pd import numpy as np from gamestonk_terminal.helper_funcs import ( parse_known_args_and_warn, check_non_negative, ) # pylint: disable=R1710 def load(other_args: List[str]) -> str: """Load ti...
null
v0
[ "list[list[float]]" ]
list[list[float]]
def v0(v1: list[list[float]]) -> list[list[float]]: v2 = Decimal v3 = v2(v1[0][0]) * v2(v1[1][1]) - v2(v1[1][0]) * v2(v1[0][1]) if v3 == 0: raise ValueError('This matrix has no inverse.') v4 = [[0.0, 0.0], [0.0, 0.0]] (v4[0][0], v4[1][1]) = (v1[1][1], v1[0][0]) (v4[1][0], v4[0][1]) = (-v...
[]
[ "decimal" ]
[ "from decimal import Decimal" ]
9
from __future__ import annotations from decimal import Decimal def inverse_of_matrix(matrix: list[list[float]]) -> list[list[float]]: """ A matrix multiplied with its inverse gives the identity matrix. This function finds the inverse of a 2x2 matrix. If the determinant of a matrix is 0, its inverse d...
null
v7
[ "torch.Tensor" ]
Any
def v7(v8: torch.Tensor): if isinstance(v8, nn.Linear): v0(v8.weight.data) torch.nn.init.zeros_(v8.bias.data) if isinstance(v8, nn.LayerNorm): torch.nn.init.zeros_(v8.weight.data) torch.nn.init.zeros_(v8.bias.data)
[ { "name": "v0", "input_types": [ "torch.Tensor", "float", "float" ], "output_type": "torch.Tensor", "code": "def v0(v1: torch.Tensor, v2: float=0.1, v3: float=0) -> torch.Tensor:\n (v4, v5) = torch.nn.init._calculate_fan_in_and_fan_out(v1)\n v6 = math.sqrt(v2 / v4)\n r...
[ "math", "torch" ]
[ "import torch", "import torch.nn as nn", "import math", "from torch.utils.data import Dataset, DataLoader" ]
7
# Imports import torch from labml_nn.transformers.switch import SwitchTransformer, SwitchTransformerLayer, SwitchFeedForward from labml_nn.transformers import MultiHeadAttention from labml_nn.transformers.feed_forward import FeedForward import numpy as np from transformers import AutoConfig, AutoModel import torch.nn a...
null
v0
[ "torch.Tensor", "float", "float" ]
torch.Tensor
def v0(v1: torch.Tensor, v2: float=0.1, v3: float=0) -> torch.Tensor: (v4, v5) = torch.nn.init._calculate_fan_in_and_fan_out(v1) v6 = math.sqrt(v2 / v4) return torch.nn.init.trunc_normal_(tensor=v1, mean=v3, std=v6)
[]
[ "math", "torch" ]
[ "import torch", "import torch.nn as nn", "import math", "from torch.utils.data import Dataset, DataLoader" ]
4
# Imports import torch from labml_nn.transformers.switch import SwitchTransformer, SwitchTransformerLayer, SwitchFeedForward from labml_nn.transformers import MultiHeadAttention from labml_nn.transformers.feed_forward import FeedForward import numpy as np from transformers import AutoConfig, AutoModel import torch.nn a...
null
v0
[ "Iterable" ]
Any
def v0(self, v1: Iterable): if self.write_sentence(v1) == 0: return while 1: v2 = self.read_sentence() if len(v2) == 0: continue v3 = v2[0] v4 = {} for v5 in v2[1:]: v6 = v5.find('=', 1) if v6 == -1: v4[v5] = '' ...
[]
[]
[]
18
import binascii import re import socket from abc import ABCMeta from hashlib import md5 from ipaddress import ip_network, _BaseNetwork from typing import Iterable, Optional, Tuple, Generator, Dict, Iterator from django.conf import settings from django.utils.translation import ugettext_lazy as _ from djing.lib.decorato...
null
v0
[ "Iterable" ]
Any
def v0(self, v1: Iterable): v2 = 0 for v3 in v1: self.write_word(v3) v2 += 1 self.write_word('') return v2
[]
[]
[]
7
import binascii import re import socket from abc import ABCMeta from hashlib import md5 from ipaddress import ip_network, _BaseNetwork from typing import Iterable, Optional, Tuple, Generator, Dict, Iterator from django.conf import settings from django.utils.translation import ugettext_lazy as _ from djing.lib.decorato...
null
v0
[ "str" ]
Optional[i_structs.SubnetQueue]
def v0(self, v1: str) -> Optional[i_structs.SubnetQueue]: v2 = self._exec_cmd(('/queue/simple/print', '?name=%s' % v1)) if v2: return self._build_shape_obj(v2.get('!re'))
[]
[]
[]
4
import binascii import re import socket from abc import ABCMeta from hashlib import md5 from ipaddress import ip_network, _BaseNetwork from typing import Iterable, Optional, Tuple, Generator, Dict, Iterator from django.conf import settings from django.utils.translation import ugettext_lazy as _ from djing.lib.decorato...
null
v0
[ "Iterable[str]" ]
Any
def v0(self, v1: Iterable[str]): v2 = ','.join(v1) if len(v2) > 1: self._exec_cmd(('/queue/simple/remove', '=numbers=%s' % v2))
[]
[]
[]
4
import binascii import re import socket from abc import ABCMeta from hashlib import md5 from ipaddress import ip_network, _BaseNetwork from typing import Iterable, Optional, Tuple, Generator, Dict, Iterator from django.conf import settings from django.utils.translation import ugettext_lazy as _ from djing.lib.decorato...
null
v0
[]
Generator
def v0(self) -> Generator: for v1 in self._exec_cmd_iter(('/queue/simple/print', '=detail')): v2 = self._build_shape_obj(v1) if v2 is not None: yield v2
[]
[]
[]
5
import binascii import re import socket from abc import ABCMeta from hashlib import md5 from ipaddress import ip_network, _BaseNetwork from typing import Iterable, Optional, Tuple, Generator, Dict, Iterator from django.conf import settings from django.utils.translation import ugettext_lazy as _ from djing.lib.decorato...
null
v0
[ "i_structs.VectorQueue" ]
Any
def v0(self, v1: i_structs.VectorQueue): for v2 in v1: self.add_user(v2)
[]
[]
[]
3
import binascii import re import socket from abc import ABCMeta from hashlib import md5 from ipaddress import ip_network, _BaseNetwork from typing import Iterable, Optional, Tuple, Generator, Dict, Iterator from django.conf import settings from django.utils.translation import ugettext_lazy as _ from djing.lib.decorato...
null
v0
[ "Any", "Any" ]
Optional[Tuple[int, int]]
def v0(self, v1, v2=10) -> Optional[Tuple[int, int]]: v3 = self._exec_cmd(('/ip/arp/print', '?address=%s' % v1)) if v3 == {}: return v4 = v3['!re'].get('=interface') v3 = self._exec_cmd(('/ping', '=address=%s' % v1, '=arp-ping=yes', '=interval=100ms', '=count=%d' % v2, '=interface=%s' % v4)) ...
[]
[]
[]
10
import binascii import re import socket from abc import ABCMeta from hashlib import md5 from ipaddress import ip_network, _BaseNetwork from typing import Iterable, Optional, Tuple, Generator, Dict, Iterator from django.conf import settings from django.utils.translation import ugettext_lazy as _ from djing.lib.decorato...
null
v0
[ "str", "str" ]
bytes
def v0(self, v1: str, v2: str) -> bytes: v3 = ''.join([self.url_prefix, '/products/', str(v2)]) v4 = {} v4['some_parameter'] = v1 v5 = requests.request(method='get', url=v3, params=v4, auth=self.auth) with contextlib.closing(v5): v5.raise_for_status() return v5.content
[]
[ "contextlib", "requests" ]
[ "import contextlib", "import requests", "import requests.auth" ]
8
#!/usr/bin/env python3 # Automatically generated file by swagger_to. DO NOT EDIT OR APPEND ANYTHING! """Implements the client for test.""" # pylint: skip-file # pydocstyle: add-ignore=D105,D107,D401 import contextlib import json from typing import Any, BinaryIO, Dict, List, MutableMapping, Optional import requests i...
null
v3
[]
None
def v3(self) -> None: async def v4() -> None: async with self.init_client() as v5: self.assertEqual(await v5.addPrimitive(0, 0), 0) async with v5.createAddition() as v6: self.assertEqual(await v6.getPrimitive(), 0) v6.accumulatePrimitive(1) ...
[ { "name": "v0", "input_types": [], "output_type": "None", "code": "async def v0() -> None:\n try:\n async with self.init_client() as v1:\n self.assertEqual(await v1.addPrimitive(0, 0), 0)\n async with v1.createAddition() as v2:\n v2.accumulatePrimitive(...
[ "asyncio" ]
[ "import asyncio" ]
16
# Copyright (c) Facebook, Inc. and its affiliates. # # 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 ...
null
v3
[]
None
def v3(self) -> None: async def v4() -> None: async with self.init_client() as v5: async with v5.createAddition() as v6: pass asyncio.run(v4())
[ { "name": "v0", "input_types": [], "output_type": "None", "code": "async def v0() -> None:\n try:\n async with self.init_client() as v1:\n self.assertEqual(await v1.addPrimitive(0, 0), 0)\n async with v1.createAddition() as v2:\n v2.accumulatePrimitive(...
[ "asyncio" ]
[ "import asyncio" ]
7
# Copyright (c) Facebook, Inc. and its affiliates. # # 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 ...
null
v0
[ "str", "Any", "str", "str", "str" ]
Any
def v0(self, v1: str, v2, v3: str=None, v4: str=None, v5: str=None): v6 = dict(MessageBody=json.dumps({'Message': v1})) if v3: v6['MessageAttributes'] = {'event_type': {'DataType': 'String', 'StringValue': v3}} if v4: v6['MessageGroupId'] = v4 if v5: v6['MessageDeduplicationId'] ...
[]
[ "json" ]
[ "import json", "from json import JSONDecodeError" ]
9
# type: ignore import json import uuid from json import JSONDecodeError from typing import Tuple, Dict, List import boto3 from melange.drivers.interfaces import Queue, Topic, MessagingDriver, Message class AWSDriver(MessagingDriver): def __init__(self, **kwargs): super().__init__() self.max_num...
null
v33
[ "bool", "Any", "Any" ]
Any
def v33(v34: bool, v35, v36): def v37(v38, v39): v40 = 0 for v41 in v38: if v41 is v39: v40 += 1 return v40 def v42(v43: bool, v44, v45): def v46(v47, v48): for v49 in v47: if v49 is v48: return True ...
[ { "name": "v0", "input_types": [ "bool", "Any", "Any" ], "output_type": "Any", "code": "def v0(v1: bool, v2, v3):\n\n def v4(v5, v6):\n for v7 in v5:\n if v7 is v6:\n return True\n return False\n v8 = deepcopy([possibility for v9 in...
[ "copy" ]
[ "from copy import deepcopy" ]
65
#Import modules and libraries from random import randint from string import ascii_uppercase, ascii_lowercase from itertools import permutations from copy import deepcopy from tail_recursion import tail_recursive, recurse #Define board mapping function def mapBoard(col, row, value): board = [[value for x in range(c...
null
v9
[ "bool", "Any", "Any" ]
Any
def v9(v10: bool, v11, v12): def v13(v14, v15): for v16 in v14: if v16 is v15: return True return False v17 = deepcopy([possibility for v18 in v11 if v18[-1][1] == v12]) v19 = deepcopy([v18 for v18 in v11 if v18 not in v17]) if len(v17) == 1: v19.appe...
[ { "name": "v0", "input_types": [ "Any", "Any" ], "output_type": "Any", "code": "def v0(v1, v2):\n for v3 in v1:\n if v3 is v2:\n return True\n return False", "dependencies": [] }, { "name": "v4", "input_types": [ "Any", "Any" ],...
[ "copy" ]
[ "from copy import deepcopy" ]
44
#Import modules and libraries from random import randint from string import ascii_uppercase, ascii_lowercase from itertools import permutations from copy import deepcopy from tail_recursion import tail_recursive, recurse #Define board mapping function def mapBoard(col, row, value): board = [[value for x in range(c...
null
v0
[ "str" ]
Any
def v0(self, v1: str): if 'metro' in v1: v2 = 160 v3 = 160 else: v2 = 80 v3 = 80 v4 = Image.new('RGBA', (v3 * 12, v2), (0, 255, 0, 0)) v5 = f'{v1}.png' v6 = 0 v7 = 'bknpqr' for v8 in 'bw': for v9 in v7: v10 = f'{v8}{v9}' v11 = I...
[]
[ "PIL", "os" ]
[ "import os", "from PIL import Image, ImageFile" ]
20
# coding: utf-8 # @author octopoulo <polluxyz@gmail.com> # @version 2020-05-01 """ Sync """ import gzip from logging import getLogger import os import re import shutil from subprocess import run from time import time from typing import Any from PIL import Image, ImageFile from common import makedirs_safe, read_text...
null
v0
[ "str" ]
Any
def v0(self, v1: str): v2 = os.listdir(v1) for v3 in v2: v4 = os.path.join(v1, v3) if os.path.isdir(v4): self.combine_pieces(v4)
[]
[ "os" ]
[ "import os" ]
6
# coding: utf-8 # @author octopoulo <polluxyz@gmail.com> # @version 2020-05-01 """ Sync """ import gzip from logging import getLogger import os import re import shutil from subprocess import run from time import time from typing import Any from PIL import Image, ImageFile from common import makedirs_safe, read_text...
null
v0
[ "str" ]
str
def v0(self, v1: str) -> str: v1 = re.sub('\\bTHREE\\b', 'T', v1) v1 = re.sub('console\\.(error|warn)\\(.+?\\);', '', v1, flags=re.S) return v1
[]
[ "re" ]
[ "import re" ]
4
# coding: utf-8 # @author octopoulo <polluxyz@gmail.com> # @version 2020-05-01 """ Sync """ import gzip from logging import getLogger import os import re import shutil from subprocess import run from time import time from typing import Any from PIL import Image, ImageFile from common import makedirs_safe, read_text...
null
v0
[ "str" ]
Any
def v0(self, v1: str): v2 = f'{v1}.gz' with open(v1, 'rb') as v3: with gzip.open(v2, 'wb') as v4: shutil.copyfileobj(v3, v4) if os.path.isfile(v2): v5 = os.stat(v2) os.utime(v1, (v5.st_atime, v5.st_mtime)) print('g', end='')
[]
[ "gzip", "os", "shutil" ]
[ "import gzip", "import os", "import shutil" ]
9
# coding: utf-8 # @author octopoulo <polluxyz@gmail.com> # @version 2020-05-01 """ Sync """ import gzip from logging import getLogger import os import re import shutil from subprocess import run from time import time from typing import Any from PIL import Image, ImageFile from common import makedirs_safe, read_text...
null
v0
[]
None
def v0(self) -> None: v1 = 'https://secure.kontomierz.pl/k4/user_accounts.json?api_key=' + self.apiToken v2 = requests.get(v1, auth=HTTPBasicAuth(self.username, self.password), headers={'Content-Type': 'application/json', 'Accept': 'application/json'}, data={}) v3 = v2.json() v4 = 0.0 for v5 in v3: ...
[]
[ "requests" ]
[ "import requests", "from requests.auth import HTTPBasicAuth" ]
11
"""Platform for sensor integration.""" from __future__ import annotations import homeassistant.helpers.config_validation as cv import requests import voluptuous as vol from homeassistant.components.sensor import SensorEntity, PLATFORM_SCHEMA, SensorStateClass, SensorDeviceClass from homeassistant.const import CONF_USE...
null
v0
[]
bool
def v0(self) -> bool: if not super().validate(): return False else: pass
[]
[]
[]
5
# Pydifact - a python edifact library # # Copyright (c) 2019 Christian González # # 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 ...
null
v0
[ "'K x N'" ]
Any
def v0(v1: 'K x N'): v2 = v1.permute(1, 0) @ v1 return torch.trace(v2) / abs(v2).sum()
[]
[ "torch" ]
[ "import torch", "import torch.nn as nn", "import torch.backends.cudnn as cudnn" ]
3
from __future__ import print_function from __future__ import division import os import sys import time import datetime import os.path as osp import numpy as np import warnings import torch import torch.nn as nn import torch.backends.cudnn as cudnn from args import argument_parser, image_dataset_kwargs, optimizer_kwa...
null
v0
[ "Callable" ]
Any
def v0(self, v1: Callable): self.state_changed_callback = v1 if self.wallet_state_manager is not None: self.wallet_state_manager.set_callback(self.state_changed_callback) self.wallet_state_manager.set_pending_callback(self._pending_tx_handler)
[]
[]
[]
5
import asyncio import json import logging import socket import time import traceback from pathlib import Path from typing import Callable, Dict, List, Optional, Set, Tuple, Union from blspy import PrivateKey from chia.consensus.block_record import BlockRecord from chia.consensus.blockchain_interface import BlockchainI...
null
v0
[]
None
async def v0(self) -> None: v1 = 0 while not self._shut_down and v1 < 5: if self.has_full_node(): await self.wallet_peers.ensure_is_closed() if self.wallet_state_manager is not None: self.wallet_state_manager.state_changed('add_connection') break ...
[]
[ "asyncio" ]
[ "import asyncio" ]
10
import asyncio import json import logging import socket import time import traceback from pathlib import Path from typing import Callable, Dict, List, Optional, Set, Tuple, Union from blspy import PrivateKey from chia.consensus.block_record import BlockRecord from chia.consensus.blockchain_interface import BlockchainI...
null
v0
[]
None
def v0(self) -> None: self.log.info('self.sync_event.set()') self.sync_event.set()
[]
[]
[]
3
import asyncio import json import logging import socket import time import traceback from pathlib import Path from typing import Callable, Dict, List, Optional, Set, Tuple, Union from blspy import PrivateKey from chia.consensus.block_record import BlockRecord from chia.consensus.blockchain_interface import BlockchainI...
null
v0
[]
None
async def v0(self) -> None: if self.wallet_state_manager is None: return None v1: Optional[BlockRecord] = self.wallet_state_manager.blockchain.get_peak() if v1 is None: return None v2: List[Tuple[bytes32, HeaderBlock]] = self.wallet_state_manager.sync_store.get_potential_peaks_tuples() ...
[]
[ "asyncio" ]
[ "import asyncio" ]
12
import asyncio import json import logging import socket import time import traceback from pathlib import Path from typing import Callable, Dict, List, Optional, Set, Tuple, Union from blspy import PrivateKey from chia.consensus.block_record import BlockRecord from chia.consensus.blockchain_interface import BlockchainI...
null
v0
[ "list" ]
Any
def v0(self, v1: list): self.updated = True v1.reverse() for v2 in v1: self.table.insert_new_row(v2)
[]
[]
[]
5
import numpy as np import pyqtgraph as pg from datetime import datetime, timedelta from vnpy.trader.constant import Interval, Direction, Offset from vnpy.trader.engine import MainEngine from vnpy.trader.ui import QtCore, QtWidgets, QtGui from vnpy.trader.ui.widget import BaseMonitor, BaseCell, DirectionCell, EnumCell ...
null
v0
[ "list" ]
Any
def v0(self, v1: list): self.updated = True self.chart.update_history(v1) for (v2, v3) in enumerate(v1): self.dt_ix_map[v3.datetime] = v2
[]
[]
[]
5
import numpy as np import pyqtgraph as pg from datetime import datetime, timedelta from vnpy.trader.constant import Interval, Direction, Offset from vnpy.trader.engine import MainEngine from vnpy.trader.ui import QtCore, QtWidgets, QtGui from vnpy.trader.ui.widget import BaseMonitor, BaseCell, DirectionCell, EnumCell ...
null
v0
[ "str" ]
int
def v0(self, v1: str) -> int: v2 = self.root_node for v3 in v1: if v3 not in v2.children: return 0 v2 = v2.children[v3] return v2.value
[]
[]
[]
7
# # @lc app=leetcode id=677 lang=python3 # # [677] Map Sum Pairs # https://leetcode.com/problems/map-sum-pairs/ # This problem is about the trie data structure. Each node keeps track of the sum of its children. # A new key overrides the original values. # import unittest from typing import Dict # @lc code=s...
null
v4
[ "str", "t.List[str]" ]
bool
def v4(v5: str, v6: t.List[str]) -> bool: v5 = os.path.abspath(v5) for v7 in v6: v7 = os.path.abspath(v7) if v0(v5, v7): return True return False
[ { "name": "v0", "input_types": [ "str", "str" ], "output_type": "bool", "code": "def v0(v1: str, v2: str) -> bool:\n try:\n v3 = os.path.relpath(v1, v2)\n except ValueError:\n return False\n return v3 == os.curdir or not v3.startswith(os.pardir)", "dependen...
[ "os" ]
[ "import os" ]
7
__author__ = 'Niklas Rosenstein <rosensteinniklas@gmail.com>' __version__ = '1.7.6' import copy import glob import os import pkgutil import sys import traceback import typing as t import zipfile if t.TYPE_CHECKING: from sys import _MetaPathFinder def is_local(filename: str, pathlist: t.List[str]) -> bool: ''' ...
null
v0
[ "str", "str" ]
bool
def v0(v1: str, v2: str) -> bool: try: v3 = os.path.relpath(v1, v2) except ValueError: return False return v3 == os.curdir or not v3.startswith(os.pardir)
[]
[ "os" ]
[ "import os" ]
6
__author__ = 'Niklas Rosenstein <rosensteinniklas@gmail.com>' __version__ = '1.7.6' import copy import glob import os import pkgutil import sys import traceback import typing as t import zipfile if t.TYPE_CHECKING: from sys import _MetaPathFinder def is_local(filename: str, pathlist: t.List[str]) -> bool: ''' ...
null
v4
[ "str", "str", "t.Optional[t.List[str]]", "t.Optional[t.List[t.Tuple[str, int, str]]]" ]
t.List[str]
def v4(v5: str, v6: str, v7: t.Optional[t.List[str]]=None, v8: t.Optional[t.List[t.Tuple[str, int, str]]]=None) -> t.List[str]: if v7 is None: v7 = sys.path if not os.path.isfile(v5): return [] with open(v5, 'r') as v9: for (v10, v11) in enumerate(v9): if v11.startswith('...
[ { "name": "v0", "input_types": [ "str", "int", "str" ], "output_type": "None", "code": "def v0(v1: str, v2: int, v3: str) -> None:\n v3 = '\\n' * (v2 - 1) + v3.strip()\n try:\n exec(compile(v3, v1, 'exec'))\n except BaseException:\n traceback.print_exc()"...
[ "os", "sys", "traceback" ]
[ "import os", "import sys", "import traceback" ]
23
__author__ = 'Niklas Rosenstein <rosensteinniklas@gmail.com>' __version__ = '1.7.6' import copy import glob import os import pkgutil import sys import traceback import typing as t import zipfile if t.TYPE_CHECKING: from sys import _MetaPathFinder def is_local(filename: str, pathlist: t.List[str]) -> bool: ''' ...
null
v0
[ "str", "int", "str" ]
None
def v0(v1: str, v2: int, v3: str) -> None: v3 = '\n' * (v2 - 1) + v3.strip() try: exec(compile(v3, v1, 'exec')) except BaseException: traceback.print_exc()
[]
[ "traceback" ]
[ "import traceback" ]
6
__author__ = 'Niklas Rosenstein <rosensteinniklas@gmail.com>' __version__ = '1.7.6' import copy import glob import os import pkgutil import sys import traceback import typing as t import zipfile if t.TYPE_CHECKING: from sys import _MetaPathFinder def is_local(filename: str, pathlist: t.List[str]) -> bool: ''' ...
null
v3
[ "t.List[str]", "str" ]
t.List[str]
def v3(v4: t.List[str], v5: str) -> t.List[str]: def v6(v7, v8): v8.rstrip('/') return v8 in v7.namelist() v9 = os.path.join(*v5.split('.')) v10 = '/'.join(v5.split('.')) v11 = '__init__' + os.extsep + 'py' v12 = '__init__' + os.extsep + 'pyc' v13 = '__init__' + os.extsep + 'pyo...
[ { "name": "v0", "input_types": [ "Any", "Any" ], "output_type": "Any", "code": "def v0(v1, v2):\n v2.rstrip('/')\n return v2 in v1.namelist()", "dependencies": [] } ]
[ "os", "sys", "zipfile" ]
[ "import os", "import sys", "import zipfile" ]
28
__author__ = 'Niklas Rosenstein <rosensteinniklas@gmail.com>' __version__ = '1.7.6' import copy import glob import os import pkgutil import sys import traceback import typing as t import zipfile if t.TYPE_CHECKING: from sys import _MetaPathFinder def is_local(filename: str, pathlist: t.List[str]) -> bool: ''' ...
null
v0
[ "t.Union[t.List[str], str]" ]
None
def v0(self, v1: t.Union[t.List[str], str]) -> None: if not isinstance(v1, str): for v2 in v1: self.disable(v2) return v3 = v1 + '.' v4 = {} for (v5, v6) in sys.modules.items(): if v5 == v1 or v5.startswith(v3): try: v7 = '.'.join(v5.split(...
[]
[ "sys" ]
[ "import sys" ]
23
__author__ = 'Niklas Rosenstein <rosensteinniklas@gmail.com>' __version__ = '1.7.6' import copy import glob import os import pkgutil import sys import traceback import typing as t import zipfile if t.TYPE_CHECKING: from sys import _MetaPathFinder def is_local(filename: str, pathlist: t.List[str]) -> bool: ''' ...
null
v0
[]
None
def v0(self) -> None: for (v1, v2, v3) in self.discover(): self.disable(v2)
[]
[]
[]
3
__author__ = 'Niklas Rosenstein <rosensteinniklas@gmail.com>' __version__ = '1.7.6' import copy import glob import os import pkgutil import sys import traceback import typing as t import zipfile if t.TYPE_CHECKING: from sys import _MetaPathFinder def is_local(filename: str, pathlist: t.List[str]) -> bool: ''' ...
null
v2
[ "str" ]
Any
def v2(v3: str): v4 = v3.split('_') assert len(v4) == 7 v5 = float(v0(v4[1])) v6 = int(v0(v4[2])) v7 = int(v0(v4[3])) v8 = int(v0(v4[4])) return (v5, v6, v7, v8)
[ { "name": "v0", "input_types": [ "str" ], "output_type": "Any", "code": "def v0(v1: str):\n return v1.split('=')[-1]", "dependencies": [] } ]
[]
[]
8
import numpy as np import matplotlib.pyplot as plt import argparse def extract_name(word: str): return word.split('=')[-1] def extract_info(filename: str): filename_splitted = filename.split('_') assert len(filename_splitted) == 7 p = float(extract_name(filename_splitted[1])) iterations = int(ex...
null
v0
[ "str" ]
list
def v0(v1: str) -> list: with open(v1, 'r') as v2: return [float(line.strip()) for v3 in v2]
[]
[]
[]
3
import numpy as np import matplotlib.pyplot as plt import argparse def extract_name(word: str): return word.split('=')[-1] def extract_info(filename: str): filename_splitted = filename.split('_') assert len(filename_splitted) == 7 p = float(extract_name(filename_splitted[1])) iterations = int(ex...
null
v9
[ "str", "list", "str" ]
Any
def v9(v10: str, v11: list, v12: str=None): (v13, v14, v15, v16) = v0(v10) v17 = np.linspace(0, v14, len(v11)) plt.rc('text', usetex=True) plt.rc('font', family='serif') plt.figure(figsize=(8, 5)) plt.grid(True, alpha=0.3) plt.plot(v17, v11, label=f'p = {v13}, N = {v15}, G = {v16}') plt....
[ { "name": "v0", "input_types": [ "str" ], "output_type": "Any", "code": "def v0(v1: str):\n v2 = v1.split('_')\n assert len(v2) == 7\n v3 = float(extract_name(v2[1]))\n v4 = int(extract_name(v2[2]))\n v5 = int(extract_name(v2[3]))\n v6 = int(extract_name(v2[4]))\n retu...
[ "matplotlib", "numpy" ]
[ "import numpy as np", "import matplotlib.pyplot as plt" ]
17
import numpy as np import matplotlib.pyplot as plt import argparse def extract_name(word: str): return word.split('=')[-1] def extract_info(filename: str): filename_splitted = filename.split('_') assert len(filename_splitted) == 7 p = float(extract_name(filename_splitted[1])) iterations = int(ex...
null
v8
[ "str", "str" ]
None
def v8(v9: str, v10: str='') -> None: if v9 == 'seconds': sqlite3.register_adapter(time, v2) elif v9 == 'text': sqlite3.register_adapter(time, v4(v10)) else: raise ValueError(f"Unknown time adapter: '{v9}'")
[ { "name": "v0", "input_types": [ "time" ], "output_type": "str", "code": "def v0(v1: time) -> str:\n return v1.strftime(format)", "dependencies": [] }, { "name": "v2", "input_types": [ "time" ], "output_type": "float", "code": "def v2(v3: time) -> float...
[ "datetime", "sqlite3" ]
[ "from datetime import date, datetime, time", "import sqlite3" ]
7
from calendar import timegm from datetime import date, datetime, time import sqlite3 from typing import Callable import julian # type: ignore def store_time(time_type: str, time_format: str = "") -> None: if time_type == "seconds": sqlite3.register_adapter(time, time_to_seconds) elif time_type == "t...
null
v10
[ "str", "str" ]
None
def v10(v11: str, v12: str='') -> None: if v11 == 'julian': sqlite3.register_adapter(datetime, v2) elif v11 == 'posix': sqlite3.register_adapter(datetime, v4) elif v11 == 'text': sqlite3.register_adapter(datetime, v6(v12)) else: raise ValueError(f"Unknown datetime adapter...
[ { "name": "v0", "input_types": [ "datetime" ], "output_type": "str", "code": "def v0(v1: datetime) -> str:\n return v1.strftime(format)", "dependencies": [] }, { "name": "v2", "input_types": [ "datetime" ], "output_type": "float", "code": "def v2(v3: da...
[ "calendar", "datetime", "sqlite3" ]
[ "from calendar import timegm", "from datetime import date, datetime, time", "import sqlite3" ]
9
from calendar import timegm from datetime import date, datetime, time import sqlite3 from typing import Callable import julian # type: ignore def store_time(time_type: str, time_format: str = "") -> None: if time_type == "seconds": sqlite3.register_adapter(time, time_to_seconds) elif time_type == "t...
null
v2
[ "str" ]
Callable[[time], str]
def v2(v3: str) -> Callable[[time], str]: def v4(v5: time) -> str: return v5.strftime(v3) return v4
[ { "name": "v0", "input_types": [ "time" ], "output_type": "str", "code": "def v0(v1: time) -> str:\n return v1.strftime(format)", "dependencies": [] } ]
[]
[]
5
from calendar import timegm from datetime import date, datetime, time import sqlite3 from typing import Callable import julian # type: ignore def store_time(time_type: str, time_format: str = "") -> None: if time_type == "seconds": sqlite3.register_adapter(time, time_to_seconds) elif time_type == "t...
null
v2
[ "str" ]
Callable[[datetime], str]
def v2(v3: str) -> Callable[[datetime], str]: def v4(v5: datetime) -> str: return v5.strftime(v3) return v4
[ { "name": "v0", "input_types": [ "datetime" ], "output_type": "str", "code": "def v0(v1: datetime) -> str:\n return v1.strftime(format)", "dependencies": [] } ]
[]
[]
5
from calendar import timegm from datetime import date, datetime, time import sqlite3 from typing import Callable import julian # type: ignore def store_time(time_type: str, time_format: str = "") -> None: if time_type == "seconds": sqlite3.register_adapter(time, time_to_seconds) elif time_type == "t...
null
v0
[ "Dataset" ]
Any
def v0(v1: Dataset): v2 = DataLoader(v1, batch_size=1, shuffle=False) v3 = torch.zeros(3) v4 = torch.zeros(3) for (v5, (v6, v7)) in enumerate(v2): if v5 % 1000 == 0: print(v5) v3 += v6.mean(dim=(0, 2, 3)) v4 += v6.std(dim=(0, 2, 3)) v3 /= len(v2) v4 /= len(v2)...
[]
[ "torch" ]
[ "import torch", "from torch.utils.data import Dataset, DataLoader", "from torch.utils.data.distributed import DistributedSampler" ]
12
import logging import os import numpy as np import torch from torch.utils.data import Dataset, DataLoader import torchvision.transforms as transforms from torch.utils.data.distributed import DistributedSampler from .dataset import CheXpert def _get_mean_and_std(dataset: Dataset): """Compute the mean and std of ...
null
v6
[ "v0" ]
None
def v6(self, v7: v0) -> None: self._state = v7 self._state.context = self
[]
[]
[]
3
""" 状态模式 """ from __future__ import annotations from abc import ABC, abstractmethod class Context: # 状态(状态模式的判断) _state: State = None def __init__(self, state: State) -> None: self.transition_to(state) def transition_to(self, state: State) -> None: # 根据不同状态,切换上下文 self._state ...
[ "class v0(ABC):\n\n @property\n def v1(self) -> Context:\n return self._context\n\n @v3.setter\n def v2(self, v3: Context) -> None:\n self._context = v3\n\n @abstractmethod\n def v4(self) -> None:\n pass\n\n @abstractmethod\n def v5(self) -> None:\n pass" ]
v0
[ "pd.DataFrame", "str" ]
bytes
def v0(v1: pd.DataFrame, v2: str='csv') -> bytes: v3: int = int(re.sub('[^0-9]', '', pd.__version__)) if v2 == 'csv': v4 = BytesIO() if v3 >= 120: v1.to_csv(v4, index=False) else: v4.write(v1.to_csv(index=False).encode('utf-8')) v4.seek(0) retu...
[]
[ "io", "pandas", "re" ]
[ "import re", "from io import BytesIO", "import pandas as pd" ]
12
"""Various input/output utility functions""" from typing import Any, Optional import os import re from io import BytesIO import cloudpickle import pandas as pd from zstandard import ZstdCompressor, ZstdDecompressor COMPRESSION_MAX_OUTPUT_SIZE = 10 ** 9 # 1GB def pickle_dumps(variable: object) -> bytes: pickl...
null
v0
[ "Any", "int | None" ]
str
def v0(v1, v2: int | None=None) -> str: v3 = 0 v4 = ['' for v5 in range(len(v1))] for (v5, v6) in enumerate(v1): try: v7 = repr(v6) except Exception: v7 = '< could not convert arg to str >' v4[v5] = v7 v3 += len(v7) + 2 if v2 is not None and v3...
[]
[]
[]
14
from __future__ import annotations import asyncio import bisect import builtins import concurrent.futures import errno import heapq import logging import os import random import sys import threading import warnings import weakref from collections import defaultdict, deque, namedtuple from collections.abc import Hashab...
null
v0
[ "dict", "int | None" ]
str
def v0(v1: dict, v2: int | None=None) -> str: v3 = 0 v4 = ['' for v5 in range(len(v1))] for (v5, (v6, v7)) in enumerate(v1.items()): try: v8 = repr(v7) except Exception: v8 = '< could not convert arg to str >' v9 = repr(v6) + ': ' + v8 v4[v5] = v9 ...
[]
[]
[]
15
from __future__ import annotations import asyncio import bisect import builtins import concurrent.futures import errno import heapq import logging import os import random import sys import threading import warnings import weakref from collections import defaultdict, deque, namedtuple from collections.abc import Hashab...
null
v0
[ "str" ]
bool
def v0(self, v1: str) -> bool: v2 = self.tasks[v1] if not v2.resource_restrictions: return True for (v3, v4) in v2.resource_restrictions.items(): if self.available_resources[v3] < v4: return False return True
[]
[]
[]
8
from __future__ import annotations import asyncio import bisect import builtins import concurrent.futures import errno import heapq import logging import os import random import sys import threading import warnings import weakref from collections import defaultdict, deque, namedtuple from collections.abc import Hashab...
null
v0
[]
Tuple[float, float]
def v0(self) -> Tuple[float, float]: if self.number_tracks() == 0: return (0, 0) v1 = self.get_track_lengths() return (np.mean(v1), np.median(v1))
[]
[ "numpy" ]
[ "import numpy as np" ]
5
"""Class to hold the tracks and cameras of a 3D scene. This can be the output of either data association or of bundle adjustment. Authors: Ayush Baid, John Lambert, Xiaolong Wu """ import itertools from typing import Any, Dict, List, Optional, Tuple import numpy as np from gtsam import PinholeCameraCal3Bundler, Pose3...
null