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
[ "tweepy.API" ]
Any
def v0(self, v1: tweepy.API): self.api = v1 if self.api is not None: self.connected = True else: self.connected = False self.retweetw.set_connected(self.connected) self.tweetw.set_connected(self.connected)
[]
[]
[]
8
#!/usr/bin/env python3 import sys from PySide2 import QtCore, QtWidgets, QtGui from os.path import exists, join, abspath from os import remove import tweepy from auth.auth import AuthData from tweet.tweet import getTweetsKeyword, tweetRandom, OutputerInterface import types class AuthDataInput(QtWidgets.QWidget): d...
null
v0
[ "bool" ]
Any
def v0(self, v1: bool): self.connected = v1 self.try_enabling_tweet_button()
[]
[]
[]
3
#!/usr/bin/env python3 import sys from PySide2 import QtCore, QtWidgets, QtGui from os.path import exists, join, abspath from os import remove import tweepy from auth.auth import AuthData from tweet.tweet import getTweetsKeyword, tweetRandom, OutputerInterface import types class AuthDataInput(QtWidgets.QWidget): d...
null
v0
[ "int", "float", "float", "Any" ]
bytes
def v0(self, v1: int, v2: float=None, v3: float=None, v4=True) -> bytes: if v3 is None: v3 = v2 v5 = bytearray() v6 = v1 while v6 > 0: v7 = v3 if len(v5) == 0 else v2 v8 = self.read(max_size=v6, timeout=v7) if v8 is None: break v6 -= len(v8) v5...
[]
[]
[]
15
import time from threading import Event, RLock from mltk.utils import hexdump from .device_interface import DeviceInterface, MAX_BUFFER_SIZE WAIT_FOREVER = 4294967.0 class JLinkDataStream(object): """JLink data stream""" def __init__( self, name:str, mode:str, ifc: Dev...
null
v0
[ "Any" ]
bytes
def v0(self, v1) -> bytes: with self._buffer_lock: v2 = self._buffer[:v1] self._buffer = self._buffer[v1:] if self._max_read_size != -1: if v1 <= self._max_read_size: self._max_read_size -= v1 else: self._max_read_size = 0 if self.m...
[]
[]
[]
12
import time from threading import Event, RLock from mltk.utils import hexdump from .device_interface import DeviceInterface, MAX_BUFFER_SIZE WAIT_FOREVER = 4294967.0 class JLinkDataStream(object): """JLink data stream""" def __init__( self, name:str, mode:str, ifc: Dev...
null
v0
[ "str", "str" ]
str
def v0(v1: str, v2: str) -> str: v3 = ['.' + p if not p.startswith('.') else p for v4 in Path(v2).parts] v5 = Path(v1, *v3).as_posix() return v5
[]
[ "pathlib" ]
[ "from pathlib import Path" ]
4
"""Utilities functions for setting up test fixtures.""" import tempfile from pathlib import Path import shutil import json from uuid import uuid4 import pandas as pd import numpy as np from iblutil.io.parquet import uuid2np, np2str import one.params def set_up_env(use_temp_cache=True) -> tempfile.TemporaryDirectory...
null
v0
[ "bytes", "bytes", "Any" ]
Any
def v0(self, v1: bytes, v2: bytes, v3=None): v4 = self.conn.cursor() v4.execute('INSERT OR REPLACE INTO data (key, value, expire_time_ms) VALUES (?, ?, ?)', (v1, v2, v3)) self.conn.commit()
[]
[]
[]
4
import os import sqlite3 from typing import List, Optional from .storage_base import Storage class SqliteStorage(Storage): def __init__(self, db_path): """ Init table "data" with the attribute "key" being the primary key :param db_path: str. Path to database file """ super(...
null
v0
[ "List[bytes]", "List[bytes]", "List[Optional[int]]" ]
Any
def v0(self, v1: List[bytes], v2: List[bytes], v3: List[Optional[int]]): v4 = self.conn.cursor() v4.executemany('INSERT OR REPLACE INTO data (key, value, expire_time_ms) VALUES (?, ?, ?)', zip(v1, v2, v3)) self.conn.commit()
[]
[]
[]
4
import os import sqlite3 from typing import List, Optional from .storage_base import Storage class SqliteStorage(Storage): def __init__(self, db_path): """ Init table "data" with the attribute "key" being the primary key :param db_path: str. Path to database file """ super(...
null
v0
[ "bytes" ]
bool
def v0(self, v1: bytes) -> bool: v2 = self.conn.cursor() v3 = v2.execute('DELETE FROM data WHERE key = ?', (v1,)).rowcount self.conn.commit() return v3 > 0
[]
[]
[]
5
import os import sqlite3 from typing import List, Optional from .storage_base import Storage class SqliteStorage(Storage): def __init__(self, db_path): """ Init table "data" with the attribute "key" being the primary key :param db_path: str. Path to database file """ super(...
null
v4
[ "dict" ]
str
def v4(v5: dict) -> str: v6 = [] def v7(v8: dict): for (v9, v10) in v8.items(): if isinstance(v10, dict): if v9 != 'entry': v6.append(v9) v7(v10) elif v10: if not v9.startswith('@'): v6.appen...
[ { "name": "v0", "input_types": [ "dict" ], "output_type": "Any", "code": "def v0(v1: dict):\n for (v2, v3) in v1.items():\n if isinstance(v3, dict):\n if v2 != 'entry':\n keys.append(v2)\n v0(v3)\n elif v3:\n if not v2.starts...
[]
[]
17
''' Serve up a fake REST server acting as device REST API ''' import sys import argparse from pathlib import Path import ssl import logging from aiohttp import web import xmltodict def get_filename_from_cmd(cmd_dict: dict) -> str: """Build filename from an xml command""" keys = [] def recursive_items(c...
null
v0
[ "Dict[Hashable, Set[Hashable]]" ]
Any
def v0(v1: Dict[Hashable, Set[Hashable]]): v2 = [] for v3 in range(1, len(v1) + 1): if v3 == 1: v4 = [[k] for v5 in v1.keys()] else: v4 = map(list, itertools.combinations(v1.keys(), v3)) for v6 in v4: v7 = len(v1[v6[0]] if v3 == 1 else set.intersection...
[]
[ "itertools", "pandas" ]
[ "import itertools", "import pandas as pd" ]
12
import itertools import pandas as pd from typing import Dict, Set, Hashable def upset_from_dict_of_sets(inputs: Dict[Hashable, Set[Hashable]]): ''' Given a dictionary of sets, produce input ready for `upsetplot` python package We produce this input by computing set intersections of all relevant combinations of...
null
v17
[ "Any", "str", "Any", "Any" ]
Any
def v17(v18, v19: str, v20=False, v21=False): if v19 in ('mot', 'lab'): v22 = v0 else: raise ValueError('Unknown data type: {}'.format(v19)) return v22(v18, v20, v21)
[ { "name": "v0", "input_types": [ "Any", "Any", "Any" ], "output_type": "Any", "code": "def v0(v1, v2, v3):\n v4 = {1}\n v5 = {2, 7, 8, 12}\n v6 = dict()\n if os.path.isfile(v1):\n with open(v1, 'r') as v7:\n for v8 in v7.readlines():\n ...
[ "os" ]
[ "import os" ]
6
import os from typing import Dict import numpy as np from utils.log import logger def write_results(filename, results_dict: Dict, data_type: str): if not filename: return path = os.path.dirname(filename) if not os.path.exists(path): os.makedirs(path) if data_type in ('mot', 'mcmot', ...
null
v0
[ "moves.Move" ]
None
def v0(self, v1: moves.Move) -> None: v2 = self.current_board v2.apply(v1) self._log.append((v1, v2))
[]
[]
[]
4
import copy from typing import List, Optional, Tuple from . import boards, enums, moves JournalEntry = Tuple[Optional[moves.Move], boards.Board] class Journal: """A journal of all previous Move and Board states.""" def __init__(self, board: boards.Board): """ Create a journal. :par...
null
v0
[ "int", "int" ]
Any
def v0(v1: int, v2: int): v3 = [None] * v1 v4 = [0] * v2 for v5 in range(v1): v3[v5] = copy.deepcopy(v4) return v3
[]
[ "copy" ]
[ "import copy" ]
6
""" Author: Shreck Ye Date: June 16, 2019 Time complexity: O(log(N)) Let's think in the mathematical way. Obviously, the recursion formula represents a linear relationship. By viewing it as a recursion formula of a single vector F_n = (f_n, f_{n + 1})' with a transition matrix M = (0, 1; 1, 1), which is (f_{n + 1}, f_...
null
v6
[ "int" ]
Any
def v6(v7: int): v8 = v0(v7, v7) for v9 in range(v7): v8[v9][v9] = 1 return v8
[ { "name": "v0", "input_types": [ "int", "int" ], "output_type": "Any", "code": "def v0(v1: int, v2: int):\n v3 = [None] * v1\n v4 = [0] * v2\n for v5 in range(v1):\n v3[v5] = copy.deepcopy(v4)\n return v3", "dependencies": [] } ]
[ "copy" ]
[ "import copy" ]
5
""" Author: Shreck Ye Date: June 16, 2019 Time complexity: O(log(N)) Let's think in the mathematical way. Obviously, the recursion formula represents a linear relationship. By viewing it as a recursion formula of a single vector F_n = (f_n, f_{n + 1})' with a transition matrix M = (0, 1; 1, 1), which is (f_{n + 1}, f_...
null
v20
[ "dict", "int", "float", "int" ]
tuple
def v20(v21: dict, v22: int, v23: float=0.25, v24: int=None) -> tuple: v25 = list(v21['train']['var'].keys())[-1] v26 = ['train', 'eval', 'test'] v27 = [int(v22 * (1 - 2 * v23)), int(v22 * v23), int(v22 * v23)] v28 = [] for (v29, (v30, v31)) in enumerate(zip(v26, v27)): if v24 is None: ...
[ { "name": "v0", "input_types": [ "dict", "dict", "int", "int" ], "output_type": "pd.DataFrame", "code": "def v0(v1: dict, v2: dict, v3: int, v4: int=None) -> pd.DataFrame:\n v5 = list(v1.keys())\n v6 = v5[-1]\n v7 = len(v5) - 1\n assert v1[v6]['corr'] is None\...
[ "numpy", "pandas" ]
[ "import numpy as np", "import pandas as pd" ]
13
import numpy as np import pandas as pd import openturns as ot from .conf_file_generation import GENERATION_CONF, post_process_generated_dataset def sample_from_conf( var_conf: dict, corr_conf: dict, n_sample: int, seed: int = None ) -> pd.DataFrame: """ Generate dataset with n_sample form configuration f...
null
v0
[ "Callable", "Any" ]
Any
def v0(self, v1: Callable, v2=False): assert callable(v1) self._filters.append((v1, v2))
[]
[]
[]
3
"""Pipeline class implementing Pipes and Filters pattern. A generic pipeline to process messages efficiently in a pipes-and-filter manner (multiprocessing possible). Inspired, but not copied from https://deparkes.co.uk/2019/12/08/simple-python-pipes-and-filters/ Authors: - Lukas Block - Adrian Raiser Todo:...
null
v0
[ "int" ]
None
def v0(self, v1: int) -> None: self.game_total += 1 self.point_margin += v1
[]
[]
[]
3
from typing import Dict from typing import List import numpy from fbsrankings.domain.model.affiliation import Subdivision from fbsrankings.domain.model.game import Game from fbsrankings.domain.model.game import GameStatus from fbsrankings.domain.model.ranking import Ranking from fbsrankings.domain.model.ranking impor...
null
v0
[ "Union[list, tuple, range, np.ndarray]", "int" ]
Any
def v0(self, v1: Union[list, tuple, range, np.ndarray], v2: int): if v1 is None: v1 = range(v2) else: if isinstance(v1, int): v1 = [v1] if max(v1) > v2: raise RuntimeError(f'{self.name} index cannot be higher than nx ({v2})') v1 = np.array(v1) if not np.is...
[]
[ "numpy" ]
[ "import numpy as np" ]
12
from typing import Any, Union, Callable import biorbd_casadi as biorbd from casadi import horzcat, vertcat, Function, MX, SX import numpy as np from .penalty_node import PenaltyNodeList from ..misc.enums import Node, PlotType, ControlType, ConstraintType, IntegralApproximation from ..misc.mapping import Mapping, BiMa...
null
v0
[ "int" ]
Any
def v0(self, v1: int=1): v2 = self.db.engine if not v2: return None else: return self.db.get_price_policy_by_id(v1)
[]
[]
[]
6
from management.config import config_api_setup from management.database import Database class Price_Policies: """price_policies class model.""" def __init__(self): config, config_file = config_api_setup() config.read(config_file) self.db = Database( connector=config['datab...
null
v0
[ "str", "str", "str" ]
str
def v0(self, v1: str, v2: str, v3: str) -> str: v4 = " SELECT *, CASE WHEN {} '{}' THEN timestamp ELSE NULL END as mark from ({}) as sessionified ".format(v1, v3, v2) v5 = ' SELECT *, MIN(mark) OVER ( PARTITION BY distinct_id , session ORDER BY ...
[]
[]
[]
5
from rest_framework import viewsets, request from rest_framework.response import Response from rest_framework.decorators import action from posthog.models import Event, Filter from posthog.utils import request_to_date_query, dict_from_cursor_fetchall from django.db.models import OuterRef from django.db import connectio...
null
v0
[ "str" ]
str
def v0(self, v1: str) -> str: v2 = 'SELECT \'<\'|| e."tag_name" || \'> \' || e."text" as tag_name_source, e."text" as text_source FROM "posthog_element" e JOIN ( SELECT group_id, MIN("posthog_element"."order") as minOrder FROM "posthog_element" GROUP BY group_id) e2 ON e.order = e2.minOrder AND...
[]
[]
[]
5
from rest_framework import viewsets, request from rest_framework.response import Response from rest_framework.decorators import action from posthog.models import Event, Filter from posthog.utils import request_to_date_query, dict_from_cursor_fetchall from django.db.models import OuterRef from django.db import connectio...
null
v7
[ "List[str]" ]
Any
def v7(v8: List[str]): v9 = [] v10 = [] for v11 in v8: v12 = v0(v11) v9.append(v11) v10.append(v12) return v10
[ { "name": "v0", "input_types": [ "str" ], "output_type": "List[str]", "code": "def v0(v1: str) -> List[str]:\n v2 = []\n v3 = False\n for v4 in range(len(v1)):\n if v3:\n v3 = False\n continue\n v5 = v1[v4]\n if v4 < len(v1) - 1 and v1[v4...
[]
[]
8
import torch import torch.nn as nn import os from common import base_data_path from typing import List import pandas as pd CONTEXT_SIZE = 1 # 1 words to the left, 1 to the right EMDEDDING_DIM = 3 word_to_ix = {} ix_to_word = {} def make_context_vector(context, word_to_ix): idxs = [word_to_ix[w] for w in contex...
null
v0
[]
None
def v0(self, *v1) -> None: if self.number_of_intrastellar_objects() < self.max_objects: for v2 in v1: self.planets_list.append(v2) else: self.error = True
[]
[]
[]
6
import functionality.planets as planets import assets.tools as tools from assets.variables import * # TODO: Also add logger to code and display errors correctly # TODO: Make one pixel correspond to 1/10 au so that acceleration works more realistic class SolarSystem(metaclass=tools.Singleton): """This creates the...
null
v0
[]
None
def v0(self) -> None: for (v1, v2) in enumerate(self.planets_list): (v2.pos_x_real, v2.pos_y_real) = self.planetary_positions()[0][v1] (v2.v_x, v2.v_y) = self.planetary_positions()[1][v1]
[]
[]
[]
4
import functionality.planets as planets import assets.tools as tools from assets.variables import * # TODO: Also add logger to code and display errors correctly # TODO: Make one pixel correspond to 1/10 au so that acceleration works more realistic class SolarSystem(metaclass=tools.Singleton): """This creates the...
null
v0
[]
None
def v0(self) -> None: self.planets_list = [] self.system_time = 0
[]
[]
[]
3
import functionality.planets as planets import assets.tools as tools from assets.variables import * # TODO: Also add logger to code and display errors correctly # TODO: Make one pixel correspond to 1/10 au so that acceleration works more realistic class SolarSystem(metaclass=tools.Singleton): """This creates the...
null
v0
[]
None
def v0(self) -> None: if not self._released: self._notify_content() if self._closed: return self._closed = True if self._loop is None or self._loop.is_closed(): return if self._connection is not None: self._connection.close() self._connection = None self._...
[]
[]
[]
12
import asyncio import codecs import dataclasses import functools import io import re import sys import traceback import warnings from hashlib import md5, sha1, sha256 from http.cookies import CookieError, Morsel, SimpleCookie from types import MappingProxyType, TracebackType from typing import ( TYPE_CHECKING, ...
null
v0
[]
None
def v0(self) -> None: if self._writer is not None: if not self.loop.is_closed(): self._writer.cancel() self._writer = None
[]
[]
[]
5
import asyncio import codecs import dataclasses import functools import io import re import sys import traceback import warnings from hashlib import md5, sha1, sha256 from http.cookies import CookieError, Morsel, SimpleCookie from types import MappingProxyType, TracebackType from typing import ( TYPE_CHECKING, ...
null
v0
[]
None
def v0(self) -> None: if self._closed: return if self._connection is not None: if self._connection.protocol is not None and self._connection.protocol.upgraded: return self._connection.release() self._connection = None self._closed = True self._cleanup_writer()
[]
[]
[]
10
import asyncio import codecs import dataclasses import functools import io import re import sys import traceback import warnings from hashlib import md5, sha1, sha256 from http.cookies import CookieError, Morsel, SimpleCookie from types import MappingProxyType, TracebackType from typing import ( TYPE_CHECKING, ...
null
v0
[]
None
def v0(self) -> None: if self._writer is not None: self._writer.cancel() self._writer = None self._session = None
[]
[]
[]
5
import asyncio import codecs import dataclasses import functools import io import re import sys import traceback import warnings from hashlib import md5, sha1, sha256 from http.cookies import CookieError, Morsel, SimpleCookie from types import MappingProxyType, TracebackType from typing import ( TYPE_CHECKING, ...
null
v0
[]
None
async def v0(self) -> None: if self._writer is not None: try: await self._writer finally: self._writer = None self.release()
[]
[]
[]
7
import asyncio import codecs import dataclasses import functools import io import re import sys import traceback import warnings from hashlib import md5, sha1, sha256 from http.cookies import CookieError, Morsel, SimpleCookie from types import MappingProxyType, TracebackType from typing import ( TYPE_CHECKING, ...
null
v0
[ "Optional[str]", "str" ]
str
async def v0(self, v1: Optional[str]=None, v2: str='strict') -> str: if self._body is None: await self.read() if v1 is None: v1 = self.get_encoding() return self._body.decode(v1, errors=v2)
[]
[]
[]
6
import asyncio import codecs import dataclasses import functools import io import re import sys import traceback import warnings from hashlib import md5, sha1, sha256 from http.cookies import CookieError, Morsel, SimpleCookie from types import MappingProxyType, TracebackType from typing import ( TYPE_CHECKING, ...
null
v0
[ "np.ndarray", "np.ndarray", "bool", "bool", "bool", "bool", "bool", "float", "float", "float" ]
Tuple[np.ndarray, np.ndarray]
def v0(v1: np.ndarray, v2: np.ndarray, v3: bool=True, v4: bool=True, v5: bool=False, v6: bool=False, v7: bool=True, v8: float=0.25, v9: float=0.25, v10: float=0.67) -> Tuple[np.ndarray, np.ndarray]: v11 = sum((1.0 for v12 in (v3, v4, v5, v6, v7) if v12)) v13 = v10 ** (1.0 / v11) if v3 and np.random.random()...
[]
[ "numpy" ]
[ "import numpy as np" ]
25
import os from collections import OrderedDict from typing import Tuple, List, Callable from fs_s3fs import S3FS import numpy as np import pandas as pd import torch from torch.utils.data import Dataset from skimage.exposure import match_histograms from datetime import datetime from eolearn.core import EOPatch def a...
null
v0
[ "np.ndarray", "int", "bool" ]
np.ndarray
def v0(v1: np.ndarray, v2: int=16, v3: bool=True) -> np.ndarray: v4 = v2 - len(v1) if v4 < 0: raise ValueError(f'Can not pad when length of features: {len(v1)} is longer than k: {v2}') (v5, v6, v7, v8) = v1.shape if v3: v1 = np.concatenate((np.zeros(shape=(v4, v6, v7, v8)), v1)) else...
[]
[ "numpy" ]
[ "import numpy as np" ]
10
import os from collections import OrderedDict from typing import Tuple, List, Callable from fs_s3fs import S3FS import numpy as np import pandas as pd import torch from torch.utils.data import Dataset from skimage.exposure import match_histograms from datetime import datetime from eolearn.core import EOPatch def a...
null
v0
[ "Union[str, Type]", "Callable", "Any" ]
None
def v0(self, v1: Union[str, Type], v2: Callable, v3='overwrite') -> None: if isinstance(v1, str): self._register(self._funcs, name=v1, func=v2, on_dup=v3) else: self._register(self._type_funcs, name=v1, func=v2, on_dup=v3)
[]
[]
[]
5
from typing import Any, Callable, Dict, Optional, Type, Union from fugue.execution.execution_engine import ExecutionEngine, SQLEngine from fugue.execution.native_execution_engine import NativeExecutionEngine from triad.utils.convert import to_instance from triad import assert_or_throw class _ExecutionEngineFactory(o...
null
v0
[ "Dict[Any, Callable]", "Any", "Callable", "Any" ]
None
def v0(self, v1: Dict[Any, Callable], v2: Any, v3: Callable, v4='overwrite') -> None: if v2 not in v1: v1[v2] = v3 if v4 in ['raise', 'throw']: raise KeyError(f'{v2} is already registered') if v4 == 'overwrite': v1[v2] = v3 return if v4 == 'ignore': return rai...
[]
[]
[]
11
from typing import Any, Callable, Dict, Optional, Type, Union from fugue.execution.execution_engine import ExecutionEngine, SQLEngine from fugue.execution.native_execution_engine import NativeExecutionEngine from triad.utils.convert import to_instance from triad import assert_or_throw class _ExecutionEngineFactory(o...
null
v0
[ "str" ]
str
def v0(self, v1: str) -> str: v2 = self._prepare_sequence_in(v1).view(1, -1) v3 = [len(v1) + 1] v4 = self._network(v2, v3, None, 0) if v4.size(0) == 0: v5 = ['<PAD>'] else: v6 = torch.argmax(v4.squeeze(1), 1).cpu().detach().numpy() v5 = [self._ix_to_target_char[t] for v7 in v...
[]
[ "torch" ]
[ "import torch", "import torch.nn as nn", "import torch.nn.functional as F" ]
10
# -*- coding: utf-8 -*- """ Romanization of Thai words based on machine-learnt engine ("thai2rom") """ import random import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pythainlp.corpus import get_corpus_path device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu...
null
v0
[ "set", "str", "str" ]
set
def v0(v1: set, v2: str, v3: str='::') -> set: v4 = set() for v5 in v1: v6 = v2.split(v3) v7 = v5.split(v3) v6.reverse() v7.reverse() v8 = len(v6) v7 = v7[:v8] if v6 == v7: v4.add(v5) return v4
[]
[]
[]
12
# -*- coding: utf-8 -*- import os import re import requests import shutil import time import xml.etree.ElementTree as ET import urllib.parse from collections import namedtuple from dateutil.parser import parse as parsedate from docutils import nodes, utils from sphinx.util.nodes import split_explicit_title from sphin...
null
v9
[ "str" ]
str
def v9(self, v10: str) -> str: if self._mapping.get(v10): return v10 v11 = v0(self._mapping.keys(), v10) if len(v11) == 1: return list(v11)[0] v12 = {s for v13 in v11 if self._mapping[v13].kind == 'class'} if len(v12) == 1: return list(v12)[0] v14 = {v13 for v13 in v11 if...
[ { "name": "v0", "input_types": [ "set", "str", "str" ], "output_type": "set", "code": "def v0(v1: set, v2: str, v3: str='::') -> set:\n v4 = set()\n for v5 in v1:\n v6 = v2.split(v3)\n v7 = v5.split(v3)\n v6.reverse()\n v7.reverse()\n v8...
[]
[]
15
# -*- coding: utf-8 -*- import os import re import requests import shutil import time import xml.etree.ElementTree as ET import urllib.parse from collections import namedtuple from dateutil.parser import parse as parsedate from docutils import nodes, utils from sphinx.util.nodes import split_explicit_title from sphin...
null
v0
[ "Dict" ]
Any
def v0(self, v1: Dict): v1 = {'Целесообразность затрат на содержание техники.': self._visualise_one_day_cost} print('[ENTER] - выйти.\nВыберете вид отчета:') v2 = super().choise_from_list(v1, none_option=True) if v2: v1[v2]()
[]
[]
[]
6
#!/usr/bin/env python3 """Visualise statistic by machine economic.""" from __future__ import annotations import pandas as pd from matplotlib import pyplot as plt from typing import Dict from .mechanic_report import MechReports from .administration.logger_cfg import Logs from .support_modules.custom_exceptions impor...
null
v0
[ "discord.TextChannel", "str" ]
None
async def v0(self, v1: discord.TextChannel, v2: str) -> None: async with self.pool.acquire() as v3: async with v3.cursor() as v4: assert not await self._read(v4, v1, v2), '既に設定されています。' await v4.execute(f'SELECT * FROM {self.TABLE} WHERE GuildID = %s;', (v1.guild.id,)) ass...
[]
[]
[]
7
# RT - Twitter from typing import TYPE_CHECKING, Union, Dict, Tuple, List from discord.ext import commands import discord from tweepy.asynchronous import AsyncStream from tweepy import API, OAuthHandler from tweepy.errors import NotFound from tweepy.models import Status from jishaku.functools import executor_functi...
null
v0
[ "discord.TextChannel", "str" ]
None
async def v0(self, v1: discord.TextChannel, v2: str) -> None: async with self.pool.acquire() as v3: async with v3.cursor() as v4: assert await self._read(v4, v1, v2), 'その設定はありません。' await v4.execute(f'DELETE FROM {self.TABLE} WHERE ChannelID = %s AND UserName = %s;', (v1.id, v2))
[]
[]
[]
5
# RT - Twitter from typing import TYPE_CHECKING, Union, Dict, Tuple, List from discord.ext import commands import discord from tweepy.asynchronous import AsyncStream from tweepy import API, OAuthHandler from tweepy.errors import NotFound from tweepy.models import Status from jishaku.functools import executor_functi...
null
v0
[]
List[Tuple[int, str]]
async def v0(self) -> List[Tuple[int, str]]: async with self.pool.acquire() as v1: async with v1.cursor() as v2: await self._update_users(v2)
[]
[]
[]
4
# RT - Twitter from typing import TYPE_CHECKING, Union, Dict, Tuple, List from discord.ext import commands import discord from tweepy.asynchronous import AsyncStream from tweepy import API, OAuthHandler from tweepy.errors import NotFound from tweepy.models import Status from jishaku.functools import executor_functi...
null
v0
[ "bool" ]
Union[type, 'pyarrow.lib.Schema']
def v0(self, v1: bool=False) -> Union[type, 'pyarrow.lib.Schema']: if not self._executed[0]: self._schema = self._peek().schema(v1) return self._schema
[]
[]
[]
4
import inspect import itertools import logging import time from typing import ( Any, Callable, List, Iterator, Iterable, Generic, Union, Optional, TYPE_CHECKING, ) import ray from ray.data.context import DatasetContext from ray.data.dataset import Dataset, T, U from ray.data.impl.pi...
null
v0
[ "int" ]
None
def v0(self, v1: int=10) -> None: v2 = None for (v3, v4) in enumerate(self.iter_datasets()): if v4._get_epoch() != v2: v2 = v4._get_epoch() print('------ Epoch {} ------'.format(v2)) print('=== Window {} ==='.format(v3)) v4.show(v1)
[]
[]
[]
8
import inspect import itertools import logging import time from typing import ( Any, Callable, List, Iterator, Iterable, Generic, Union, Optional, TYPE_CHECKING, ) import ray from ray.data.context import DatasetContext from ray.data.dataset import Dataset, T, U from ray.data.impl.pi...
null
v3
[ "str" ]
Any
def v3(v4: str): def v5(*v6, **v7): raise DeprecationWarning('`{}` has been renamed to `{}_each_window`.'.format(v4, v4)) return v5
[ { "name": "v0", "input_types": [], "output_type": "Any", "code": "def v0(self, *v1, **v2):\n return delegate(self, *v1, **v2)", "dependencies": [] } ]
[]
[]
5
import inspect import itertools import logging import time from typing import ( Any, Callable, List, Iterator, Iterable, Generic, Union, Optional, TYPE_CHECKING, ) import ray from ray.data.context import DatasetContext from ray.data.dataset import Dataset, T, U from ray.data.impl.pi...
null
v3
[ "'AsyncSyncPath'", "bool" ]
Optional[str]
async def v3(self, v4: 'AsyncSyncPath', v5: bool=False) -> Optional[str]: v6 = str(v4) if not v6: return os.getcwd() v7: Optional[str] = None if v0 is not None: if v5: return self._ext_to_normal(await v0(v6)) else: v8: List[str] = [] while True: ...
[ { "name": "v0", "input_types": [], "output_type": "Any", "code": "async def v0(*v1, **v2):\n raise ImportError('_getfinalpathname() requires a Windows/NT platform')", "dependencies": [] } ]
[ "os" ]
[ "import os" ]
22
from __future__ import annotations from pathlib import _PosixFlavour, _WindowsFlavour from typing import Optional, Callable, Awaitable, Dict, List, TYPE_CHECKING from errno import EINVAL import os import sys from aiopath.wrap import func_to_async_func as wrap_async try: from pathlib import _getfinalpathname _a...
null
v0
[ "Mapping[str, Union[int, Mapping[str, int]]]" ]
Any
def v0(v1: Mapping[str, Union[int, Mapping[str, int]]]): if not isinstance(v1, collections.Mapping): raise TypeError('Not a valid power-levels content: %r' % (v1,)) v2 = {} for (v3, v4) in v1.items(): if isinstance(v4, int): v2[v3] = v4 continue if isinstance(...
[]
[ "collections" ]
[ "import collections" ]
17
# -*- coding: utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
null
v8
[]
List[smart_contract_model.SmartContractModel]
def v8() -> List[smart_contract_model.SmartContractModel]: v6() v9 = [] for v10 in v2(): v11 = v0(v10) if v11.execution_order == 'serial': v9.append(v11) return v9
[ { "name": "v0", "input_types": [ "str" ], "output_type": "smart_contract_model.SmartContractModel", "code": "def v0(v1: str) -> smart_contract_model.SmartContractModel:\n return smart_contract_model.new_from_at_rest(storage.get_json_from_object(f'{FOLDER}/{v1}/metadata.json'))", "de...
[]
[]
8
# Copyright 2020 Dragonchain, Inc. # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # 6. Tr...
null
v4
[ "str" ]
int
def v4(self, v5: str) -> int: if len(v5) == 0: return 0 self.cache = {} self.cache[''] = 1 def v6(v7): if v7 in self.cache: return self.cache[v7] if v7[0] == '0': return 0 if len(v7) == 1: return 1 v8 = v6(v7[1:]) v9 = ...
[ { "name": "v0", "input_types": [ "Any" ], "output_type": "Any", "code": "def v0(v1):\n if v1 in self.cache:\n return self.cache[v1]\n if v1[0] == '0':\n return 0\n if len(v1) == 1:\n return 1\n v2 = v0(v1[1:])\n v3 = int(v1[:2])\n if 0 < v3 <= 26:\n ...
[]
[]
20
# Space: O(n) # Time: O(n) class Solution: def numDecodings(self, s: str) -> int: if len(s) == 0: return 0 self.cache = {} self.cache[''] = 1 def recursive(string): if string in self.cache: return self.cache[string] if string[0] == '0': return 0 ...
null
v5
[ "str", "str" ]
Optional[str]
def v5(v6: str, v7: str) -> Optional[str]: try: v8 = v0(v6, v7) + 1 except ValueError: return None v9 = v6[v8:] if not v9: return None return v9
[ { "name": "v0", "input_types": [ "str", "str" ], "output_type": "int", "code": "def v0(v1: str, v2: str) -> int:\n for (v3, v4) in enumerate(v1):\n if v4 != '-':\n continue\n if canonicalize_name(v1[:v3]) == v2:\n return v3\n raise ValueError...
[]
[]
9
"""Routines related to PyPI, indexes""" # The following comment should be removed at some point in the future. # mypy: strict-optional=False import enum import functools import itertools import logging import re from typing import FrozenSet, Iterable, List, Optional, Set, Tuple, Union from pip._vendor.packaging impo...
null
v0
[ "List[str]", "Dict" ]
None
def v0(self, v1: List[str], v2: Dict) -> None: for v3 in v1: self.design_choices[v3] = v2['design_choices'][v3]
[]
[]
[]
3
""" design_choice ~~~~~~~~~~~~~~ IMPORTANT: This is a straightforward adaptation of sphinx's todo extension done by search/replace. Allow design_choices to be inserted into your documentation. Inclusion of design_choices can be switched of by a configuration variable. The design_choice_li...
null
v0
[ "Any", "Any", "str" ]
Any
def v0(self, v1, v2, v3: str=None): v1 = super().validate_and_parse_config(v1, v2, v3) v4 = self.machine.get_platform_sections('switches', getattr(v1, 'platform', None)) v1['platform_settings'] = v4.validate_switch_section(self, v1.get('platform_settings', None)) self._configure_device_logging(v1) r...
[]
[]
[]
6
"""Contains the Switch parent class.""" import asyncio from functools import partial from mpf.core.device_monitor import DeviceMonitor from mpf.core.machine import MachineController from mpf.core.system_wide_device import SystemWideDevice from mpf.core.utility_functions import Util from mpf.core.platform import Switch...
null
v0
[ "str" ]
tuple
def v0(v1: str) -> tuple: if not isinstance(v1, str): raise ValueError v2 = re.split('[.?!]', v1) v3 = [] for v4 in v2: v5 = re.sub('[^a-z \\n]', '', v4.lower()).split() if v5: v3 += v5 + ['<END>'] return tuple(v3)
[]
[ "re" ]
[ "import re" ]
10
""" Lab 4 """ import re from ngrams.ngram_trie import NGramTrie def tokenize_by_sentence(text: str) -> tuple: if not isinstance(text, str): raise ValueError sents = re.split(r'[.?!]', text) tokenized_sent = [] for sent in sents: tokens = re.sub(r'[^a-z \n]', '', sent.lower()).split()...
null
v0
[ "str" ]
Any
def v0(self, v1: str): if not isinstance(v1, str) or not v1: raise ValueError if v1 not in self.storage: self.storage[v1] = len(self.storage) + 1 return self.storage[v1]
[]
[]
[]
6
""" Lab 4 """ import re from ngrams.ngram_trie import NGramTrie def tokenize_by_sentence(text: str) -> tuple: if not isinstance(text, str): raise ValueError sents = re.split(r'[.?!]', text) tokenized_sent = [] for sent in sents: tokens = re.sub(r'[^a-z \n]', '', sent.lower()).split()...
null
v0
[ "str" ]
int
def v0(self, v1: str) -> int: if not isinstance(v1, str) or not v1: raise ValueError if v1 not in self.storage: raise KeyError return self.storage[v1]
[]
[]
[]
6
""" Lab 4 """ import re from ngrams.ngram_trie import NGramTrie def tokenize_by_sentence(text: str) -> tuple: if not isinstance(text, str): raise ValueError sents = re.split(r'[.?!]', text) tokenized_sent = [] for sent in sents: tokens = re.sub(r'[^a-z \n]', '', sent.lower()).split()...
null
v0
[ "int" ]
str
def v0(self, v1: int) -> str: if not isinstance(v1, int): raise ValueError for (v2, v3) in self.storage.items(): if v3 == v1: return v2 raise KeyError
[]
[]
[]
7
""" Lab 4 """ import re from ngrams.ngram_trie import NGramTrie def tokenize_by_sentence(text: str) -> tuple: if not isinstance(text, str): raise ValueError sents = re.split(r'[.?!]', text) tokenized_sent = [] for sent in sents: tokens = re.sub(r'[^a-z \n]', '', sent.lower()).split()...
null
v0
[ "tuple" ]
Any
def v0(self, v1: tuple): if not isinstance(v1, tuple): raise ValueError for v2 in v1: self._put_word(v2)
[]
[]
[]
5
""" Lab 4 """ import re from ngrams.ngram_trie import NGramTrie def tokenize_by_sentence(text: str) -> tuple: if not isinstance(text, str): raise ValueError sents = re.split(r'[.?!]', text) tokenized_sent = [] for sent in sents: tokens = re.sub(r'[^a-z \n]', '', sent.lower()).split()...
null
v0
[ "tuple" ]
tuple
def v0(self, v1: tuple) -> tuple: if not isinstance(v1, tuple): raise ValueError v2 = self.sent_is(v1) for v3 in range(20): v2.append(self._generate_next_word(v1)) v1 = tuple(list(v1) + v2)[-len(v1):] if v2[-1] == self._word_storage.get_id('<END>'): return tuple(v...
[]
[]
[]
11
""" Lab 4 """ import re from ngrams.ngram_trie import NGramTrie def tokenize_by_sentence(text: str) -> tuple: if not isinstance(text, str): raise ValueError sents = re.split(r'[.?!]', text) tokenized_sent = [] for sent in sents: tokens = re.sub(r'[^a-z \n]', '', sent.lower()).split()...
null
v0
[ "tuple", "int" ]
tuple
def v0(self, v1: tuple, v2: int) -> tuple: if not isinstance(v1, tuple) or not isinstance(v2, int) or isinstance(v2, bool): raise ValueError v3 = [] for v4 in range(v2): v5 = self._generate_sentence(v1) v3.extend(v5) v1 = tuple(v3[-len(v1):]) return tuple(v3)
[]
[]
[]
9
""" Lab 4 """ import re from ngrams.ngram_trie import NGramTrie def tokenize_by_sentence(text: str) -> tuple: if not isinstance(text, str): raise ValueError sents = re.split(r'[.?!]', text) tokenized_sent = [] for sent in sents: tokens = re.sub(r'[^a-z \n]', '', sent.lower()).split()...
null
v0
[ "int", "tuple" ]
float
def v0(self, v1: int, v2: tuple) -> float: v3 = [isinstance(v1, int), isinstance(v2, tuple)] if not all(v3) or v1 not in self._word_storage.storage.values() or len([wrd for v4 in v2 if v4 in self._word_storage.storage.values()]) != len(v2): raise ValueError v5 = 0 v6 = 0 v7 = self._n_gram_tr...
[]
[]
[]
17
""" Lab 4 """ import re from ngrams.ngram_trie import NGramTrie def tokenize_by_sentence(text: str) -> tuple: if not isinstance(text, str): raise ValueError sents = re.split(r'[.?!]', text) tokenized_sent = [] for sent in sents: tokens = re.sub(r'[^a-z \n]', '', sent.lower()).split()...
null
v0
[ "Tuple[int, int]", "Tuple[int, int]" ]
np.array
def v0(self, v1: Tuple[int, int], v2: Tuple[int, int]) -> np.array: v2 = (np.min([v2[0], self.color_map.shape[0] - v1[0]]), np.min([v2[1], self.color_map.shape[1] - v1[1]])) return self.color_map[v1[0]:v1[0] + v2[0], v1[1]:v1[1] + v2[1]]
[]
[ "numpy" ]
[ "import numpy as np" ]
3
# This file defines the back end of the Tetris game # # GameState is the base class of GameClient. # # GameClient.Run() will start two threads: # - _ProcessActions: Process the action list every x seconds # - _AutoDrop: Auto drops the current piece. # # GameClient: # - current piece # - held piece # - piece list...
null
v0
[ "Tuple[int, int]", "int", "np.array" ]
Any
def v0(self, v1: Tuple[int, int], v2: int, v3: np.array=None): (v4, v5) = v1 v6 = self.bit_map.copy() if v3 is None or v3 is self.color_map: v3 = self.color_map v6 = self.bit_map v3[v4, v5] = v2 v7 = 0 if v2 == 0 else 1 v8 = self.width + self.map_side_padding - 1 - v5 v6[v4] ...
[]
[]
[]
10
# This file defines the back end of the Tetris game # # GameState is the base class of GameClient. # # GameClient.Run() will start two threads: # - _ProcessActions: Process the action list every x seconds # - _AutoDrop: Auto drops the current piece. # # GameClient: # - current piece # - held piece # - piece list...
null
v0
[ "List[actions.Action]" ]
Any
def v0(self, v1: List[actions.Action]): if self.is_gameover: return if len(v1) > 30: print('len:', len(v1)) v1 = v1[-30:] for v2 in v1: if self.action_list.qsize() > 50: break self.action_list.put(v2)
[]
[]
[]
10
# This file defines the back end of the Tetris game # # GameState is the base class of GameClient. # # GameClient.Run() will start two threads: # - _ProcessActions: Process the action list every x seconds # - _AutoDrop: Auto drops the current piece. # # GameClient: # - current piece # - held piece # - piece list...
null
v0
[ "List[v1.Action]", "Any" ]
Any
def v0(self, v1: List[v1.Action], v2=True): for v3 in v1: self.ProcessAction(v3, post_processing=v2)
[]
[]
[]
3
# This file defines the back end of the Tetris game # # GameState is the base class of GameClient. # # GameClient.Run() will start two threads: # - _ProcessActions: Process the action list every x seconds # - _AutoDrop: Auto drops the current piece. # # GameClient: # - current piece # - held piece # - piece list...
null
v0
[ "actions.Action", "Any" ]
Any
def v0(self, v1: actions.Action, v2=True): if self.is_gameover: return if v1.swap: self.Swap() self.Rotate(v1.rotation) self.Move(v1, post_processing=v2)
[]
[]
[]
7
# This file defines the back end of the Tetris game # # GameState is the base class of GameClient. # # GameClient.Run() will start two threads: # - _ProcessActions: Process the action list every x seconds # - _AutoDrop: Auto drops the current piece. # # GameClient: # - current piece # - held piece # - piece list...
null
v0
[ "int" ]
Any
def v0(self, v1: int=0): self.level = v1 v2 = min(len(self.interval_decrease), self.level) self._current_spawn_interval = max(10, self._init_spawn_interval - self.interval_decrease[v2])
[]
[]
[]
4
# This file defines the back end of the Tetris game # # GameState is the base class of GameClient. # # GameClient.Run() will start two threads: # - _ProcessActions: Process the action list every x seconds # - _AutoDrop: Auto drops the current piece. # # GameClient: # - current piece # - held piece # - piece list...
null
v0
[ "int" ]
Any
def v0(self, v1: int=1): self.level += v1 self.SetLevel(self.level)
[]
[]
[]
3
# This file defines the back end of the Tetris game # # GameState is the base class of GameClient. # # GameClient.Run() will start two threads: # - _ProcessActions: Process the action list every x seconds # - _AutoDrop: Auto drops the current piece. # # GameClient: # - current piece # - held piece # - piece list...
null
v0
[ "shape.Shape" ]
Any
def v0(self, v1: shape.Shape=None): if self._PrePutPiece(v1): self._PostPutPiece(v1) return True else: return False
[]
[]
[]
6
# This file defines the back end of the Tetris game # # GameState is the base class of GameClient. # # GameClient.Run() will start two threads: # - _ProcessActions: Process the action list every x seconds # - _AutoDrop: Auto drops the current piece. # # GameClient: # - current piece # - held piece # - piece list...
null
v0
[ "shape.Shape", "np.array" ]
Any
def v0(self, v1: shape.Shape=None, v2: np.array=None): try: if not v1: self.mutex_current_piece.acquire() v1 = self.current_piece if v2 is None: v2 = self.color_map if not self.CheckValidity(v1): return False for (v3, v4) in v1.GetShape...
[]
[]
[]
15
# This file defines the back end of the Tetris game # # GameState is the base class of GameClient. # # GameClient.Run() will start two threads: # - _ProcessActions: Process the action list every x seconds # - _AutoDrop: Auto drops the current piece. # # GameClient: # - current piece # - held piece # - piece list...
null
v0
[ "shape.Shape" ]
Any
def v0(self, v1: shape.Shape=None): if v1 is not None: self.last_put_piece = v1 else: self.last_put_piece = self.current_piece self._LineClear() if v1 is None: self._TakePieceFromList() self.CheckGameOver() self._ResetLockTime() self._SendAttack() self.can_swap = ...
[]
[]
[]
13
# This file defines the back end of the Tetris game # # GameState is the base class of GameClient. # # GameClient.Run() will start two threads: # - _ProcessActions: Process the action list every x seconds # - _AutoDrop: Auto drops the current piece. # # GameClient: # - current piece # - held piece # - piece list...
null
v0
[ "shape.Shape" ]
bool
def v0(self, v1: shape.Shape=None) -> bool: if not v1: self._TakePieceFromList() else: self.current_piece = v1.copy() return self.CheckValidity(self.current_piece)
[]
[]
[]
6
# This file defines the back end of the Tetris game # # GameState is the base class of GameClient. # # GameClient.Run() will start two threads: # - _ProcessActions: Process the action list every x seconds # - _AutoDrop: Auto drops the current piece. # # GameClient: # - current piece # - held piece # - piece list...
null
v0
[ "shape.Shape", "Tuple[int, int]" ]
Any
def v0(self, v1: shape.Shape, v2: Tuple[int, int]=(0, 0)): (v3, v4, v5) = (v1.x, v1.y, v1.state) v1.x += v2[0] v1.y += v2[1] v6 = self.bit_map[v1.x:v1.x + 4] v7 = self.width - v1.y v8 = v1.GetBitMap().astype(self.dtype) v9 = v8 << v7 v10 = v6 & v9 v11 = v10 == 0 (v1.x, v1.y, v1.s...
[]
[ "numpy" ]
[ "import numpy as np" ]
12
# This file defines the back end of the Tetris game # # GameState is the base class of GameClient. # # GameClient.Run() will start two threads: # - _ProcessActions: Process the action list every x seconds # - _AutoDrop: Auto drops the current piece. # # GameClient: # - current piece # - held piece # - piece list...
null
v3
[ "Any", "Any", "Any", "Any" ]
torch.Tensor
def v3(v4, v5, v6, v7=False) -> torch.Tensor: if v7: return torch.ones(*v4, dtype=v0(v5, v6), device=v6) if not (v5.is_floating_point or v5.is_complex): v8 = torch.randint(0, 10, v4, device=v6) if v5 != torch.uint8: v8 = v8 - 5 return v8.to(v0(v5, v6)) if v5 == to...
[ { "name": "v0", "input_types": [ "Any", "Any" ], "output_type": "Any", "code": "def v0(v1, v2):\n if v2 == 'cpu' and v1 in {torch.half, torch.bfloat16}:\n return torch.float\n return v1", "dependencies": [] } ]
[ "torch" ]
[ "import torch", "from torch._six import inf, nan", "from torch.testing._internal.common_utils import TestCase, iter_indices, TEST_WITH_ASAN, run_tests, torch_to_numpy_dtype_dict, make_tensor, TEST_SCIPY, set_default_dtype", "from torch.testing._internal.common_device_type import instantiate_device_type_tests,...
13
import torch import numpy as np import itertools from itertools import product import math import random import unittest import warnings import operator from functools import partial from torch._six import inf, nan from torch.testing._internal.common_utils import ( TestCase, iter_indices, TEST_WITH_ASAN, run_test...
null
v6
[ "nn.Module" ]
Any
def v6(v7: nn.Module): def v8(v9): if isinstance(v9, (nn.Conv1d, nn.Conv2d, nn.Linear)): v9.weight.data = v9.weight.data.half() if v9.bias is not None: v9.bias.data = v9.bias.data.half() if isinstance(v9, nn.MultiheadAttention): for v10 in [*[f'{s...
[ { "name": "v0", "input_types": [ "Any" ], "output_type": "Any", "code": "def v0(v1):\n if isinstance(v1, (nn.Conv1d, nn.Conv2d, nn.Linear)):\n v1.weight.data = v1.weight.data.half()\n if v1.bias is not None:\n v1.bias.data = v1.bias.data.half()\n if isinstanc...
[ "torch" ]
[ "from torch.nn.modules.activation import GELU, ReLU", "import torch", "import torch.nn as nn", "from torch.nn import functional as F", "from torch.autograd import Variable" ]
18
# from code.transformer_vid.utils import convert_weights # import rotary_embedding_torch from torch.nn.modules.activation import GELU, ReLU # from data.OneCombo3.trainer import TrainerConfig import math import numpy as np import itertools import logging import torch import torch.nn as nn from torch.nn import functiona...
null
v0
[ "int", "Any" ]
Any
def v0(self, v1: int, v2=None): v3 = torch.rand(1, v1) v4 = round(0.75 * v1) v5 = torch.topk(v3, v4, largest=False)[0][:, -1:] v6 = v3 <= v5 v7 = torch.where(v6, torch.tensor(1), torch.tensor(0)).repeat(v1, 1) v7 = v7.float().masked_fill(v7 == 0, float('-inf')).masked_fill(v7 == 1, float(0.0)) ...
[]
[ "torch" ]
[ "from torch.nn.modules.activation import GELU, ReLU", "import torch", "import torch.nn as nn", "from torch.nn import functional as F", "from torch.autograd import Variable" ]
8
# from code.transformer_vid.utils import convert_weights # import rotary_embedding_torch from torch.nn.modules.activation import GELU, ReLU # from data.OneCombo3.trainer import TrainerConfig import math import numpy as np import itertools import logging import torch import torch.nn as nn from torch.nn import functiona...
null
v0
[ "int", "Any" ]
Any
def v0(self, v1: int, v2=None): v3 = (torch.triu(torch.ones(v1, v1), diagonal=0) == 1).transpose(0, 1) v3 = v3.float().masked_fill(v3 == 0, float('-inf')).masked_fill(v3 == 1, float(0.0)) return v3
[]
[ "torch" ]
[ "from torch.nn.modules.activation import GELU, ReLU", "import torch", "import torch.nn as nn", "from torch.nn import functional as F", "from torch.autograd import Variable" ]
4
# from code.transformer_vid.utils import convert_weights # import rotary_embedding_torch from torch.nn.modules.activation import GELU, ReLU # from data.OneCombo3.trainer import TrainerConfig import math import numpy as np import itertools import logging import torch import torch.nn as nn from torch.nn import functiona...
null
v0
[ "int", "Any" ]
Any
def v0(self, v1: int, v2=None): v3 = torch.zeros(1, v1, dtype=torch.bool) return v3
[]
[ "torch" ]
[ "from torch.nn.modules.activation import GELU, ReLU", "import torch", "import torch.nn as nn", "from torch.nn import functional as F", "from torch.autograd import Variable" ]
3
# from code.transformer_vid.utils import convert_weights # import rotary_embedding_torch from torch.nn.modules.activation import GELU, ReLU # from data.OneCombo3.trainer import TrainerConfig import math import numpy as np import itertools import logging import torch import torch.nn as nn from torch.nn import functiona...
null
v0
[ "str", "bool" ]
typing.List[str]
def v0(self, v1: str, v2: bool=False) -> typing.List[str]: v3 = v1.lower().encode(self.encoding) v4 = [item_value.decode(self.encoding) for (v5, v6) in self._list if v5 == v3] if not v2: return v4 v7 = [] for v8 in v4: v7.extend([item.strip() for v9 in v8.split(',')]) return v7
[]
[]
[]
9
import cgi import datetime import email.message import json as jsonlib import typing import urllib.request from collections.abc import MutableMapping from http.cookiejar import Cookie, CookieJar from urllib.parse import parse_qsl, urlencode import chardet import rfc3986 from .config import USER_AGENT from .decoders i...
null
v0
[]
bytes
async def v0(self) -> bytes: if not hasattr(self, '_content'): self._content = b''.join([part async for v1 in self.aiter_bytes()]) return self._content
[]
[]
[]
4
import cgi import contextlib import datetime import email.message import json as jsonlib import typing import urllib.request from collections.abc import MutableMapping from http.cookiejar import Cookie, CookieJar from urllib.parse import parse_qsl, quote, unquote, urlencode import rfc3986 import rfc3986.exceptions fr...
null
v0
[]
typing.AsyncIterator[bytes]
async def v0(self) -> typing.AsyncIterator[bytes]: if hasattr(self, '_content'): yield self._content else: async for v1 in self.aiter_raw(): yield self.decoder.decode(v1) yield self.decoder.flush()
[]
[]
[]
7
import cgi import datetime import email.message import json as jsonlib import typing import urllib.request import warnings from collections.abc import MutableMapping from http.cookiejar import Cookie, CookieJar from urllib.parse import parse_qsl, urlencode import chardet import rfc3986 from .__version__ import __vers...
null
v0
[]
None
def v0(self) -> None: if not self.is_closed: self.is_closed = True if self._on_close is not None: self._on_close(self)
[]
[]
[]
5
import cgi import contextlib import datetime import email.message import json as jsonlib import typing import urllib.request from collections.abc import MutableMapping from http.cookiejar import Cookie, CookieJar from urllib.parse import parse_qsl, quote, unquote, urlencode import rfc3986 import rfc3986.exceptions fr...
null
v43
[ "v0" ]
None
def v43(self, v44: v0) -> None: assert v44.request is not None v45 = self._CookieCompatResponse(v44) v46 = self._CookieCompatRequest(v44.request) self.jar.extract_cookies(v45, v46)
[]
[]
[]
5
import cgi import datetime import email.message import json as jsonlib import typing import urllib.request from collections.abc import MutableMapping from http.cookiejar import Cookie, CookieJar from urllib.parse import parse_qsl, urlencode import chardet import rfc3986 from .config import USER_AGENT from .decoders i...
[ "class v0:\n\n def __init__(self, v1: int, *, v2: str=None, v3: HeaderTypes=None, v4: BaseRequest=None, v5: typing.Callable=None, v6: datetime.timedelta=None):\n self.status_code = v1\n self.http_version = v2\n self.headers = Headers(v3)\n self.request = v4\n self.on_close = v5...
v28
[ "v0" ]
None
def v28(self, v29: v0) -> None: v30 = self._CookieCompatRequest(v29) self.jar.add_cookie_header(v30)
[]
[]
[]
3
import cgi import datetime import email.message import json as jsonlib import typing import urllib.request from collections.abc import MutableMapping from http.cookiejar import Cookie, CookieJar from urllib.parse import parse_qsl, urlencode import chardet import rfc3986 from .config import USER_AGENT from .decoders i...
[ "class v0:\n\n def __init__(self, v1: str, v2: typing.Union[str, URL], *, v3: QueryParamTypes=None, v4: HeaderTypes=None, v5: CookieTypes=None):\n self.method = v1.upper()\n self.url = URL(v2, params=v3)\n self.headers = Headers(v4)\n if v5:\n self._cookies = Cookies(v5)\n ...
v0
[ "str", "str", "str", "str" ]
None
def v0(self, v1: str, v2: str, v3: str='', v4: str='/') -> None: v5 = {'version': 0, 'name': v1, 'value': v2, 'port': None, 'port_specified': False, 'domain': v3, 'domain_specified': bool(v3), 'domain_initial_dot': v3.startswith('.'), 'path': v4, 'path_specified': bool(v4), 'secure': False, 'expires': None, 'discar...
[]
[ "http" ]
[ "from http.cookiejar import Cookie, CookieJar" ]
4
import cgi import datetime import email.message import json as jsonlib import typing import urllib.request from collections.abc import MutableMapping from http.cookiejar import Cookie, CookieJar from urllib.parse import parse_qsl, urlencode import chardet import rfc3986 from .config import USER_AGENT from .decoders i...
null
v0
[ "str", "str", "str" ]
None
def v0(self, v1: str, v2: str=None, v3: str=None) -> None: if v2 is not None and v3 is not None: return self.jar.clear(v2, v3, v1) v4 = [] for v5 in self.jar: if v5.name == v1: if v2 is None or v5.domain == v2: if v3 is None or v5.path == v3: v...
[]
[]
[]
11
import cgi import datetime import email.message import json as jsonlib import typing import urllib.request from collections.abc import MutableMapping from http.cookiejar import Cookie, CookieJar from urllib.parse import parse_qsl, urlencode import chardet import rfc3986 from .config import USER_AGENT from .decoders i...
null
v0
[ "str", "str" ]
None
def v0(self, v1: str=None, v2: str=None) -> None: v3 = [] if v1 is not None: v3.append(v1) if v2 is not None: assert v1 is not None v3.append(v2) self.jar.clear(*v3)
[]
[]
[]
8
import cgi import datetime import email.message import json as jsonlib import typing import urllib.request from collections.abc import MutableMapping from http.cookiejar import Cookie, CookieJar from urllib.parse import parse_qsl, urlencode import chardet import rfc3986 from .config import USER_AGENT from .decoders i...
null
v0
[ "str", "str" ]
None
def v0(self, v1: str, v2: str) -> None: super().add_unredirected_header(v1, v2) self.request.headers[v1] = v2
[]
[]
[]
3
import cgi import datetime import email.message import json as jsonlib import typing import urllib.request from collections.abc import MutableMapping from http.cookiejar import Cookie, CookieJar from urllib.parse import parse_qsl, urlencode import chardet import rfc3986 from .config import USER_AGENT from .decoders i...
null
v0
[ "git.Repo" ]
str
def v0(v1: git.Repo) -> str: v2 = v1.config_reader() return v2.get_value('init', 'defaultBranch', 'master')
[]
[]
[]
3
# Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT import logging import re import subprocess import tempfile from pathlib import Path from typing import Tuple, Optional, Union, List import git import yaml from ogr.parsing import RepoUrl, parse_git_repo from packit.exceptions import Packi...
null
v0
[ "Path", "List[str]" ]
Any
def v0(v1: Path, v2: List[str]): subprocess.check_call(['git', 'init'] + v2 + [str(v1)]) if '--bare' not in v2: subprocess.check_call(['git', 'checkout', '-b', 'main'], cwd=v1) else: subprocess.check_call(['git', 'symbolic-ref', 'HEAD', 'refs/heads/main'], cwd=v1)
[]
[ "subprocess" ]
[ "import subprocess" ]
6
# Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT import logging import re import subprocess import tempfile from pathlib import Path from typing import Tuple, Optional, Union, List import git import yaml from ogr.parsing import RepoUrl, parse_git_repo from packit.exceptions import Packi...
null
v0
[ "str" ]
str
def v0(v1: str) -> str: v2 = re.compile('^diff -\\w+ ', flags=re.MULTILINE) v3 = 'diff --git ' v1 = re.sub(v2, v3, v1) v2 = re.compile('^((---|\\+\\+\\+) .+)\\t\\d{4}.+$', flags=re.MULTILINE) v3 = '\\1' v1 = re.sub(v2, v3, v1) if 'diff --git ' not in v1: v2 = re.compile('(\\n--- (.+)...
[]
[ "re" ]
[ "import re" ]
12
# Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT import logging import re import subprocess import tempfile from pathlib import Path from typing import Tuple, Optional, Union, List import git import yaml from ogr.parsing import RepoUrl, parse_git_repo from packit.exceptions import Packi...
null
v15
[ "Any", "Optional[int]", "Optional[int]" ]
Any
def v15(v16, v17: Optional[int]=None, v18: Optional[int]=None): with h5py.File(v16, 'r') as v19: v20 = np.asarray(v19['eri'][()]) try: v21 = np.asarray(v19['h0'][()]) except KeyError: try: v21 = np.asarray(v19['hcore'][()]) except KeyError:...
[ { "name": "v0", "input_types": [ "Any", "Any", "Any", "Any", "Any" ], "output_type": "Any", "code": "def v0(v1, v2, v3, v4, v5):\n v6 = len(v1)\n assert [v6] * 4 == [*v2.shape]\n v7 = gto.M()\n v7.nelectron = v4 + v5\n v6 = v1.shape[0]\n v8 = [1] *...
[ "h5py", "numpy", "sys" ]
[ "import sys", "import h5py", "import numpy as np" ]
31
#coverage:ignore """ Drivers for various PySCF electronic structure routines """ from typing import Tuple, Optional import sys import h5py import numpy as np from pyscf import gto, scf, ao2mo, mcscf, lo, tools, cc from pyscf.mcscf import avas def stability(pyscf_mf): """ Test wave function stability and re-op...
null
v20
[ "Any", "Any", "Optional[int]", "Optional[int]", "Any" ]
Any
def v20(v21, v22, v23: Optional[int]=None, v24: Optional[int]=None, v25=None): (v26, v27, v28, v29, v30) = v9(v22, v23, v24, v25) with h5py.File(v21, 'w') as v31: v31.create_dataset('ecore', data=float(v28), dtype=float) v31.create_dataset('h0', data=v26) v31.create_dataset('eri', data=v...
[ { "name": "v0", "input_types": [ "Any", "Any" ], "output_type": "Any", "code": "def v0(v1, v2):\n v3 = v1.mol.nelectron\n v4 = v3 - v2\n assert v4 % 2 == 0\n if isinstance(v1, scf.rohf.ROHF):\n v5 = v4 // 2\n v6 = v4 // 2\n v7 = v1.nelec[0] - v5\n ...
[ "h5py", "numpy" ]
[ "import h5py", "import numpy as np" ]
8
#coverage:ignore """ Drivers for various PySCF electronic structure routines """ from typing import Tuple, Optional import sys import h5py import numpy as np from pyscf import gto, scf, ao2mo, mcscf, lo, tools, cc from pyscf.mcscf import avas def stability(pyscf_mf): """ Test wave function stability and re-op...
null
v48
[ "Any", "Any", "Any", "Any" ]
Tuple[float, float, float]
def v48(v49, v50=None, v51=True, v52=False) -> Tuple[float, float, float]: (v53, v54, v55, v56, v57) = v33(v49) if v50 is None: v50 = v54 (v58, v59, v60) = v0(v53, v50, v55, v56, v57, v54, v51, v52) return (v58, v59, v60)
[ { "name": "v0", "input_types": [ "Any", "Any", "Any", "int", "int", "Any", "Any", "Any" ], "output_type": "Tuple[float, float, float]", "code": "def v0(v1, v2, v3, v4: int, v5: int, v6=None, v7=True, v8=False) -> Tuple[float, float, float]:\n v9...
[ "numpy" ]
[ "import numpy as np" ]
6
#coverage:ignore """ Drivers for various PySCF electronic structure routines """ from typing import Tuple, Optional import sys import h5py import numpy as np from pyscf import gto, scf, ao2mo, mcscf, lo, tools, cc from pyscf.mcscf import avas def stability(pyscf_mf): """ Test wave function stability and re-op...
null
v6
[ "Any", "Any", "Optional[float]", "Any", "Any", "Any", "Any" ]
_compare_return_type
def v6(self, v7, v8, *, v9: Optional[float]=None, v10=None, v11=True, v12=True, v13=False) -> _compare_return_type: assert (v10 is None) == (v9 is None) if not isinstance(v7, torch.Tensor): return (False, 'argument a, {0}, to _compareTensors is not a tensor!'.format(v7)) if not isinstance(v8, torch....
[ { "name": "v0", "input_types": [ "Any", "Any" ], "output_type": "Any", "code": "def v0(v1, v2):\n v3 = torch.float32 if v1.dtype is torch.bfloat16 else v1.dtype\n v4 = torch.float32 if v2.dtype is torch.bfloat16 else v2.dtype\n v5 = torch.promote_types(v3, v4)\n if v5 is ...
[ "torch" ]
[ "from torch.testing._internal import expecttest", "from torch.testing import _compare_tensors_internal, _compare_scalars_internal, _compare_return_type", "import torch", "import torch.cuda", "from torch._utils_internal import get_writable_path", "from torch._six import string_classes", "import torch.bac...
22
r"""Importing this file must **not** initialize CUDA context. test_distributed relies on this assumption to properly run. This means that when this is imported no CUDA calls shall be made, including torch.cuda.device_count(), etc. torch.testing._internal.common_cuda.py can freely initialize CUDA context when imported....
null
v0
[ "Any", "Any", "Optional[float]", "Optional[float]", "Any" ]
_compare_return_type
def v0(self, v1, v2, *, v3: Optional[float]=None, v4: Optional[float]=None, v5=True) -> _compare_return_type: assert (v4 is None) == (v3 is None) if v3 is None: if isinstance(v1, complex) or isinstance(v2, complex): (v3, v4) = self._getDefaultRtolAndAtol(torch.complex64, torch.complex64) ...
[]
[ "torch", "typing" ]
[ "from typing import cast, Any, Iterable, Optional", "from torch.testing._internal import expecttest", "from torch.testing import _compare_tensors_internal, _compare_scalars_internal, _compare_return_type", "import torch", "import torch.cuda", "from torch._utils_internal import get_writable_path", "from ...
11
r"""Importing this file must **not** initialize CUDA context. test_distributed relies on this assumption to properly run. This means that when this is imported no CUDA calls shall be made, including torch.cuda.device_count(), etc. torch.testing._internal.common_cuda.py can freely initialize CUDA context when imported....
null
v0
[ "Any", "Any", "Optional[str]", "Optional[float]", "Optional[float]" ]
None
def v0(self, v1, v2, v3: Optional[str]=None, *, v4: Optional[float]=None, v5: Optional[float]=None, **v6) -> None: with self.assertRaises(AssertionError, msg=v3): self.assertEqual(v1, v2, v3, atol=v4, rtol=v5, **v6)
[]
[]
[]
3
r"""Importing this file must **not** initialize CUDA context. test_distributed relies on this assumption to properly run. This means that when this is imported no CUDA calls shall be made, including torch.cuda.device_count(), etc. torch.testing._internal.common_cuda.py can freely initialize CUDA context when imported....
null
v0
[ "Any", "Any" ]
None
def v0(self, v1, v2) -> None: self.assertEqual(v1.device, v2.device) self.assertEqual(v1.dtype, v2.dtype) self.assertEqual(v1.is_sparse, v2.is_sparse)
[]
[]
[]
4
r"""Importing this file must **not** initialize CUDA context. test_distributed relies on this assumption to properly run. This means that when this is imported no CUDA calls shall be made, including torch.cuda.device_count(), etc. torch.testing._internal.common_cuda.py can freely initialize CUDA context when imported....
null
v0
[ "Any", "Iterable[Any]" ]
None
def v0(self, v1: Any, v2: Iterable[Any]) -> None: for v3 in v2: if id(v1) == id(v3): return raise AssertionError('object not found in iterable')
[]
[]
[]
5
r"""Importing this file must **not** initialize CUDA context. test_distributed relies on this assumption to properly run. This means that when this is imported no CUDA calls shall be made, including torch.cuda.device_count(), etc. torch.testing._internal.common_cuda.py can freely initialize CUDA context when imported....
null
v1
[ "v0" ]
v0
def v1(self, v2: v0) -> v0: self.add_check(v2, call_once=True) return v2
[]
[]
[]
3
""" The MIT License (MIT) Copyright (c) 2015-2021 Rapptz Copyright (c) 2021-present Disnake Development 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 limi...
[ "v0 = TypeVar('CFT', bound='CoroFunc')" ]
v1
[ "v0" ]
v0
def v1(self, v2: v0) -> v0: if not asyncio.iscoroutinefunction(v2): raise TypeError('The pre-invoke hook must be a coroutine.') self._before_invoke = v2 return v2
[]
[ "asyncio" ]
[ "import asyncio" ]
5
""" The MIT License (MIT) Copyright (c) 2015-2021 Rapptz Copyright (c) 2021-present Disnake Development 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 limi...
[ "v0 = TypeVar('CFT', bound='CoroFunc')" ]