name
stringclasses
844 values
input_types
listlengths
0
100
output_type
stringlengths
1
419
code
stringlengths
34
233k
dependencies
listlengths
0
6
lib_used
listlengths
0
11
imports
listlengths
0
66
line_count
int64
3
199
full_code
stringlengths
39
1.01M
input_type_defs
listlengths
1
12
v0
[ "str" ]
Any
def v0(v1: str): v2 = {} for v3 in v1.split(';'): v3 = v3.strip() try: v4 = v3.split()[0].replace('"', '') v5 = v3.split()[1].replace('"', '') v2[v4] = v5 except IndexError: pass return v2
[]
[]
[]
11
def read_gff_attributes(attribute_column: str) -> dict: """ Parse attributes for a GFF3 record. Attributes with pre-defined meaning are parsed according to their specification (e.g. Dbxref usually has multiple values which are split up: 'GeneID:1234,Genbank:NM_9283'). :param attribute_column: Attribut...
null
v0
[]
Union[list, dict]
def v0(self) -> Union[list, dict]: if self.nodes: return [{'name': x.get('name'), 'mapping': x.get('mapping')} for v1 in self.nodes] else: v2 = json.loads(self.data) return {'name': v2.get('name'), 'mapping': v2.get('mapping')}
[]
[ "json" ]
[ "import json" ]
6
import json from typing import Union from requests import Response from py_behrtech.Parsers.defaults import Defaults class NodeParser(Defaults): # TODO: setup for downlink messages from nodesEpEuiTxDataGet and nodesEpEuiTxDataIdGet when bi-directional is setup def __init__(self, req: Response): de...
null
v0
[]
Union[list, dict]
def v0(self) -> Union[list, dict]: if self.nodes: return [{'name': x.get('name'), 'Plugin Mapping': x.get('mapping').get('pluginMapping')} for v1 in self.nodes] else: v2 = json.loads(self.data) return {'name': v2.get('name'), 'Plugin Mapping': v2.get('mapping').get('pluginMapping')}
[]
[ "json" ]
[ "import json" ]
6
import json from typing import Union from requests import Response from py_behrtech.Parsers.defaults import Defaults class NodeParser(Defaults): # TODO: setup for downlink messages from nodesEpEuiTxDataGet and nodesEpEuiTxDataIdGet when bi-directional is setup def __init__(self, req: Response): de...
null
v0
[ "Any", "Any" ]
float
def v0(v1, v2) -> float: with torch.no_grad(): v3 = 0 v4 = 0 (v5, v6) = next(iter(DataLoader(v1, batch_size=20, shuffle=True))) v7 = v2(v5) for v8 in range(len(v7)): v9 = torch.argmax(v7[v8]) v10 = torch.argmax(v6[v8]) if v9.item() == v10.i...
[]
[ "torch" ]
[ "import torch", "import torch.nn as nn", "from torch.utils.data import DataLoader, random_split", "import torch.optim as optim", "from torch.utils.tensorboard import SummaryWriter" ]
13
import torch import torch.nn as nn from torch.utils.data import DataLoader, random_split import torch.optim as optim from tqdm import tqdm from matplotlib import pyplot as plt from datetime import datetime from util import WavData from torch.utils.tensorboard import SummaryWriter # fixed : pip3 install torch torchvi...
null
v0
[ "Any", "Any", "Any", "np.ndarray", "np.ndarray" ]
Any
def v0(v1, v2, v3, v4: np.ndarray, v5: np.ndarray): assert v1.shape == (v2, v3, 2), v1.shape assert v4.max() < v3 assert v5.max() < v2 return v1[v5, v4]
[]
[]
[]
5
from loader.loader_dsec import * from loader.loader_mvsec_flow import * import json from utils import dsec_utils import torch.nn from model import eraft import argparse from pathlib import Path from test import * import utils.helper_functions as helper from utils import visualization import numpy as np import cv2 from ...
null
v0
[]
list
def v0(self) -> list: if self.__threshold_pixels is None: raise RuntimeError('threshold pixels are None. crop method must be done before this method.') return self.__threshold_pixels
[]
[]
[]
4
from PIL import Image from collections import deque import numpy as np import warnings class ImageThresholdUtil: """ It has to do with the image threshold. Threshold here means filtering, which finds the pixels to be filtered out. So this class has static methods related to the threshold and cooperate...
null
v0
[ "Any", "Any" ]
None
def v0(self, v1, v2=True) -> None: self.__img = Image.open(v1).convert('RGB') (self.__row, self.__col) = self.__img.size self.__numpy_mean_variant()
[]
[ "PIL" ]
[ "from PIL import Image" ]
4
from PIL import Image from collections import deque import numpy as np import warnings class ImageThresholdUtil: """ It has to do with the image threshold. Threshold here means filtering, which finds the pixels to be filtered out. So this class has static methods related to the threshold and cooperate...
null
v0
[]
None
def v0(self) -> None: self.__img_field = np.zeros((self.__col, self.__row)) v1 = np.mean(np.array(self.__img), axis=2, keepdims=True) self.__pix = np.rint(np.concatenate([v1], axis=2))
[]
[ "numpy" ]
[ "import numpy as np" ]
4
from PIL import Image from collections import deque import numpy as np import warnings class ImageThresholdUtil: """ It has to do with the image threshold. Threshold here means filtering, which finds the pixels to be filtered out. So this class has static methods related to the threshold and cooperate...
null
v0
[ "Any", "Any" ]
bool
def v0(self, v1, v2) -> bool: (v3, v4) = v1 (v5, v6) = v2 v7 = v6 - v4 v8 = v5 - v3 return v8 > self.__min_width and v7 > self.__min_height
[]
[]
[]
6
from PIL import Image from collections import deque import numpy as np import warnings class ImageThresholdUtil: """ It has to do with the image threshold. Threshold here means filtering, which finds the pixels to be filtered out. So this class has static methods related to the threshold and cooperate...
null
v0
[ "Any", "Any" ]
bool
def v0(self, v1, v2) -> bool: for v3 in self.__threshold_pixels: if v3 - self.__pixel_sensitivity <= self.__pix[v1, v2] <= v3 + self.__pixel_sensitivity: return False return True
[]
[]
[]
5
from PIL import Image from collections import deque import numpy as np import warnings class ImageThresholdUtil: """ It has to do with the image threshold. Threshold here means filtering, which finds the pixels to be filtered out. So this class has static methods related to the threshold and cooperate...
null
v0
[]
None
def v0(self) -> None: for v1 in range(self.__row): for v2 in range(self.__col): if self.__img_field[v2][v1] == 0 and self.__validate_pixel(v2, v1) is True: v3 = self.__validate_image_pixel(v2, v1) if v3: self.__save_points.append(v3)
[]
[]
[]
7
from PIL import Image from collections import deque import numpy as np import warnings class ImageThresholdUtil: """ It has to do with the image threshold. Threshold here means filtering, which finds the pixels to be filtered out. So this class has static methods related to the threshold and cooperate...
null
v0
[ "Any", "Any", "Any" ]
None
def v0(self, v1, v2, v3) -> None: for (v4, v5) in enumerate(self.__save_points): v6 = (v5[0][1], v5[0][0], v5[1][1], v5[1][0]) v7 = self.__img.crop(v6) v8 = v2 + '_' + str(v4 + 1) + '.' + v3.lower() v7.save(v1 + '/' + v8, format=v3)
[]
[]
[]
6
from PIL import Image from collections import deque import numpy as np import warnings class ImageThresholdUtil: """ It has to do with the image threshold. Threshold here means filtering, which finds the pixels to be filtered out. So this class has static methods related to the threshold and cooperate...
null
v0
[]
list
def v0(self) -> list: v1 = [] for v2 in self.__save_points: v1.append((v2[0][1], v2[0][0], v2[1][1], v2[1][0])) return v1
[]
[]
[]
5
from PIL import Image from collections import deque import numpy as np import warnings class ImageThresholdUtil: """ It has to do with the image threshold. Threshold here means filtering, which finds the pixels to be filtered out. So this class has static methods related to the threshold and cooperate...
null
v1
[ "v0" ]
bool
def v1(v2: v0) -> bool: if isinstance(v2, ast.Name): return True if isinstance(v2, ast.Starred) and isinstance(v2.value, ast.Name): return True return False
[]
[ "ast" ]
[ "import ast" ]
6
import ast from typing import Union _VarDefinition = Union[ast.AST, ast.expr] def _is_valid_single(node: _VarDefinition) -> bool: if isinstance(node, ast.Name): return True if isinstance(node, ast.Starred) and isinstance(node.value, ast.Name): return True return False def is_valid_block...
[ "v0 = Union[ast.AST, ast.expr]" ]
v3
[ "v0" ]
bool
def v3(v4: v0) -> bool: if isinstance(v4, ast.Tuple): for v5 in v4.elts: if not v1(v5): return False return True return v1(v4)
[ { "name": "v1", "input_types": [ "v0" ], "output_type": "bool", "code": "def v1(v2: v0) -> bool:\n if isinstance(v2, ast.Name):\n return True\n if isinstance(v2, ast.Starred) and isinstance(v2.value, ast.Name):\n return True\n return False", "dependencies": [] ...
[ "ast" ]
[ "import ast" ]
7
import ast from typing import Union _VarDefinition = Union[ast.AST, ast.expr] def _is_valid_single(node: _VarDefinition) -> bool: if isinstance(node, ast.Name): return True if isinstance(node, ast.Starred) and isinstance(node.value, ast.Name): return True return False def is_valid_block...
[ "v0 = Union[ast.AST, ast.expr]" ]
v0
[ "Callable[[float], float]", "float", "float", "int" ]
bool
def v0(v1: Callable[[float], float], v2: float, v3: float, v4: int) -> bool: v5 = v3 - v2 v6 = v5 / v4 v7 = v2 v8 = v1(v2) for v9 in range(1, v4 + 1): v7 += v6 if v8 * v1(v7) <= 0: return True return False
[]
[]
[]
10
""" Authors: Luiz Gustavo Mugnaini Anselmo (nUSP: 11809746) Victor Manuel Dias Saliba (nUSP: 11807702) Luan Marc Suquet Camargo (nUSP: 11809090) Computacao III (CCM): EP 1 Test for Dekker method for finding roots of a given function. """ import math from typing import Callable from numerical...
null
v0
[]
dict
def v0(*v1: Mapping[Hashable, Any]) -> dict: v2 = chain.from_iterable(map(operator.methodcaller('items'), v1)) return dict(v2)
[]
[ "itertools", "operator" ]
[ "import operator", "from itertools import chain" ]
3
import operator import os from functools import partial from itertools import chain from typing import (Any, Hashable, Mapping) import autopep8 from . import arboretum def to_name(object_: Any) -> str: try: return object_.__qualname__ except AttributeError: ...
null
v4
[ "str" ]
str
def v4(v5: str) -> str: with get(v5, stream=True) as v6: v7 = (yield from v0(v6)) return v7.decode('utf-8')
[ { "name": "v0", "input_types": [ "Response" ], "output_type": "bytes", "code": "def v0(v1: Response) -> bytes:\n v2 = b''\n for v3 in v1.iter_content(SIZE):\n v2 += v3\n yield\n return v2", "dependencies": [] } ]
[ "requests" ]
[ "from requests import get, Response" ]
4
# Copyright 2019 John Reese # Licensed under the MIT License import time from random import randint from typing import Generator, Any, List, Iterable from requests import get, Response # reuse wait() from part 5 wait = __import__("5-generator-coroutines").wait SIZE = 1024 URLS = [ "https://2019.northbaypython.o...
null
v0
[]
None
def v0(self) -> None: self._driver.get('https://jwxt.ncepu.edu.cn/jsxsd/xskb/xskb_list.do') try: self._driver.implicitly_wait(0.02) v1 = self._driver.switch_to.alert v1.accept() except Exception as e: pass
[]
[]
[]
8
from typing import List from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from bs4 import BeautifulSoup import re class CourseTableCrawler: """登教务,爬课表 """ BASE_URL = "https://jwxt.ncepu.edu.cn/jsxsd/xskb/xskb_list.do" COURSE_TABLE_URL = 'https://jwxt.ncepu.edu....
null
v0
[ "Any" ]
dict
def v0(self, v1) -> dict: v2 = {} for v3 in v1.find_all(name='div'): if '老师' not in str(v3): continue v4 = re.findall('class="kbcontent".*?>.*?<br.?>(.*?)<br.?><font', str(v3)) if v4: v2['name'] = v4[0] v2['text'] = v3.text for v5 in v3: ...
[]
[ "re" ]
[ "import re" ]
22
from typing import List from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from bs4 import BeautifulSoup import re class CourseTableCrawler: """登教务,爬课表 """ BASE_URL = "https://jwxt.ncepu.edu.cn/jsxsd/xskb/xskb_list.do" COURSE_TABLE_URL = 'https://jwxt.ncepu.edu....
null
v0
[]
List[List[dict]]
def v0(self) -> List[List[dict]]: self._login() self._switch_to_course_table() v1 = self._fetch_course_table_page() v2 = self._parse_course_table(v1) return v2
[]
[]
[]
6
from typing import List from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from bs4 import BeautifulSoup import re class CourseTableCrawler: """登教务,爬课表 """ BASE_URL = "https://jwxt.ncepu.edu.cn/jsxsd/xskb/xskb_list.do" COURSE_TABLE_URL = 'https://jwxt.ncepu.edu....
null
v0
[ "str" ]
None
def v0(self, v1: str) -> None: if v1: self.model.save_pretrained(v1) self.tokenizer.save_pretrained(v1)
[]
[]
[]
4
from typing import Optional import numpy as np import torch from torch import cuda from torch.utils.data import DataLoader from transformers import GPT2LMHeadModel, GPT2Tokenizer from pytorch_lightning.loggers import WandbLogger import pytorch_lightning as pl from kogito.models.gpt2.utils import GPT2Finetuner from kog...
null
v0
[ "List[int]", "int" ]
bool
def v0(v1: List[int], v2: int) -> bool: v3 = 0 v4 = {} for v5 in range(len(v1)): v6 = v1[v5] v3 = (v3 + v6) % v2 if v6 % v2 == 0 and v3 != 0: if v1[v5 - 1] % v2 != 0: continue if v4.get(v3, 0): return True v4[v3] = v4.get(v3, 0)...
[]
[]
[]
15
#works in O(n) from typing import List def solve(nums: List[int], k: int) -> bool: current_sum = 0 sum_hash = {} for idx in range(len(nums)): # increase sum accumulated so far by current number, divide it by k num = nums[idx] current_sum = (current_sum + num) % k ...
null
v9
[ "Any", "int", "bool", "bool", "int" ]
Any
def v9(v10, v11: int=1, v12: bool=False, v13: bool=False, v14: int=0): v15 = [] for v16 in v10: v15.append({'node': v5(v16)}) return {'edges': v15, 'pageInfo': v0(end_index=v11, has_next_page=v12, has_previous_page=v13, start_index=v14)}
[ { "name": "v0", "input_types": [ "int", "bool", "bool", "int" ], "output_type": "Any", "code": "def v0(v1: int=1, v2: bool=False, v3: bool=False, v4: int=0):\n return {'endIndex': v1, 'hasNextPage': v2, 'hasPreviousPage': v3, 'startIndex': v4}", "dependencies": [] ...
[]
[]
5
from galley.types import PageInfoType from tests.mock_responses import (mock_nutrition_data, mock_recipe_items, mock_recipe_tree_components, mock_recipe_category_values) from galley.enums import RecipeCategoryTagTypeEn...
null
v0
[ "dict" ]
Any
def v0(self, v1: dict): v2 = v1['output'] for v3 in v2: v4 = None if 'suggestedActions' in v3: v4 = v3['suggestedActions']['actions'] if 'text' in v3: self.send_text(v3['text'], v4) if 'attachments' in v3: for v5 in v3['attachments']: ...
[]
[]
[]
16
"""Telegram Channel. LOAD channels.restful.app TO ANSWER TELEGRAM WEBHOOK""" import telepot import logging from urllib.parse import urlparse import time import html import traceback import json import os import cgi from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton from bbot.core import BBotCore...
null
v0
[ "list", "list" ]
Any
def v0(self, v1: list, v2: list): if len(v1) == 0: v1 = '...' v3 = self._get_keyboard(v2) self.api.sendMessage(self.user_id, v1, parse_mode=self.default_text_encoding, reply_markup=v3)
[]
[]
[]
5
"""Telegram Channel. LOAD channels.restful.app TO ANSWER TELEGRAM WEBHOOK""" import telepot import logging from urllib.parse import urlparse import time import html import traceback import json import os import cgi from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton from bbot.core import BBotCore...
null
v0
[ "dict", "list" ]
Any
def v0(self, v1: dict, v2: list): v3 = None if v1.get('media'): v3 = v1['media'][0]['url'] elif v1.get('images'): v3 = v1['images'][0]['url'] v4 = self._common_media_caption(v1) v5 = self._get_keyboard(v2) self.logger.debug('Sending image to Telegram: url: ' + v3) self.api.se...
[]
[]
[]
10
"""Telegram Channel. LOAD channels.restful.app TO ANSWER TELEGRAM WEBHOOK""" import telepot import logging from urllib.parse import urlparse import time import html import traceback import json import os import cgi from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton from bbot.core import BBotCore...
null
v0
[ "dict" ]
Any
def v0(self, v1: dict): v2 = None v3 = '' if v1.get('title'): v3 += f"{self.emOpen}{v1['title']}{self.emClose}" if v1.get('subtitle'): if len(v3) > 0: v3 += '\n' v3 += v1['subtitle'] if v1.get('text'): if len(v3) > 0: v3 += '\n\n' v3 +=...
[]
[]
[]
16
"""Telegram Channel. LOAD channels.restful.app TO ANSWER TELEGRAM WEBHOOK""" import telepot import logging from urllib.parse import urlparse import time import html import traceback import json import os import cgi from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton from bbot.core import BBotCore...
null
v0
[ "dict" ]
Any
def v0(self, v1: dict): if v1.get('message'): self.user_id = str(v1['message']['from']['id']) return self.user_id if v1.get('callback_query'): self.user_id = str(v1['callback_query']['from']['id']) return self.user_id
[]
[]
[]
7
"""Telegram Channel. LOAD channels.restful.app TO ANSWER TELEGRAM WEBHOOK""" import telepot import logging from urllib.parse import urlparse import time import html import traceback import json import os import cgi from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton from bbot.core import BBotCore...
null
v0
[ "dict" ]
Any
def v0(self, v1: dict): if v1.get('message'): return v1['message']['text'] if v1.get('callback_query'): return v1['callback_query']['data']
[]
[]
[]
5
"""Telegram Channel. LOAD channels.restful.app TO ANSWER TELEGRAM WEBHOOK""" import telepot import logging from urllib.parse import urlparse import time import html import traceback import json import os import cgi from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton from bbot.core import BBotCore...
null
v9
[ "Any", "list" ]
Any
def v9(v10, v11: list): if type(v11) is not list: raise TypeError('Positions must be lists') v12 = v0(v10) if v11 not in v12['known_zaaps']: v12['known_zaaps'].append(v11) v5(v10, v12)
[ { "name": "v0", "input_types": [ "Any", "Any" ], "output_type": "Any", "code": "def v0(v1, v2=None):\n if v2 is None:\n v2 = mongo_client()\n v3 = v2.blackfalcon.bots.find_one({'name': v1})\n if v3 is None:\n raise Exception(\"Bot does not exist. Create a profi...
[]
[]
7
import hashlib import json import random import uuid import numpy as np from heapq import * import time import itertools import sys import pymongo import psycopg2 from credentials import credentials def cell2coord(cell): return cell % 14 + int((cell // 14) / 2 + 0.5), (13 - cell % 14 + int((cell // 14) / 2)) ...
null
v0
[]
int
def v0(self) -> int: if self.a > 0: return self.a ** (1 / float(self.b)) return 'Error!, no se puede obtener la raiz de un numero negativo.'
[]
[]
[]
4
class Calculator: def __init__(self, a : int, b : int) -> None: self.a = a self.b = b def suma(self) -> int: return self.a + self.b def resta(self) -> int: return self.a - self.b def multiplicacion(self) -> int: return self.a * self.b def division...
null
v0
[ "Dict[str, Any]" ]
Tuple[bool, List[str]]
def v0(v1: Dict[str, Any]) -> Tuple[bool, List[str]]: v2 = ['request_type', 'name', 'response_time', 'response_length', 'context', 'exception'] v3 = list(v1.keys()) v2.sort() v3.sort() v4 = list(set(v2) - set(v3)) return (v3 == v2, v4)
[]
[]
[]
7
import inspect import subprocess import os import stat from typing import Any, Dict, Optional, Tuple, List, Set, Callable from types import MethodType, TracebackType from locust import task from locust.event import EventHook from grizzly.users.base import GrizzlyUser from grizzly.types import GrizzlyResponse, Reques...
null
v0
[ "List[str]", "Optional[Dict[str, str]]", "Optional[str]" ]
Tuple[int, List[str]]
def v0(v1: List[str], v2: Optional[Dict[str, str]]=None, v3: Optional[str]=None) -> Tuple[int, List[str]]: v4: List[str] = [] if v2 is None: v2 = os.environ.copy() if v3 is None: v3 = os.getcwd() v5 = subprocess.Popen(v1, env=v2, cwd=v3, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) ...
[]
[ "os", "subprocess" ]
[ "import subprocess", "import os" ]
26
import inspect import subprocess import os import stat from typing import Any, Dict, Optional, Tuple, List, Set, Callable from types import MethodType, TracebackType from locust import task from locust.event import EventHook from grizzly.users.base import GrizzlyUser from grizzly.types import GrizzlyResponse, Reques...
null
v0
[ "np.ndarray", "Tuple[int, int]" ]
Optional[np.ndarray]
def v0(v1: np.ndarray, v2: Tuple[int, int]) -> Optional[np.ndarray]: if len(v1.shape) == 3: return np.pad(v1, ((v2[0], v2[0]), (v2[1], v2[1]), (0, 0)), 'constant', constant_values=0) elif len(v1.shape) == 2: return np.pad(v1, ((v2[0], v2[0]), (v2[1], v2[1])), 'constant', constant_values=0) e...
[]
[ "numpy" ]
[ "import numpy as np" ]
7
from typing import Callable, List, Optional, Tuple import numpy as np from image_keras.supports.tuple_op import ( tuple_add, tuple_divide_int, tuple_element_wise_add, tuple_element_wise_divide_int, tuple_element_wise_subtract, tuple_multiply, ) def add_zero_padding( cv2_image: np.ndarray,...
null
v0
[ "List[List[np.ndarray]]", "Callable[[int, int, np.ndarray], Optional[np.ndarray]]" ]
Tuple[int, int, List[List[np.ndarray]]]
def v0(v1: List[List[np.ndarray]], v2: Callable[[int, int, np.ndarray], Optional[np.ndarray]]) -> Tuple[int, int, List[List[np.ndarray]]]: v3 = 0 v4 = 0 v5: List[List[np.ndarray]] = [] for v6 in v1: v4 = 0 v7: List[np.ndarray] = [] for v8 in v6: v9 = v2(v3, v4, v8) ...
[]
[]
[]
15
from typing import Callable, List, Optional, Tuple import numpy as np from image_keras.supports.tuple_op import ( tuple_add, tuple_divide_int, tuple_element_wise_add, tuple_element_wise_divide_int, tuple_element_wise_subtract, tuple_multiply, ) def add_zero_padding( cv2_image: np.ndarray,...
null
v33
[ "str", "Any", "Any", "Any" ]
Any
def v33(v34: str, v35, v36, v37): v36 = deepcopy(v36) v38 = v37.get('sample_annotation', v34) v39 = ['1', '2', '3', '4'] if not v38['visibility_token'] in v39: return (None, None, None) v40 = v37.get_box(v34) v41 = v38['next'] v42 = v38['prev'] v43 = v41 != '' v44 = v42 != ''...
[ { "name": "v0", "input_types": [ "Any", "Any" ], "output_type": "Any", "code": "def v0(v1, v2):\n v2 = points_to_box(v1, v2)\n v2 = np.abs(v2)\n (v3, v4, v5) = v1.wlh\n (v6, v7, v8) = (v4 / 2, v3 / 2, v5 / 2)\n v9 = v2[0, :] < v6\n v10 = v2[1, :] < v7\n v11 = v2[...
[ "copy", "numpy" ]
[ "import numpy as np", "from copy import deepcopy" ]
31
from nuscenes.nuscenes import NuScenes, NuScenesExplorer import numpy as np import os import os.path as osp import json from pyquaternion import Quaternion from nuscenes.utils.data_classes import LidarPointCloud, RadarPointCloud, Box from nuscenes.utils.geometry_utils import view_points, box_in_image, BoxVisibility, tr...
null
v0
[ "str", "str" ]
dict
def v0(v1: str, v2: str) -> dict: v3 = {} if v1 == 'early': v3['sqlColumsToRetrieve'] = ['UTG', 'UTGp1'] if v1 == 'blinds': v3['sqlColumsToRetrieve'] = ['SB', 'BB'] if v1 == 'middle': v3['sqlColumsToRetrieve'] = ['MP', 'MPp1', 'MPp2'] if v1 == 'late': v3['sqlColumsToR...
[]
[]
[]
20
from GLOBAL_VARIABLES import FOLDER_PLOT_DUMP, PLAYER_NAME import matplotlib.pyplot as plt from matplotlib import rcParams import pandas as pd import seaborn as sns from utils.run_sql_command import run_sql_command hand_matrix = [ ['AA', 'AKs', 'AQs', 'AJs', 'ATs', 'A9s', 'A8s', 'A7s', 'A6s', 'A5s', 'A4s', 'A3s',...
null
v0
[ "list" ]
list
def v0(v1: list) -> list: v2 = [] for v3 in v1: if v3[0] == v3[3]: v4 = v3[0] + v3[3] elif v3[1] == v3[4]: v4 = v3[0] + v3[3] + 's' elif v3[1] != v3[4]: v4 = v3[0] + v3[3] + 'o' v2.append(v4) return v2
[]
[]
[]
11
from GLOBAL_VARIABLES import FOLDER_PLOT_DUMP, PLAYER_NAME import matplotlib.pyplot as plt from matplotlib import rcParams import pandas as pd import seaborn as sns from utils.run_sql_command import run_sql_command hand_matrix = [ ['AA', 'AKs', 'AQs', 'AJs', 'ATs', 'A9s', 'A8s', 'A7s', 'A6s', 'A5s', 'A4s', 'A3s',...
null
v0
[ "list" ]
dict
def v0(v1: list) -> dict: v2 = {'AA': 0, 'AKs': 0, 'AQs': 0, 'AJs': 0, 'ATs': 0, 'A9s': 0, 'A8s': 0, 'A7s': 0, 'A6s': 0, 'A5s': 0, 'A4s': 0, 'A3s': 0, 'A2s': 0, 'KAo': 0, 'KK': 0, 'KQs': 0, 'KJs': 0, 'KTs': 0, 'K9s': 0, 'K8s': 0, 'K7s': 0, 'K6s': 0, 'K5s': 0, 'K4s': 0, 'K3s': 0, 'K2s': 0, 'QAo': 0, 'QKo': 0, 'QQ': ...
[]
[]
[]
19
from GLOBAL_VARIABLES import FOLDER_PLOT_DUMP, PLAYER_NAME import matplotlib.pyplot as plt from matplotlib import rcParams import pandas as pd import seaborn as sns from utils.run_sql_command import run_sql_command hand_matrix = [ ['AA', 'AKs', 'AQs', 'AJs', 'ATs', 'A9s', 'A8s', 'A7s', 'A6s', 'A5s', 'A4s', 'A3s',...
null
v0
[ "str" ]
str
def v0(v1: str) -> str: if v1 == 'early': return 'UTG | UTGp1' if v1 == 'blinds': return 'SB | BB' if v1 == 'middle': return 'MP | MPp1 | MPp2' if v1 == 'late': return 'CO | BTN'
[]
[]
[]
9
from GLOBAL_VARIABLES import FOLDER_PLOT_DUMP, PLAYER_NAME import matplotlib.pyplot as plt from matplotlib import rcParams import pandas as pd import seaborn as sns from utils.run_sql_command import run_sql_command hand_matrix = [ ['AA', 'AKs', 'AQs', 'AJs', 'ATs', 'A9s', 'A8s', 'A7s', 'A6s', 'A5s', 'A4s', 'A3s',...
null
v0
[ "model.Expression", "model.Expression" ]
model.Expression
def v0(self, v1: model.Expression, v2: model.Expression) -> model.Expression: assert self.fuel_model is not None, 'no fuel model has been defined' return self.fuel_model(self, v1, v2)
[]
[]
[]
3
# -*- coding:utf-8 -*- # # Copyright (C) 2020-2021, Saarland University # Copyright (C) 2020-2021, Maximilian Köhl <koehl@cs.uni-saarland.de> # Copyright (C) 2020-2021, Michaela Klauck <klauck@cs.uni-saarland.de> from __future__ import annotations import dataclasses as d import typing as t import enum import itertoo...
null
v0
[]
argparse.Namespace
def v0() -> argparse.Namespace: v1 = argparse.ArgumentParser(description='Commandline weather checker', prog='weather-checker') v1.add_argument('city') v1.add_argument('-l', '--long', action='store_true', help='show more detailed weather information') v2 = v1.parse_args() return v2
[]
[ "argparse" ]
[ "import argparse" ]
6
#!/usr/bin/env python3 import os import requests import argparse from dotenv import load_dotenv from typing import Dict, Optional from src import helpers as h path_to_env = os.path.abspath(__file__ + "/../../.env") load_dotenv(path_to_env) BASE_URL = "https://api.openweathermap.org/data/2.5/weather" API_KEY = os.ge...
null
v0
[ "str", "Dict[str, str]" ]
str
def v0(v1: str, v2: Dict[str, str]) -> str: v3 = '&'.join([f'{k}={v}' for (v4, v5) in v2.items()]) v6 = v1 + '?' + v3 return v6
[]
[]
[]
4
#!/usr/bin/env python3 import os import requests import argparse from dotenv import load_dotenv from typing import Dict, Optional from src import helpers as h path_to_env = os.path.abspath(__file__ + "/../../.env") load_dotenv(path_to_env) BASE_URL = "https://api.openweathermap.org/data/2.5/weather" API_KEY = os.ge...
null
v0
[ "str" ]
Optional[dict]
def v0(v1: str) -> Optional[dict]: v2 = requests.get(v1) if v2: return v2.json() else: if v2.status_code == 404: print('\nWeather information not found.\n') elif v2.status_code == 401: print('\nValidation error, please contact the developer.') else: ...
[]
[ "requests" ]
[ "import requests" ]
12
#!/usr/bin/env python3 import os import requests import argparse from dotenv import load_dotenv from typing import Dict, Optional from src import helpers as h path_to_env = os.path.abspath(__file__ + "/../../.env") load_dotenv(path_to_env) BASE_URL = "https://api.openweathermap.org/data/2.5/weather" API_KEY = os.ge...
null
v0
[ "dict" ]
Any
def v0(v1: dict): v2 = f"| {' | '.join([x[:10] for v3 in v1.keys()])} |" v4 = f"|{'|:'.join([3 * '-' for v3 in range(len(v1.keys()))])}|" v5 = f"| {' | '.join([str(v3) for v3 in v1.values()])} |" return '\n'.join([v2, v4, v5])
[]
[]
[]
5
import json from datetime import datetime import argparse import torch from tensorboardX import SummaryWriter from helper import Helper from models.simple import Net, NetTF import torch.nn as nn import torch.optim as optim from tqdm import tqdm as tqdm import yaml import logging logger = logging.getLogger("logger") wr...
null
v0
[ "int", "int", "bool" ]
None
def v0(self, v1: int, v2: int, v3: bool) -> None: logging.debug('sdt add link: %s, %s, %s', v1, v2, v3) if not self.connect(): return if self.wireless_net_check(v1) or self.wireless_net_check(v2): return if v3: v4 = 'green,2' else: v4 = 'red,2' self.cmd(f'link {v1...
[]
[ "logging" ]
[ "import logging" ]
11
""" sdt.py: Scripted Display Tool (SDT3D) helper """ import logging import socket import threading from typing import TYPE_CHECKING, Optional, Tuple from urllib.parse import urlparse from core import constants from core.constants import CORE_DATA_DIR from core.emane.nodes import EmaneNet from core.emulator.data impor...
null
v0
[ "int", "int" ]
None
def v0(self, v1: int, v2: int) -> None: logging.debug('sdt delete link: %s, %s', v1, v2) if not self.connect(): return if self.wireless_net_check(v1) or self.wireless_net_check(v2): return self.cmd(f'delete link,{v1},{v2}')
[]
[ "logging" ]
[ "import logging" ]
7
""" sdt.py: Scripted Display Tool (SDT3D) helper """ import logging import socket import threading from typing import TYPE_CHECKING, Optional, Tuple from urllib.parse import urlparse from core import constants from core.constants import CORE_DATA_DIR from core.emane.nodes import EmaneNet from core.emulator.data impor...
null
v0
[]
Union[int, Tuple[Any, ...]]
def v0(self) -> Union[int, Tuple[Any, ...]]: if self._flattened: return np.sum([d.get_data_dimension() for v1 in self._datasets]) else: return tuple([v1.get_data_dimension() for v1 in self._datasets])
[]
[ "numpy" ]
[ "import numpy as np" ]
5
# ----------------------------------------------------------- # Class to zip PSFDatasets, handling their extra structures. # # (C) 2020 Kevin Schlegel, Oxford, United Kingdom # Released under Apache License, Version 2.0 # email kevinschlegel@cantab.net # ----------------------------------------------------------- impor...
null
v0
[ "Optional[np.ndarray]" ]
None
def v0(self, v1: Optional[np.ndarray]) -> None: assert len(self.distributions) > 0, 'Must set distribution parameters' v2 = [None] * len(self.distributions) if v1 is not None: v1 = th.as_tensor(v1) v1 = v1.view(-1, sum(self.action_dims)) v2 = th.split(v1, tuple(self.action_dims), dim...
[]
[ "torch" ]
[ "import torch as th", "from torch import nn", "from torch.distributions import Categorical", "from torch.distributions.utils import logits_to_probs" ]
9
from abc import ABC, abstractmethod from typing import List, Optional, Tuple import numpy as np import torch as th from gym import spaces from stable_baselines3.common.distributions import Distribution from torch import nn from torch.distributions import Categorical from torch.distributions.utils import logits_to_prob...
null
v0
[]
th.Tensor
def v0(self) -> th.Tensor: assert len(self.distributions) > 0, 'Must set distribution parameters' return th.stack([dist.entropy() for v1 in self.distributions], dim=1).sum(dim=1)
[]
[ "torch" ]
[ "import torch as th", "from torch import nn", "from torch.distributions import Categorical", "from torch.distributions.utils import logits_to_probs" ]
3
from abc import ABC, abstractmethod from typing import List, Optional, Tuple import numpy as np import torch as th from gym import spaces from stable_baselines3.common.distributions import Distribution from torch import nn from torch.distributions import Categorical from torch.distributions.utils import logits_to_prob...
null
v0
[ "int" ]
nn.Module
def v0(self, v1: int) -> nn.Module: v2 = nn.Linear(v1, sum(self.action_dims)) return v2
[]
[ "torch" ]
[ "import torch as th", "from torch import nn", "from torch.distributions import Categorical", "from torch.distributions.utils import logits_to_probs" ]
3
from abc import ABC, abstractmethod from typing import List, Optional, Tuple import numpy as np import torch as th from gym import spaces from stable_baselines3.common.distributions import Distribution from torch import nn from torch.distributions import Categorical from torch.distributions.utils import logits_to_prob...
null
v0
[ "th.Tensor" ]
th.Tensor
def v0(self, v1: th.Tensor) -> th.Tensor: assert len(self.distributions) > 0, 'Must set distribution parameters' v1 = v1.view(-1, len(self.action_dims)) return th.stack([dist.log_prob(action) for (v2, v3) in zip(self.distributions, th.unbind(v1, dim=1))], dim=1).sum(dim=1)
[]
[ "torch" ]
[ "import torch as th", "from torch import nn", "from torch.distributions import Categorical", "from torch.distributions.utils import logits_to_probs" ]
4
from abc import ABC, abstractmethod from typing import List, Optional, Tuple import numpy as np import torch as th from gym import spaces from stable_baselines3.common.distributions import Distribution from torch import nn from torch.distributions import Categorical from torch.distributions.utils import logits_to_prob...
null
v0
[]
th.Tensor
def v0(self) -> th.Tensor: assert len(self.distributions) > 0, 'Must set distribution parameters' return th.stack([th.argmax(dist.probs, dim=1) for v1 in self.distributions], dim=1)
[]
[ "torch" ]
[ "import torch as th", "from torch import nn", "from torch.distributions import Categorical", "from torch.distributions.utils import logits_to_probs" ]
3
from abc import ABC, abstractmethod from typing import List, Optional, Tuple import numpy as np import torch as th from gym import spaces from stable_baselines3.common.distributions import Distribution from torch import nn from torch.distributions import Categorical from torch.distributions.utils import logits_to_prob...
null
v0
[ "th.Tensor" ]
Tuple[th.Tensor, th.Tensor]
def v0(self, v1: th.Tensor) -> Tuple[th.Tensor, th.Tensor]: v2 = self.actions_from_params(v1) v3 = self.log_prob(v2) return (v2, v3)
[]
[]
[]
4
from abc import ABC, abstractmethod from typing import List, Optional, Tuple import numpy as np import torch as th from gym import spaces from stable_baselines3.common.distributions import Distribution from torch import nn from torch.distributions import Categorical from torch.distributions.utils import logits_to_prob...
null
v0
[ "discord.User" ]
Any
def v0(self, v1: discord.User): try: return self.players[str(v1.id)] except: return None
[]
[]
[]
5
import collections import datetime import uuid import struct from queue import Queue from typing import List from .strings import Strings import discord SELECTION_MODES = { 0x1F3B2: Strings.RANDOM_TS, # game_die 0x1F1E8: Strings.CAPTAINS_TS, # C 0x0262F: Strings.BALANCED_TS, # yin_yang 0x0FE0F...
null
v0
[ "str", "Any" ]
Any
def v0(v1: str, v2): v3 = min((i for (v4, v5, v4) in v2 if v5 > 0), default=0) v6 = max((v5 for (v4, v4, v5) in v2 if v5 > 0), default=v3) return [v1, v3, v6]
[]
[]
[]
4
# parser combinators """ This module defines basic parser combinators. Each 'Parse' object transforms an 'Item' to an 'Item'. Following the class functions for Parse, we give basic parsers for words, phrases, delimited expressions, and lists """ import msg import lib import lexer import word_lists import copy f...
null
v121
[ "v0", "v0", "v0" ]
v0
def v121(v122: v0, v123: v0, v124: v0) -> v0: def v125(v126): try: v122.process(v126) except: return v124.process(v126) return v123.process(v126)
[]
[]
[]
8
# parser combinators """ This module defines basic parser combinators. Each 'Parse' object transforms an 'Item' to an 'Item'. Following the class functions for Parse, we give basic parsers for words, phrases, delimited expressions, and lists """ import msg import lib import lexer import word_lists import copy f...
[ "class v0:\n\n def __init__(self, v1):\n \"\"\"r:Item->Item, repr:str\"\"\"\n self.process = v1\n\n def v2(self, v3):\n self.repr = v3\n return self\n\n def v4():\n return v0(next_item)\n\n def v5():\n \"\"\"fails if tokens remain in stream, otherwise do nothing...
v128
[ "v0", "str", "str" ]
v0
def v128(v129: v0, v130: str, v131: str) -> v0: def v132(v133): ((v134, v135), v136) = v133 v135 = v135 if type(v135) is list else [v135] return [v134] + v135 + [v136] return (v126(v130) + v129 + v126(v131)).treat(v132)
[ { "name": "v121", "input_types": [ "Any" ], "output_type": "Any", "code": "def v121(v122):\n ((v123, v124), v125) = v122\n v124 = v124 if type(v124) is list else [v124]\n return [v123] + v124 + [v125]", "dependencies": [] }, { "name": "v126", "input_types": [ ...
[]
[]
7
# parser combinators """ This module defines basic parser combinators. Each 'Parse' object transforms an 'Item' to an 'Item'. Following the class functions for Parse, we give basic parsers for words, phrases, delimited expressions, and lists """ import msg import lib import lexer import word_lists import copy f...
[ "class v0:\n\n def __init__(self, v1):\n \"\"\"r:Item->Item, repr:str\"\"\"\n self.process = v1\n\n def v2(self, v3):\n self.repr = v3\n return self\n\n def v4():\n return v0(next_item)\n\n def v5():\n \"\"\"fails if tokens remain in stream, otherwise do nothing...
v139
[ "v0", "str", "str" ]
v0
def v139(v140: v0, v141: str, v142: str) -> v0: def v143(v144): return v144[1:-1] return v121(v140, v141, v142).treat(v143)
[ { "name": "v121", "input_types": [ "v0", "str", "str" ], "output_type": "v0", "code": "def v121(v122: v0, v123: str, v124: str) -> v0:\n\n def v125(v126):\n ((v127, v128), v129) = v126\n v128 = v128 if type(v128) is list else [v128]\n return [v127] + v12...
[]
[]
5
# parser combinators """ This module defines basic parser combinators. Each 'Parse' object transforms an 'Item' to an 'Item'. Following the class functions for Parse, we give basic parsers for words, phrases, delimited expressions, and lists """ import msg import lib import lexer import word_lists import copy f...
[ "class v0:\n\n def __init__(self, v1):\n \"\"\"r:Item->Item, repr:str\"\"\"\n self.process = v1\n\n def v2(self, v3):\n self.repr = v3\n return self\n\n def v4():\n return v0(next_item)\n\n def v5():\n \"\"\"fails if tokens remain in stream, otherwise do nothing...
v0
[ "Union[Path, str]", "Union[Path, str]" ]
pd.DataFrame
def v0(v1: Union[Path, str], v2: Union[Path, str]) -> pd.DataFrame: v3 = pd.read_csv(v2).columns.values return pd.read_csv(v1, names=v3, parse_dates=True)
[]
[ "pandas" ]
[ "import pandas as pd" ]
3
import html import io from pathlib import Path from typing import Optional, Union import pandas as pd import numpy as np import pendulum import prefect from prefect import Flow, task, unmapped from prefect.core.parameter import Parameter from prefect.engine.results import S3Result from prefect.engine.serializers impo...
null
v0
[ "str", "str" ]
str
def v0(v1: str, v2: str) -> str: assert 2010 < v2.year, 'jday must be in range >= 2010' v3 = v1.capitalize()[:3] v4 = str(v2.year)[2:4] v5 = v2.timetuple().tm_yday return f'{v3}_M_{v4}_{v5}.dat'
[]
[]
[]
6
import html import io from pathlib import Path from typing import Optional, Union import pandas as pd import numpy as np import pendulum import prefect from prefect import Flow, task, unmapped from prefect.core.parameter import Parameter from prefect.engine.results import S3Result from prefect.engine.serializers impo...
null
v0
[ "str", "Any", "Any" ]
Any
def v0(self, v1: str, v2='<input>', v3='multi'): try: v4 = self.interpreter.compile(v1, v2, v3) except (OverflowError, SyntaxError, ValueError): self.interpreter.showsyntaxerror(v2) return False if v4 is None: return True try: self.interpreter.exec(v4) pas...
[]
[]
[]
16
from matplotlib.backends.backend_qt5agg import \ FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure from .pyqtconsole.console import PythonConsole from .pyqtconsole.console import PythonInterpreter from .pyqtconsole.interpreter import redirected_io class MatplotlibPythonInterpreter(PythonInte...
null
v0
[ "int" ]
int
def v0(self, v1: int) -> int: v2 = [[i for v3 in range(5, 0, -1)] for v4 in range(v1)] for v3 in range(1, v1): for v5 in range(3, -1, -1): v2[v3][v5] = v2[v3 - 1][v5] + v2[v3][v5 + 1] return v2[v1 - 1][0]
[]
[]
[]
6
class Solution: def countVowelStrings(self, n: int) -> int: dp = [[i for i in range(5,0,-1)] for _ in range(n)] for i in range(1,n): for j in range(3,-1,-1): dp[i][j] = dp[i - 1][j] + dp[i][j + 1] return dp[n-1][0]
null
v0
[ "str", "int" ]
int
def v0(v1: str, v2: int) -> int: with open(v1) as v3: v4 = list(map(int, v3.read().split(','))) v5 = Counter(v4) for v6 in range(v2): v7 = defaultdict(int) for v8 in v5: if v8 == 0: v7[6] += v5[0] v7[8] += v5[0] else: ...
[]
[ "collections" ]
[ "from collections import Counter, defaultdict" ]
14
from collections import Counter, defaultdict def part_one(filename: str) -> int: return lanternfish_population(filename, 80) def part_two(filename: str) -> int: return lanternfish_population(filename, 256) def lanternfish_population(filename: str, days: int) -> int: with open(filename) as f: i...
null
v0
[ "str", "str" ]
Any
def v0(v1: str, v2: str): v3 = len(v1) if len(v1) >= len(v2) else len(v2) v4 = 0 v5 = math.log(v3, 2) if v5 % 1 != 0: v4 = v5 // 1 + 1 else: v4 = v5 v6 = 2 ** v4 if len(v1) < v6: v7 = '0' * int(v6 - len(v1)) v1 = v7 + v1 if len(v2) < v6: v7 = '0' *...
[]
[ "math" ]
[ "import math" ]
16
import math import functools import operator def fix_number_length(x_fix: str, y_fix: str): """ Fix the length of two number For the Karatsuba multiplication both numbers must be the same digits and the length of both numbers must be power of 2. For example, if the number is '987' then the length of ...
null
v28
[ "int", "int" ]
int
def v28(v29: int, v30: int) -> int: (v31, v32) = v0(str(v29), str(v30)) return v8(v31, v32)
[ { "name": "v0", "input_types": [ "str", "str" ], "output_type": "Any", "code": "def v0(v1: str, v2: str):\n v3 = len(v1) if len(v1) >= len(v2) else len(v2)\n v4 = 0\n v5 = math.log(v3, 2)\n if v5 % 1 != 0:\n v4 = v5 // 1 + 1\n else:\n v4 = v5\n v6 = 2 ...
[ "functools", "math", "operator" ]
[ "import math", "import functools", "import operator" ]
3
import math import functools import operator def fix_number_length(x_fix: str, y_fix: str): """ Fix the length of two number For the Karatsuba multiplication both numbers must be the same digits and the length of both numbers must be power of 2. For example, if the number is '987' then the length of ...
null
v4
[ "str", "str" ]
bool
def v4(self, v5: str, v6: str) -> bool: def v7(v8): v9 = {} for v10 in v8: if v10 not in v9: v9[v10] = 0 v9[v10] += 1 return v9 v11 = v7(v5) for v12 in range(0, len(v6) - len(v5) + 1): if v7(v6[v12:v12 + len(v5)]) == v11: r...
[ { "name": "v0", "input_types": [ "Any" ], "output_type": "Any", "code": "def v0(v1):\n v2 = {}\n for v3 in v1:\n if v3 not in v2:\n v2[v3] = 0\n v2[v3] += 1\n return v2", "dependencies": [] } ]
[]
[]
14
class Solution: def checkInclusion(self, s1: str, s2: str) -> bool: def to_dict(s): hash_map = {} for c in s: if c not in hash_map: hash_map[c] = 0 hash_map[c] += 1 return hash_map hash_map = to_...
null
v0
[ "Any", "Any" ]
List
def v0(v1, v2) -> List: v3 = len(v1) v4 = [] v5 = 0 while v1: v6 = v1.find(v2, v5, v3) if v6 != -1: v4.append(v6) v5 += 2 elif v6 == -1: break return v4
[]
[]
[]
12
""" Given a string, we need to find , if it contains AB, and BA seperately and they are non-overlapping The strings can be in any order. """ from typing import List p = 31 m = 10 ** 9 + 9 def compute_hash(s): n = len(s) power_mod = [1] for i in range(n): power_mod.append((power_mod[-1] * p) % m)...
null
v0
[ "int", "Any" ]
Any
def v0(self, v1: int=3, v2=None): if isinstance(v2, list) or isinstance(v2, np.ndarray): v3 = [indv is None for v4 in v2] if any(v3): v5 = self.rng.choice(np.arange(len(self.population)), v1, replace=False) return np.array(self.population)[v5] else: if len...
[]
[ "numpy" ]
[ "import numpy as np" ]
15
import numpy as np # from xbbo.configspace.feature_space import Uniform2Gaussian from xbbo.search_algorithm.base import AbstractOptimizer from xbbo.configspace.space import DenseConfiguration, DenseConfigurationSpace from xbbo.core.trials import Trials, Trial from . import alg_register @alg_register.register('de') c...
null
v0
[ "int" ]
bool
def v0(v1: int) -> bool: if v1 <= 3: return v1 > 1 elif not v1 % 2 or not v1 % 3: return False v2 = 5 while v2 ** 2 <= v1: if not v1 % v2 or not v1 % (v2 + 2): return False v2 += 6 return True
[]
[]
[]
11
# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. # # Find the sum of all the primes below two million. def is_prime(n: int) -> bool: if n <= 3: return n > 1 elif not n%2 or not n%3: return False i = 5 while i**2 <= n: if not n%i or not n%(i+2): return False i += 6 return Tru...
null
v0
[ "str", "List[str]", "Any" ]
int
def v0(self, v1: str, v2: List[str], v3=0) -> int: v4 = set(v1) for v5 in v2: if all([c in v4 for v6 in v5]): v3 += 1 return v3
[]
[]
[]
6
# # 1684. Count the Number of Consistent Strings # # Q: https://leetcode.com/problems/count-the-number-of-consistent-strings/ # A: https://leetcode.com/problems/count-the-number-of-consistent-strings/discuss/969513/Kt-Js-Py3-Cpp-1-Liners # from typing import List # 1-liner class Solution: def countConsistentStrin...
null
v0
[]
None
def v0(self, *v1, **v2) -> None: (v1, v2) = self.scatter(v1, v2, self.device_id) if not v1 and (not v2): v1 = ((),) v2 = ({},) return self.module.before_forward_support(*v1[0], **v2[0])
[]
[]
[]
6
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcv.parallel.scatter_gather import scatter_kwargs class MetaTestParallel(nn.Module): """The MetaTestParallel module that supports DataContainer. Note that each task is tested on a single GPU. Thus the data and model on different ...
null
v0
[ "List[str]" ]
Any
def v0(self, v1: List[str]): if len(v1) == 0: return 1 return len([m for v2 in v1 if v2 in [machine.name for v3 in self.hosts]]) / len(v1)
[]
[]
[]
4
"""This module implements some machine clustering specific to H2.""" import pandas as pd from typing import List, Set from waad.utils.asset import Machine from waad.utils.clustering import LongestCommonSubstringClustering class H2SpecificClustering(LongestCommonSubstringClustering): """H2 very specific cluste...
null
v0
[ "Any", "dict", "dict" ]
Any
def v0(v1, v2: dict={'labels': [0, 1], 'predictions': [0, 1], 'masks': [1, 0]}, v3: dict={'train': {'accuracy': 1}}): v1.after_batch(stream_name='train', batch_data=v2) v1.after_epoch(epoch_id=0, epoch_data=v3) return v3
[]
[]
[]
4
""" Test case for :py:class:`emloop.hooks.SaveConfusionMatrix hook. """ import os import matplotlib import pytest from emloop.hooks.save_cm import SaveConfusionMatrix from ..main_loop_test import SimpleDataset class MockDataset(SimpleDataset): @staticmethod def num_classes(): return 4 @staticme...
null
v0
[ "List[int]", "List[int]" ]
int
def v0(self, v1: List[int], v2: List[int]) -> int: v3 = v1[-1] v4 = [0] * (v3 + 1) for v5 in range(0, v3 + 1): if v5 in v1: if v5 < 7: v4[v5] = min(v4[v5 - 1] + v2[0], v2[1], v2[2]) elif v5 < 30: v4[v5] = min(v4[v5 - 1] + v2[0], v4[v5 - 7] + v2...
[]
[]
[]
14
# 在一个火车旅行很受欢迎的国度,你提前一年计划了一些火车旅行。在接下来的一年里,你要旅行的日子将以一个名为 days 的数组给出。每一项是一个从 1 到 365 的整数。 # # 火车票有三种不同的销售方式: # # 一张为期一天的通行证售价为 costs[0] 美元; # 一张为期七天的通行证售价为 costs[1] 美元; # 一张为期三十天的通行证售价为 costs[2] 美元。 # 通行证允许数天无限制的旅行。 例如,如果我们在第 2 天获得一张为期 7 天的通行证,那么我们可以连着旅行 7 天:第 2 天、第 3 天、第 4 天、第 5 天、第 6 天、第 7 天和第 8 天。 # # 返回你想要完成在给定的列表 day...
null
v14
[ "int", "Any" ]
Any
def v14(self, v15: int, v16): v17 = self.queue.get_new_index(v15) v18 = self.queue[v17] v18.dat.p = v16 self.queue[v17] = v18 v7(self.queue, v17)
[ { "name": "v0", "input_types": [ "Any", "Any", "Any" ], "output_type": "Any", "code": "def v0(v1, v2, v3):\n v4 = v1[v3]\n while v3 > v2:\n v5 = v3 - 1 >> 1\n v6 = v1[v5]\n if v4 < v6:\n v1[v3] = v6\n v3 = v5\n continu...
[]
[]
6
from queue import Queue from typing import List class QNode: def __init__(self, dat, index): self.dat = dat self.index = index def __repr__(self): return f'QNode({self.dat}, index={self.index})' def __lt__(self, other): return self.dat < other.dat def __eq__(self, ot...
null
v0
[ "Type" ]
bool
def v0(v1: Type) -> bool: if hasattr(typing, '_GenericAlias'): return isinstance(v1, typing._GenericAlias) and v1.__origin__ is list else: return isinstance(v1, typing.GenericMeta) and v1.__origin__ is List
[]
[ "typing" ]
[ "import typing", "from typing import Dict, List, NewType, Type, Union" ]
5
from datetime import datetime import typing from typing import Dict, List, NewType, Type, Union bool_union_fix = NewType('bool_union_fix', bool) scalar_type_to_tag = { str: 'tag:yaml.org,2002:str', int: 'tag:yaml.org,2002:int', float: 'tag:yaml.org,2002:float', bool: 'tag:yaml.org,2002:bool', boo...
null
v0
[ "Type" ]
bool
def v0(v1: Type) -> bool: if hasattr(typing, '_GenericAlias'): return isinstance(v1, typing._GenericAlias) and v1.__origin__ is Union elif hasattr(typing, '_Union'): return isinstance(v1, typing._Union) else: return isinstance(v1, typing.UnionMeta) raise RuntimeError('Could not d...
[]
[ "typing" ]
[ "import typing", "from typing import Dict, List, NewType, Type, Union" ]
8
from datetime import datetime import typing from typing import Dict, List, NewType, Type, Union bool_union_fix = NewType('bool_union_fix', bool) scalar_type_to_tag = { str: 'tag:yaml.org,2002:str', int: 'tag:yaml.org,2002:int', float: 'tag:yaml.org,2002:float', bool: 'tag:yaml.org,2002:bool', boo...
null
v0
[ "Type" ]
List[Type]
def v0(v1: Type) -> List[Type]: if hasattr(v1, '__union_params__'): return list(v1.__union_params__) return list(v1.__args__)
[]
[]
[]
4
from datetime import datetime import typing from typing import Dict, List, NewType, Type, Union bool_union_fix = NewType('bool_union_fix', bool) scalar_type_to_tag = { str: 'tag:yaml.org,2002:str', int: 'tag:yaml.org,2002:int', float: 'tag:yaml.org,2002:float', bool: 'tag:yaml.org,2002:bool', boo...
null
v0
[ "str" ]
str
def v0(v1: str) -> str: if 'www.wikidata.org' in v1 and '/' in v1: v2 = v1.rindex('/') return v1[v2 + 1:] return v1
[]
[]
[]
5
def get_wiki_id(resource: str) -> str: '''Return Wikidata id (e.g. P31 or Q42).''' if "www.wikidata.org" in resource and "/" in resource: index = resource.rindex("/") return resource[index + 1:] return resource
null