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
[ "int", "int", "float", "float", "float" ]
Any
def v0(v1: int, v2: int, v3: float, v4: float, v5: float): v6 = np.eye(3, dtype=np.float32) v7 = v1 / 2 / math.tan(v4 / 2) v8 = v2 / 2 / math.tan(v5 / 2) v9 = v1 / 2 v10 = v2 / 2 v6[0, 0] = v7 v6[1, 1] = v8 v6[0, 2] = v9 v6[1, 2] = v10 return v6
[]
[ "math", "numpy" ]
[ "import math", "import numpy as np" ]
11
import concurrent.futures import itertools import json import logging import math import random from dataclasses import dataclass from pathlib import Path from typing import List, Dict import cv2 import hydra import jsonlines import numpy as np from omegaconf import OmegaConf, DictConfig from scipy.spatial.transform i...
null
v0
[ "np.ndarray" ]
np.ndarray
def v0(v1: np.ndarray) -> np.ndarray: if v1.shape != (4, 4): raise ValueError(f'The transform matrix must be of shape [4, 4]. Given: {v1.shape}') v2 = v1.astype(np.float64) v3 = v2[:3, :3] v4 = v2[:3, 3] v5 = np.linalg.inv(v3) v6 = -1 * (v5 @ v4) v7 = np.eye(4, dtype=np.float64) ...
[]
[ "numpy" ]
[ "import numpy as np" ]
12
import concurrent.futures import itertools import json import logging import math import random from dataclasses import dataclass from pathlib import Path from typing import List, Dict import cv2 import hydra import jsonlines import numpy as np from omegaconf import OmegaConf, DictConfig from scipy.spatial.transform i...
null
v7
[ "np.ndarray", "np.ndarray", "List" ]
None
def v7(v8: np.ndarray, v9: np.ndarray, v10: List) -> None: for v11 in v9: v8 = cv2.circle(v8, tuple(v11), 1, v10, -1) def v12(v13, v14, v15, v16, v17): v18 = cv2.line(v13, tuple(v14[v16]), tuple(v14[v17]), v15, 1) return v18 v8 = v12(v8, v9, v10, 0, 1) v8 = v12(v8, v9, v10, 1, 2...
[ { "name": "v0", "input_types": [ "Any", "Any", "Any", "Any", "Any" ], "output_type": "Any", "code": "def v0(v1, v2, v3, v4, v5):\n v6 = cv2.line(v1, tuple(v2[v4]), tuple(v2[v5]), v3, 1)\n return v6", "dependencies": [] } ]
[ "cv2" ]
[ "import cv2" ]
20
import concurrent.futures import itertools import json import logging import math import random from dataclasses import dataclass from pathlib import Path from typing import List, Dict import cv2 import hydra import jsonlines import numpy as np from omegaconf import OmegaConf, DictConfig from scipy.spatial.transform i...
null
v74
[ "Path", "Path", "Path", "np.ndarray", "Dict", "int", "str" ]
Any
def v74(v75: Path, v76: Path, v77: Path, v78: np.ndarray, v79: Dict, v80: int, v81: str='.bbox.png'): v82 = v61(v75) v83 = v61(v76) if v82 != v83: raise ValueError(f'The RGB file ({v75.name}) and Info file ({v76.name}) do not match. They are of different render IDs.') v84 = v6(v76, v77, v78, v79...
[ { "name": "v6", "input_types": [ "Path", "Path", "np.ndarray", "Dict", "int" ], "output_type": "List[v0]", "code": "def v6(v7: Path, v8: Path, v9: np.ndarray, v10: Dict, v11: int) -> List[v0]:\n v12 = get_renderid(v7)\n with v7.open() as v13:\n v14 = js...
[ "cv2", "json", "numpy", "random", "scipy" ]
[ "import json", "import random", "import cv2", "import numpy as np", "from scipy.spatial.transform import Rotation as R" ]
16
import concurrent.futures import itertools import json import logging import math import random from dataclasses import dataclass from pathlib import Path from typing import List, Dict import cv2 import hydra import jsonlines import numpy as np from omegaconf import OmegaConf, DictConfig from scipy.spatial.transform i...
[ "@dataclass\nclass v0:\n v1: int\n v2: np.ndarray\n v3: np.ndarray\n v4: np.ndarray\n v5: np.ndarray" ]
v0
[ "Tuple[str, int, int, int]", "Any", "Any", "Any", "Any" ]
Any
def v0(v1: Tuple[str, int, int, int], v2=12, v3=False, v4=False, v5=False): v6 = {} v6['player_id'] = v1[3] v6['score'] = v1[1] if v2 != v1[2]: v6['races'] = v1[2] if v3: v6['subbed_in'] = True if v4: v6['subbed_out'] = True if v2 != 12: v6['multiplier'] = rou...
[]
[]
[]
13
''' Created on Sep 23, 2020 @author: willg This module does all the heavy lifting for the commands ?rtmogiupdate and ?ctmogiupdate Interestingly, we have to recreate Lorenzi's table text parser without any knowledge, except for trying different things on his website and seeing how his parser reacts Even if we don't r...
null
v13
[ "List[List[Tuple[str, int, int]]]", "Any", "Any" ]
Any
def v13(v14: List[List[Tuple[str, int, int]]], v15=12, v16=False): v17 = [] for v18 in v14: v19 = [] for v20 in v18: v21 = len(v20) - 1 for (v22, v23) in enumerate(v20): v24 = False v25 = False if v21 > 0: ...
[ { "name": "v0", "input_types": [ "Tuple[str, int, int, int]", "Any", "Any", "Any", "Any" ], "output_type": "Any", "code": "def v0(v1: Tuple[str, int, int, int], v2=12, v3=False, v4=False, v5=False):\n v6 = {}\n v6['player_id'] = v1[3]\n v6['score'] = v1[1]\...
[]
[]
20
''' Created on Sep 23, 2020 @author: willg This module does all the heavy lifting for the commands ?rtmogiupdate and ?ctmogiupdate Interestingly, we have to recreate Lorenzi's table text parser without any knowledge, except for trying different things on his website and seeing how his parser reacts Even if we don't r...
null
v6
[ "List[str]" ]
Any
def v6(v7: List[str]): for (v8, v9) in enumerate(v7): if v9.startswith('#'): continue if v3(v9): for v9 in v7[v8:]: if v9.startswith('#'): continue if not v3(v9): return None return True ...
[ { "name": "v0", "input_types": [ "str" ], "output_type": "Any", "code": "def v0(v1: str):\n v2 = v1.lower().strip()\n if len(v2) < 7:\n return False\n return v2[-1] in hex_code_chars and v2[-2] in hex_code_chars and (v2[-3] in hex_code_chars) and (v2[-4] in hex_code_chars) ...
[]
[]
14
''' Created on Sep 23, 2020 @author: willg This module does all the heavy lifting for the commands ?rtmogiupdate and ?ctmogiupdate Interestingly, we have to recreate Lorenzi's table text parser without any knowledge, except for trying different things on his website and seeing how his parser reacts Even if we don't r...
null
v6
[ "List[str]" ]
Any
def v6(v7: List[str]): v8 = True v9 = 0 for v10 in v7: if v10.startswith('#'): continue if v3(v10): if v8: v9 += 1 v8 = False else: v8 = True return v9
[ { "name": "v0", "input_types": [ "str" ], "output_type": "Any", "code": "def v0(v1: str):\n v2 = v1.lower().strip()\n if len(v2) < 7:\n return False\n return v2[-1] in hex_code_chars and v2[-2] in hex_code_chars and (v2[-3] in hex_code_chars) and (v2[-4] in hex_code_chars) ...
[]
[]
13
''' Created on Sep 23, 2020 @author: willg This module does all the heavy lifting for the commands ?rtmogiupdate and ?ctmogiupdate Interestingly, we have to recreate Lorenzi's table text parser without any knowledge, except for trying different things on his website and seeing how his parser reacts Even if we don't r...
null
v0
[ "str" ]
Any
def v0(v1: str): if v1 == '': return 0 v1 = v1.rstrip('+-') if v1 == '': return 0 v2 = '' v3 = False for v4 in v1[::-1]: if v4.isnumeric(): v2 = v4 + v2 elif v4 == '-': v3 = True if v2 == '': return 0 if not v2.isnumeric(): ...
[]
[]
[]
21
''' Created on Sep 23, 2020 @author: willg This module does all the heavy lifting for the commands ?rtmogiupdate and ?ctmogiupdate Interestingly, we have to recreate Lorenzi's table text parser without any knowledge, except for trying different things on his website and seeing how his parser reacts Even if we don't r...
null
v33
[ "str", "Any", "Any" ]
Any
def v33(v34: str, v35, v36=12): v37 = [] v38 = 0 v39 = 0 for (v40, v41) in enumerate(v34): if v41 == ')': v39 = v40 + 1 v37.append(v34[v38:v39].strip(' /\\|-')) v38 = v40 + 1 else: v37.append(v34[v38:].strip(' /\\|-')) v42 = [] for (v40, v4...
[ { "name": "v0", "input_types": [ "Any" ], "output_type": "Any", "code": "def v0(v1):\n v2 = 0\n for (v3, v4) in v1:\n v5 = v4 // 4\n v6 = 0 if v4 % 4 == 0 else 1\n v2 += v5 + v6\n return v2", "dependencies": [] }, { "name": "v7", "input_types":...
[]
[]
31
''' Created on Sep 23, 2020 @author: willg This module does all the heavy lifting for the commands ?rtmogiupdate and ?ctmogiupdate Interestingly, we have to recreate Lorenzi's table text parser without any knowledge, except for trying different things on his website and seeing how his parser reacts Even if we don't r...
null
v0
[ "Tensor", "Tensor" ]
Tensor
def v0(self, v1: Tensor, v2: Tensor) -> Tensor: v3 = v2.to(dtype=self.theta['W'].dtype) v4 = to.matmul(v3, self.theta['W'].t()) v5 = to.matmul(v3, to.log(self.theta['pies'] / (1 - self.theta['pies']))) if self.config['individual_priors'] else to.log(self.theta['pies'] / (1 - self.theta['pies'])) * v3.sum(di...
[]
[ "torch" ]
[ "import torch as to", "from torch import Tensor" ]
6
# -*- coding: utf-8 -*- # Copyright (C) 2019 Machine Learning Group of the University of Oldenburg. # Licensed under the Academic Free License version 3.0 import math import torch as to from torch import Tensor from typing import Union, Tuple import tvo from tvo.utils.parallel import pprint, all_reduce, broadcast fr...
null
v0
[ "Tensor", "Tensor", "Tensor" ]
Tensor
def v0(self, v1: Tensor, v2: Tensor, v3: Tensor=None) -> Tensor: if v3 is None: v3 = self.log_pseudo_joint(v1, v2) v4 = to.sum(to.logical_not(to.isnan(v1)), dim=1) v5 = self.shape[1] v6 = to.log(1 - self.theta['pies']).sum() if self.config['individual_priors'] else v5 * to.log(1 - self.theta['pi...
[]
[ "math", "torch" ]
[ "import math", "import torch as to", "from torch import Tensor" ]
7
# -*- coding: utf-8 -*- # Copyright (C) 2019 Machine Learning Group of the University of Oldenburg. # Licensed under the Academic Free License version 3.0 import math import torch as to from torch import Tensor from typing import Union, Tuple import tvo from tvo.utils.parallel import pprint, all_reduce, broadcast fr...
null
v0
[]
None
def v0(self) -> None: self.enc.apply(self._maybe_reset_parameters) self.clf.apply(self._maybe_reset_parameters)
[]
[]
[]
3
"""ERM Baseline Model.""" from typing import Dict, List, Literal, Tuple import ethicml as em import pandas as pd import pytorch_lightning as pl import torch import torchmetrics from kit import implements from torch import Tensor, nn, optim from torch.optim.lr_scheduler import _LRScheduler from fair_bolts.datasets.eth...
null
v15
[ "'Resource'", "'Resource'" ]
bool
def v15(v16: 'Resource', v17: 'Resource') -> bool: if v5(from_resource=v17, to_resource=v16): return False v0(v16, v17) return True
[ { "name": "v0", "input_types": [ "'Resource'", "'Resource'" ], "output_type": "None", "code": "def v0(v1: 'Resource', v2: 'Resource') -> None:\n return setattr(v1, _DEPENDENCIES_PROPERTY, _deps(v1) | set([v2]))", "dependencies": [ "v3" ] }, { "name": "v3", ...
[]
[]
5
# Copyright 2016-2021, Pulumi Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
null
v7
[ "'Resource'", "'Resource'" ]
bool
def v7(v8: 'Resource', v9: 'Resource') -> bool: v10: Set['Resource'] = set() for v11 in v2(v8, v10): if v11 == v9: return True return False
[ { "name": "v0", "input_types": [ "'Resource'" ], "output_type": "Set['Resource']", "code": "def v0(v1: 'Resource') -> Set['Resource']:\n return getattr(v1, _DEPENDENCIES_PROPERTY, set())", "dependencies": [] }, { "name": "v2", "input_types": [ "'Resource'", "...
[]
[]
6
# Copyright 2016-2021, Pulumi Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
null
v0
[ "Any" ]
bool
def v0(self, v1) -> bool: for v2 in self.control_sources: (v3, v4) = self._find_data(v2, v1) if v3 is None: return True for v2 in self.instrument_sources: (v3, v5) = self._find_data(v2, v1) if v3 is None: return True v6 = {k.partition('.')[0] for v...
[]
[]
[]
15
# coding: utf-8 """ Collection of classes and functions to help reading HDF5 file generated at The European XFEL. Copyright (c) 2017, European X-Ray Free-Electron Laser Facility GmbH All rights reserved. You should have received a copy of the 3-Clause BSD License along with this program. If not, see <https://opensour...
null
v0
[ "List[int]" ]
int
def v0(self, v1: List[int]) -> int: v2 = 0 v3 = 0 for v4 in range(len(v1) - 1): if v1[v4] == 1: v2 += 1 elif v1[v4] == 0: if v2 > v3: v3 = v2 v2 = 0 if len(v1) - 1 >= 0: if v1[len(v1) - 1] == 1: v2 += 1 i...
[]
[]
[]
20
from typing import List class Solution: def findMaxConsecutiveOnes(self, nums: List[int]) -> int: max_num = 0 max_num_g = 0 for idx in range(len(nums) - 1): if nums[idx] == 1: max_num += 1 elif nums[idx] == 0: if max_num > max_num_g: ...
null
v0
[ "list[str]" ]
typing.Optional[str]
def v0(v1: list[str]) -> typing.Optional[str]: v2 = 'Please select the command to run (invalid input will run no commands):' for (v3, v4) in enumerate(v1): v2 += f'\n {v3 + 1} ) {v4}' v2 += '\nselection: ' v5 = input(v2) try: return v1[int(v5) - 1] except IndexError: pri...
[]
[]
[]
13
import argparse import logging import os import shlex import sys import subprocess import typing from undo import expand from undo import history from undo import resolve from undo import utils def default_include_dirs(): return ":".join([ os.path.join(os.sep, "usr", "share", "undo"), os.path.joi...
null
v6
[ "list[str]" ]
typing.Optional[str]
def v6(v7: list[str]) -> typing.Optional[str]: if len(v7) == 1: v8 = input(f"run command '{v7[0]}'? [Y/n] ").lower() return v7[0] if v8 == 'y' or v8 == '' else None return v0(v7)
[ { "name": "v0", "input_types": [ "list[str]" ], "output_type": "typing.Optional[str]", "code": "def v0(v1: list[str]) -> typing.Optional[str]:\n v2 = 'Please select the command to run (invalid input will run no commands):'\n for (v3, v4) in enumerate(v1):\n v2 += f'\\n {v3 + ...
[]
[]
5
import argparse import logging import os import shlex import sys import subprocess import typing from undo import expand from undo import history from undo import resolve from undo import utils def default_include_dirs(): return ":".join([ os.path.join(os.sep, "usr", "share", "undo"), os.path.joi...
null
v3
[ "v0" ]
List[int]
def v3(v4: v0) -> List[int]: if not v4: return [] v5 = [] while v4: v5.append(v4.val) v4 = v4.next return v5
[]
[]
[]
8
from typing import List # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def isPalindrome(self, head: ListNode) -> bool: if not head or not head.next: return True # find the mid...
[ "class v0:\n\n def __init__(self, v1=0, v2=None):\n self.val = v1\n self.next = v2" ]
v0
[ "Dict" ]
int
def v0(v1: Dict) -> int: v2 = 0 for (v3, v4) in v1.items(): if type(v3) == int: v2 += v3 if type(v4) == int: v2 += v4 return v2
[]
[]
[]
8
""" Given an object/dictionary with keys and values that consist of both strings and integers, design an algorithm to calculate and return the sum of all of the numeric values. For example, given the following object/dictionary as input: { "cat": "bob", "dog": 23, 19: 18, 90: "fish" } Your algorithm should...
null
v0
[ "str" ]
Any
def v0(self, v1: str): v2 = v1.split('\t') try: v3 = v2[0] v4 = v2[1] v5 = v2[2] v6 = v2[3] v7 = v2[4] v8 = v2[5] v9 = v2[6] v8 = v2[7] v10 = v2[8] (v11, v12) = self._parse_gene_details(v10) except IndexError: raise Exce...
[]
[]
[]
22
class CSVPreparationManager: def __init__(self, path='output/', output='output/'): self.input_path = path self.output_path = output def gff_data_to_csv(self, filename): f_in, f_out = self._gff_csv_stream(filename) f_out.write("name,ID,chr,feature,strand,start,end") whi...
null
v0
[ "str" ]
Any
def v0(self, v1: str): v2 = v1.split(';') v3 = {} for v4 in v2: if v4: v5 = v4.split('=')[0] v6 = v4.split('=')[1] if v6[0] == ':': v6 = v6[1:] v3[v5] = v6 if 'ID' not in v3.keys() and 'Name' not in v3.keys(): raise Exceptio...
[]
[]
[]
13
class CSVPreparationManager: def __init__(self, path='output/', output='output/'): self.input_path = path self.output_path = output def gff_data_to_csv(self, filename): f_in, f_out = self._gff_csv_stream(filename) f_out.write("name,ID,chr,feature,strand,start,end") whi...
null
v0
[ "Any" ]
bool
def v0(v1: Any) -> bool: if not isinstance(v1, str): return v1 return bool(v1) and v1.lower() not in ('false', 'no', '0')
[]
[]
[]
4
import dataclasses import os from pathlib import Path from typing import Any, Callable, Dict, Iterator, MutableMapping, Optional, TypeVar import click import platformdirs import tomlkit from pdm import termui from pdm.exceptions import NoConfigError from pdm.utils import get_pypi_source T = TypeVar("T") def load_c...
null
v0
[ "Any", "Any" ]
Dict
def v0(v1, v2) -> Dict: if isinstance(v2, str): return {v2: v1} else: return dict(zip(v2, v1))
[]
[]
[]
5
"""Generic Iter Utilities""" from typing import Tuple, Dict import types def to_flat_tuple(items) -> Tuple: """Convert nested list, tuples and generators to a flat tuple. Flatten any nested structure of items. Will unpack lists, tuple and generators. Any other type will not be unpacked, meaning that you...
null
v0
[ "Dict", "Any" ]
Any
def v0(v1: Dict, v2): if isinstance(v2, str): return v1[v2] else: return tuple((v1[key] for v3 in v2))
[]
[]
[]
5
"""Generic Iter Utilities""" from typing import Tuple, Dict import types def to_flat_tuple(items) -> Tuple: """Convert nested list, tuples and generators to a flat tuple. Flatten any nested structure of items. Will unpack lists, tuple and generators. Any other type will not be unpacked, meaning that you...
null
v0
[ "str" ]
Any
def v0(v1: str): v2 = open(v1, 'r') return [line.strip() for v3 in v2.readlines()]
[]
[]
[]
3
""" This is module for skyscrapers.py program """ def read_input(path: str): """ Read game board file from path. Return list of str. """ file = open(path, 'r') return [line.strip() for line in file.readlines()] def left_to_right_check(input_line, pivot): """ str, int -> bool Chec...
null
v0
[ "str", "str", "dict", "bool" ]
dict
def v0(self, v1: str, v2: str, v3: dict, v4: bool) -> dict: v5 = '/graphql' if v4 is False: v6 = self.get_api_token() self._headers['Authorization'] = f'Bearer {v6}' v7 = {'operationName': v1, 'query': v2, 'variables': v3} v8 = self._http_request(url_suffix=v5, method='POST', json_data=v...
[]
[]
[]
8
import demistomock as demisto # noqa: F401 from CommonServerPython import * # noqa: F401 import json import urllib3 import traceback from typing import Tuple, List, Dict from datetime import date import dateparser # Disable insecure warnings urllib3.disable_warnings() ''' CONSTANTS ''' DATE_TIME_FORMAT = "%Y-%m-%...
null
v0
[ "Union[str, List[str], Tuple[str]]", "str" ]
Any
def v0(v1: Union[str, List[str], Tuple[str]], v2: str): if isinstance(v1, str): v1 = v1.replace('B-', '').replace('I-', '') if v1 == v2: return True elif isinstance(v1, list): v1 = [lbl.replace('B-', '').replace('I-', '') for v3 in v1] if len(set(v1)) == 1 and v1[0] =...
[]
[]
[]
12
from typing import Union, List, Tuple def check_bio_labels(input_labels: Union[str, List[str], Tuple[str]], query_label: str): """ Checks whether the input-labels and queried labels are the same. :param input_labels: :param query_label: :return: >>> input_labels = ["B-Loc", "I-Loc"] >>> qu...
null
v0
[ "bool" ]
None
def v0(self, *, v1: bool=True) -> None: if not self.can_go_back(): return self._stack.pop() v2 = self._stack[-1] self.data = copy.deepcopy(v2.db_data) if v1: self._stack.pop() self.run(v2.action, *v2.args, **v2.kwargs)
[]
[ "copy" ]
[ "import copy" ]
9
# -*- coding: utf-8 -*- # # Electrum - lightweight Bitcoin client # Copyright (C) 2016 Thomas Voegtlin # # 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 witho...
null
v0
[]
None
def v0(self) -> None: self.set_models({'meeting/222': {'name': 'name_SNLGsvIV'}}) v1 = {'name': 'Test', 'meeting_id': 222, 'width': 100, 'aspect_ratio_numerator': 101, 'aspect_ratio_denominator': 102, 'color': '#ff0000', 'background_color': '#036aee', 'header_background_color': '#123456', 'header_font_color': '...
[]
[]
[]
6
from openslides_backend.models.models import Projector from openslides_backend.permissions.permissions import Permissions from tests.system.action.base import BaseActionTestCase class ProjectorCreateActionTest(BaseActionTestCase): def test_create_correct_and_defaults(self) -> None: self.set_models( ...
null
v0
[]
None
def v0(self) -> None: self.create_model('meeting/222', {'name': 'name_SNLGsvIV'}) v1 = self.request('projector.create', {'name': 'Test', 'meeting_id': 222, 'color': 'fg0000'}) self.assert_status_code(v1, 400) self.assertIn('data.color must match pattern', v1.json['message'])
[]
[]
[]
5
from openslides_backend.models.models import Projector from openslides_backend.permissions.permissions import Permissions from tests.system.action.base import BaseActionTestCase class ProjectorCreateActionTest(BaseActionTestCase): def test_create_correct_and_defaults(self) -> None: self.set_models( ...
null
v0
[]
None
def v0(self) -> None: self.create_model('meeting/222', {'name': 'name_SNLGsvIV'}) v1 = self.request('projector.create', {'name': 'Test', 'meeting_id': 222, 'width': -2}) self.assert_status_code(v1, 400) self.assertIn('data.width must be bigger than or equal to 1', v1.json['message'])
[]
[]
[]
5
from openslides_backend.models.models import Projector from openslides_backend.permissions.permissions import Permissions from tests.system.action.base import BaseActionTestCase class ProjectorCreateActionTest(BaseActionTestCase): def test_create_correct_and_defaults(self) -> None: self.set_models( ...
null
v0
[]
None
def v0(self) -> None: self.create_model('meeting/222', {'name': 'name_SNLGsvIV'}) v1 = self.request('projector.create', {'name': 'Test', 'meeting_id': 222, 'used_as_default_$_in_meeting_id': {'topics': 222}}) self.assert_status_code(v1, 200) self.assert_model_exists('projector/1', {'used_as_default_$_in...
[]
[]
[]
6
from openslides_backend.models.models import Projector from openslides_backend.permissions.permissions import Permissions from tests.system.action.base import BaseActionTestCase class ProjectorCreateActionTest(BaseActionTestCase): def test_create_correct_and_defaults(self) -> None: self.set_models( ...
null
v0
[]
None
def v0(self) -> None: self.set_models({'meeting/222': {'name': 'name_SNLGsvIV', 'projector_ids': [1]}, 'projector/1': {'name': 'Projector1', 'meeting_id': 222}}) v1 = self.request('projector.update', {'id': 1, 'used_as_default_$_in_meeting_id': {'xxxtopics': 222}}) self.assert_status_code(v1, 400) self....
[]
[]
[]
5
from openslides_backend.permissions.permissions import Permissions from tests.system.action.base import BaseActionTestCase class ProjectorUpdate(BaseActionTestCase): def setUp(self) -> None: super().setUp() self.permission_test_model = { "projector/111": {"name": "name_srtgb123", "meet...
null
v0
[ "int" ]
int
def v0(self, v1: int) -> int: if v1 < 0: return 0 elif v1 == 0: return 1 else: return self.triple_step(v1 - 1) + self.triple_step(v1 - 2) + self.triple_step(v1 - 3)
[]
[]
[]
7
""" Triple Step A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs. """ from typing import List # Time: O(n) # Space: O(n) # Top-down memoization solution class Solution1: def...
null
v0
[ "int", "List[int]" ]
int
def v0(self, v1: int, v2: List[int]) -> int: if v1 < 0: return 0 elif v1 == 0: return 1 elif v2[v1] == 0: v2[v1] = self._triple_step(v1 - 1, v2) + self._triple_step(v1 - 2, v2) + self._triple_step(v1 - 3, v2) return v2[v1]
[]
[]
[]
8
""" Triple Step A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs. """ from typing import List # Time: O(n) # Space: O(n) # Top-down memoization solution class Solution1: def...
null
v0
[ "Any", "int", "int", "Any" ]
Any
def v0(v1, v2: int, v3: int, v4): print(f'Processing {v2}->{v3}') for v5 in range(v2, v3): v6 = v1[v5] print(f'Converting {v5}"th RGB to grayscale object class img...') print(v6)
[]
[]
[]
6
""" Brief multiprocessing example """ from mseg.utils.multiprocessing_utils import ( send_list_to_workers, send_sublists_to_workers, ) def worker(full_img_list, start_idx: int, end_idx: int, kwargs): """ Worker process. """ print(f"Processing {start_idx}->{end_idx}") # process each image...
null
v0
[ "str" ]
str
def v0(self, v1: str) -> str: v2 = len(v1) v3 = 0 v4 = -1 for v5 in range(v2): if v1[v5] == '0': v3 += 1 if v4 == -1: v4 = v5 if v4 == -1: return v1 return '1' * (v4 + v3 - 1) + '0' + '1' * (v2 - v4 - v3)
[]
[]
[]
12
from typing import List class Solution: def maximumBinaryString(self, binary: str) -> str: n = len(binary) cnt0 = 0 start = -1 for i in range(n): if binary[i] == '0': cnt0 += 1 if start == -1: start = i if start...
null
v0
[ "Dict[str, Any]" ]
Dict[str, Any]
def v0(v1: Dict[str, Any]) -> Dict[str, Any]: v2: Dict[str, Any] = {} for (v3, v4) in v1.items(): if not isinstance(v4, datetime): v2[v3] = v4 elif v4.hour != 0 or v4.minute != 0 or v4.second != 0: v2[v3] = v4.strftime('%Y-%m-%d %H:%M:%S') else: v2[v3]...
[]
[ "datetime" ]
[ "from datetime import datetime" ]
10
from dataclasses import dataclass from datetime import datetime from typing import Any, Dict, List def minimize_dict(maximized: Dict[Any, Any]) -> Dict[Any, Any]: return { key: value for key, value in maximized.items() if value is not None and value != "" } def serialize_datetimes(di...
null
v4
[]
Dict[str, Any]
def v4(self) -> Dict[str, Any]: v5: Dict[str, Any] = dict(self.__dict__) v5['origin_depart'] = self.origin_depart.json() v5['destination_return'] = self.destination_return.json() v5['passengers'] = self.passengers.json() if self.origin_segments: v5['origin_segments'] = [[k.json() for v6 in j...
[ { "name": "v0", "input_types": [ "Dict[Any, Any]" ], "output_type": "Dict[Any, Any]", "code": "def v0(v1: Dict[Any, Any]) -> Dict[Any, Any]:\n return {key: value for (v2, v3) in v1.items() if v3 is not None and v3 != ''}", "dependencies": [] } ]
[]
[]
10
from dataclasses import dataclass from datetime import datetime from typing import Any, Dict, List def minimize_dict(maximized: Dict[Any, Any]) -> Dict[Any, Any]: return { key: value for key, value in maximized.items() if value is not None and value != "" } def serialize_datetimes(di...
null
v0
[]
None
def v0(self) -> None: v1 = self.example_user('hamlet') self.login_user(v1) v2 = self.client_post('/json/users/me/presence', {'status': 'foo'}) self.assert_json_error(v2, 'Invalid status: foo')
[]
[]
[]
5
import datetime from datetime import timedelta from typing import Any, Dict from unittest import mock from django.utils.timezone import now as timezone_now from zerver.lib.actions import do_deactivate_user from zerver.lib.presence import get_status_dict_by_realm from zerver.lib.statistics import seconds_usage_between...
null
v0
[]
None
def v0(self) -> None: v1 = self.example_user('hamlet') v2 = self.example_user('othello') self.login_user(v1) v3 = 'website' v4 = dict(status='idle') v5 = self.client_post('/json/users/me/presence', v4) self.assert_json_success(v5) self.assertEqual(v5.json()['presences'][v1.email][v3]['st...
[]
[]
[]
34
import datetime from datetime import timedelta from typing import Any, Dict from unittest import mock from django.utils.timezone import now as timezone_now from zerver.lib.actions import do_deactivate_user from zerver.lib.presence import get_status_dict_by_realm from zerver.lib.statistics import seconds_usage_between...
null
v0
[]
None
def v0(self) -> None: v1 = self.mit_user('espuser') self.login_user(v1) v2 = self.client_post('/json/users/me/presence', {'status': 'idle'}, subdomain='zephyr') self.assert_json_success(v2) self.assertEqual(v2.json()['presences'], {})
[]
[]
[]
6
import datetime from datetime import timedelta from typing import Any, Dict from unittest import mock from django.utils.timezone import now as timezone_now from zerver.lib.actions import do_deactivate_user from zerver.lib.presence import get_status_dict_by_realm from zerver.lib.statistics import seconds_usage_between...
null
v3
[]
None
def v3(self) -> None: v4 = self.mit_user('espuser') self.login_user(v4) def v5() -> Dict[str, Any]: v6 = self.client_post('/json/users/me/presence', {'status': 'idle'}, subdomain='zephyr') self.assert_json_success(v6) v7 = v6.json() return v7 v8 = v5() self.assertEqu...
[ { "name": "v0", "input_types": [], "output_type": "Dict[str, Any]", "code": "def v0() -> Dict[str, Any]:\n v1 = self.client_post('/json/users/me/presence', {'status': 'idle'}, subdomain='zephyr')\n self.assert_json_success(v1)\n v2 = v1.json()\n return v2", "dependencies": [] } ]
[]
[]
14
import datetime from datetime import timedelta from typing import Any, Dict from unittest import mock from django.utils.timezone import now as timezone_now from zerver.lib.actions import do_deactivate_user from zerver.lib.presence import get_status_dict_by_realm from zerver.lib.statistics import seconds_usage_between...
null
v0
[]
None
def v0(self) -> None: v1 = self.mit_user('espuser') self.login_user(v1) self.client_post('/json/users/me/presence', {'status': 'idle'}, subdomain='zephyr') self.logout() v2 = self.example_user('hamlet') self.login_user(v2) v3 = self.client_post('/json/users/me/presence', {'status': 'idle'}) ...
[]
[]
[]
12
import datetime from datetime import timedelta from typing import Any, Dict from unittest import mock from django.utils.timezone import now as timezone_now from zerver.lib.actions import do_deactivate_user from zerver.lib.presence import get_status_dict_by_realm from zerver.lib.statistics import seconds_usage_between...
null
v0
[]
None
def v0(self) -> None: v1 = self.example_user('hamlet') self.login_user(v1) v2 = self.example_user('othello') v2.email = 'email@zulip.com' v2.delivery_email = 'delivery_email@zulip.com' v2.save() v3 = self.client_get('/json/users/delivery_email@zulip.com/presence') self.assert_json_error(...
[]
[]
[]
13
import datetime from datetime import timedelta from typing import Any, Dict from unittest import mock from django.utils.timezone import now as timezone_now from zerver.lib.actions import do_deactivate_user from zerver.lib.presence import get_status_dict_by_realm from zerver.lib.statistics import seconds_usage_between...
null
v0
[]
None
def v0(self) -> None: self.login(self.example_email('othello')) v1 = dict(status='active', ping_only='true') v2 = self.client_post('/json/users/me/presence', v1) self.assertEqual(v2.json()['msg'], '')
[]
[]
[]
5
# -*- coding: utf-8 -*- from django.http import HttpResponse from django.test import override_settings from django.utils.timezone import now as timezone_now from mock import mock from typing import Any, Dict from zerver.lib.actions import do_deactivate_user from zerver.lib.test_helpers import ( make_client, q...
null
v0
[]
None
def v0(self) -> None: v1 = self.example_user('othello') v2 = self.example_user('hamlet') v3 = self.api_post(v1, '/api/v1/users/me/presence', dict(status='active'), HTTP_USER_AGENT='ZulipAndroid/1.0') v3 = self.api_post(v2, '/api/v1/users/me/presence', dict(status='idle'), HTTP_USER_AGENT='ZulipDesktop/1...
[]
[]
[]
16
import datetime from datetime import timedelta from typing import Any, Dict from unittest import mock from django.utils.timezone import now as timezone_now from zerver.lib.actions import do_deactivate_user from zerver.lib.presence import get_status_dict_by_realm from zerver.lib.statistics import seconds_usage_between...
null
v0
[]
Dict[str, Any]
def v0() -> Dict[str, Any]: v1 = self.client_post('/json/users/me/presence', {'status': 'idle'}, subdomain='zephyr') self.assert_json_success(v1) v2 = v1.json() return v2
[]
[]
[]
5
import datetime from datetime import timedelta from typing import Any, Dict from unittest import mock from django.utils.timezone import now as timezone_now from zerver.lib.actions import do_deactivate_user from zerver.lib.presence import get_status_dict_by_realm from zerver.lib.statistics import seconds_usage_between...
null
v0
[]
None
def v0(self) -> None: v1 = self._proxied_transaction assert v1 is not None v1.rollback() self.migration_context._transaction = None
[]
[]
[]
5
from contextlib import contextmanager import logging import sys from typing import Any from typing import cast from typing import Collection from typing import ContextManager from typing import Dict from typing import Iterator from typing import List from typing import Optional from typing import Set from typing import...
null
v0
[]
bool
def v0(self) -> bool: try: v1 = self.connection.in_transaction except AttributeError: return False else: return v1()
[]
[]
[]
7
from contextlib import contextmanager import logging import sys from typing import Any from typing import cast from typing import Collection from typing import ContextManager from typing import Dict from typing import Iterator from typing import List from typing import Optional from typing import Set from typing import...
null
v0
[ "'Column'", "'Column'" ]
bool
def v0(self, v1: 'Column', v2: 'Column') -> bool: if self._user_compare_type is False: return False if callable(self._user_compare_type): v3 = self._user_compare_type(self, v1, v2, v1.type, v2.type) if v3 is not None: return v3 return self.impl.compare_type(v1, v2)
[]
[]
[]
8
from contextlib import contextmanager import logging import sys from typing import Any from typing import cast from typing import Collection from typing import ContextManager from typing import Dict from typing import Iterator from typing import List from typing import Optional from typing import Set from typing import...
null
v0
[ "'Column'", "'Column'", "Optional[str]", "Optional[str]" ]
bool
def v0(self, v1: 'Column', v2: 'Column', v3: Optional[str], v4: Optional[str]) -> bool: if self._user_compare_server_default is False: return False if callable(self._user_compare_server_default): v5 = self._user_compare_server_default(self, v1, v2, v4, v2.server_default, v3) if v5 is not...
[]
[]
[]
8
from contextlib import contextmanager import logging import sys from typing import Any from typing import cast from typing import Collection from typing import ContextManager from typing import Dict from typing import Iterator from typing import List from typing import Optional from typing import Set from typing import...
null
v0
[ "Collection[str]" ]
Tuple[str, ...]
def v0(self, v1: Collection[str]) -> Tuple[str, ...]: v2 = set(v1).difference([self.revision.revision]) if v2: v3 = set((r.revision for v4 in self.revision_map._get_ancestor_nodes(self.revision_map.get_revisions(v2), check=False))) return tuple(set(self.to_revisions).difference(v3)) else: ...
[]
[]
[]
7
from contextlib import contextmanager import logging import sys from typing import Any from typing import cast from typing import Collection from typing import ContextManager from typing import Dict from typing import Iterator from typing import List from typing import Optional from typing import Set from typing import...
null
v0
[ "Set[str]" ]
Tuple[str, str]
def v0(self, v1: Set[str]) -> Tuple[str, str]: assert len(self.from_) == 1 assert len(self.to_) == 1 return (self.from_[0], self.to_[0])
[]
[]
[]
4
from contextlib import contextmanager import logging import sys from typing import Any from typing import cast from typing import Collection from typing import ContextManager from typing import Dict from typing import Iterator from typing import List from typing import Optional from typing import Set from typing import...
null
v0
[ "List[int]" ]
int
def v0(self, v1: List[int]) -> int: v2 = 0 v3 = len(v1) - 1 v4 = 0 while v2 < v3: v5 = min(v1[v2], v1[v3]) v4 = max(v4, v5 * (v3 - v2)) while v1[v2] <= v5 and v2 < v3: v2 += 1 while v1[v3] <= v5 and v2 < v3: v3 -= 1 return v4
[]
[]
[]
12
from typing import List class Solution: def maxArea(self, height: List[int]) -> int: i = 0 j = len(height) - 1 max_value = 0 while i < j: base = min(height[i], height[j]) max_value = max(max_value, base * (j - i)) while height[i] <= base and i < ...
null
v0
[ "uavcan.node.Version_1_0", "int", "Optional[int]" ]
str
def v0(v1: uavcan.node.Version_1_0, v2: int, v3: Optional[int]) -> str: v4 = f'{v1.major:3d}.{v1.minor}' if v2 != 0 or v3 is not None: v4 += f'.{v2:016x}' if v3 is not None: v4 += f'.{v3:016x}' return v4.ljust(41)
[]
[]
[]
7
# Copyright (c) 2021 UAVCAN Consortium # This software is distributed under the terms of the MIT License. # Author: Pavel Kirienko <pavel@uavcan.org> # pylint: disable=too-many-locals from __future__ import annotations import sys import functools from typing import TYPE_CHECKING, Optional, Dict, Callable, List, Any, ...
null
v0
[ "float" ]
str
def v0(v1: float) -> str: v1 = max(v1, 0.0) if v1 < 1000.0: return f'{v1:4.0f} ' if v1 < 1000000.0: return f'{v1 / 1000.0:4.0f}k' return f'{v1 / 1000000.0:4.0f}M'
[]
[]
[]
7
# Copyright (c) 2021 UAVCAN Consortium # This software is distributed under the terms of the MIT License. # Author: Pavel Kirienko <pavel@uavcan.org> # pylint: disable=too-many-locals from __future__ import annotations import sys import functools from typing import TYPE_CHECKING, Optional, Dict, Callable, List, Any, ...
null
v0
[ "float" ]
str
def v0(v1: float) -> str: v1 = max(v1, 0.0) if v1 < 1024: return f'{v1:4.0f} ' if v1 < 1024 * 1024: return f'{v1 / 1024:4.0f}K' return f'{v1 / (1024 * 1024):4.0f}M'
[]
[]
[]
7
# Copyright (c) 2021 UAVCAN Consortium # This software is distributed under the terms of the MIT License. # Author: Pavel Kirienko <pavel@uavcan.org> # pylint: disable=too-many-locals from __future__ import annotations import sys import functools from typing import TYPE_CHECKING, Optional, Dict, Callable, List, Any, ...
null
v0
[]
str
def v0(self) -> str: v1 = [] for v2 in self.diffs: v1.append('') v1.append(str(v2)) return '\n'.join(v1)
[]
[]
[]
6
from typing import List, Union from paukenator.nlp import Text, Line from .common import CmpBase class CmpLines(CmpBase): def __call__(self, expected: List[str], observed: Text): assert isinstance(expected, list), \ "Expecting list but got {}".format(type(expected)) assert isinstance...
null
v0
[ "Optional[Any]", "str" ]
str
def v0(self, v1: Optional[Any], v2: str='en') -> str: try: if v1 is not None: v3 = v1.xpath('./xs:annotation/xs:documentation[@xml:lang=$lang]/text()', namespaces=v1.nsmap, lang=v2) return cast(List[str], v3)[0].strip() except BaseException: pass return ''
[]
[ "typing" ]
[ "from typing import Any, Dict, List, Optional, cast" ]
8
""" Type definitions for XSD processing. """ from typing import Any, Dict, List, Optional, cast from anytree import NodeMixin, RenderTree, Resolver, ResolverError, findall from lxml import etree from pygls.lsp.types import MarkupContent, MarkupKind from .constants import MSG_NO_DOCUMENTATION_AVAILABLE class XsdBas...
null
v0
[ "List[str]" ]
str
def v0(self, v1: List[str]) -> str: if v1[0] == self.root.name: v1[0] = '.' return '/'.join(v1)
[]
[]
[]
4
""" Type definitions for XSD processing. """ from lxml import etree from anytree import NodeMixin, RenderTree, Resolver, ResolverError from typing import List, Dict, Optional, cast from pygls.types import MarkupContent, MarkupKind from .constants import MSG_NO_DOCUMENTATION_AVAILABLE class XsdBase: """Base class...
null
v0
[ "Iterable[float]" ]
Iterator[Tuple[float, float, float]]
def v0(v1: Iterable[float]) -> Iterator[Tuple[float, float, float]]: for v2 in v1: for v3 in v1: for v4 in v1: yield (v2, v3, v4)
[]
[]
[]
5
"""Helpers for performing tests.""" import itertools from typing import Type, Tuple, Callable, Iterable, Iterator from srctools.math import ( Py_Vec, Cy_Vec, Py_Angle, Cy_Angle, Py_Matrix, Cy_Matrix, Py_parse_vec_str, Cy_parse_vec_str, ) from srctools import math as vec_mod import pytest import math im...
null
v7
[ "Sequence[str]" ]
str
def v7(v8: Sequence[str]) -> str: (v9, v10) = v8 v9 = v9.split() v10 = int(v10) if v10 <= 0: raise ValueError('N must be a positive integer') v11 = v0(v9, v10) return '\n'.join(v11)
[ { "name": "v0", "input_types": [ "Iterable[str]", "int" ], "output_type": "List[str]", "code": "def v0(v1: Iterable[str], v2: int) -> List[str]:\n v3 = product(v1, repeat=v2)\n v4 = [''.join(letters) for v5 in v3]\n v6 = sorted(v4)\n return v6", "dependencies": [] }...
[ "itertools" ]
[ "from itertools import product" ]
8
""" Assume that an alphabet A has a predetermined order; that is, we write the alphabet as a permutation A=(a1,a2,…, ak), where a1<a2<⋯<ak. For instance, the English alphabet is organized as (A,B,…,Z). Given two strings s and t having the same length n, we say that s precedes t in the lexicographic order (and write s<...
null
v0
[ "Iterable[str]", "int" ]
List[str]
def v0(v1: Iterable[str], v2: int) -> List[str]: v3 = product(v1, repeat=v2) v4 = [''.join(letters) for v5 in v3] v6 = sorted(v4) return v6
[]
[ "itertools" ]
[ "from itertools import product" ]
5
""" Assume that an alphabet A has a predetermined order; that is, we write the alphabet as a permutation A=(a1,a2,…, ak), where a1<a2<⋯<ak. For instance, the English alphabet is organized as (A,B,…,Z). Given two strings s and t having the same length n, we say that s precedes t in the lexicographic order (and write s<...
null
v0
[ "int", "bool" ]
Any
def v0(self, v1: int, v2: bool): if self.constraints.is_initiator != v2: raise Exception(f'Cannot update_fee: wrong initiator. us: {v2}') with self.db_lock: if v2: self.hm.send_update_fee(v1) else: self.hm.recv_update_fee(v1)
[]
[]
[]
8
# Copyright (C) 2018 The Electrum developers # Copyright (C) 2015-2018 The Lightning Network Developers # # 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 withou...
null
v0
[ "cirq.CircuitDiagramInfoArgs" ]
Tuple[str, ...]
def v0(self, v1: cirq.CircuitDiagramInfoArgs) -> Tuple[str, ...]: assert v1.known_qubit_count is not None return ('@',) + ('Z',) * (v1.known_qubit_count - 1)
[]
[]
[]
3
# Copyright 2018 The Cirq Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
null
v0
[ "int" ]
int
def v0(self, v1: int) -> int: if v1 <= 1: return 0 v2 = [True] * v1 v2[0] = False v2[1] = False v3 = 2 while v3 * v3 < v1: if not v2: continue v4 = v3 * v3 while v4 < v1: v2[v4] = False v4 += v3 v3 += 1 v5 = 0 fo...
[]
[]
[]
20
# Space : O(n) # Time : O(n log n) class Solution: def countPrimes(self, n: int) -> int: if n <= 1: return 0 isPrime = [True] * n isPrime[0] = False isPrime[1] = False i = 2 while i*i < n: if not isPrime: contin...
null
v0
[ "List[int]", "int", "int", "int" ]
Tuple[int]
def v0(self, v1: List[int], v2: int, v3: int, v4: int) -> Tuple[int]: v5 = tuple(v1) for v6 in range(v2): v5 = (v5[0], -1 * v5[2], v5[1]) for v6 in range(v3): v5 = (v5[2], v5[1], v5[0] * -1) for v6 in range(v4): v5 = (v5[1] * -1, v5[0], v5[2]) return v5
[]
[]
[]
9
from typing import List, Tuple f = open("nineteen.txt", "r") lines = [x.strip() for x in f.readlines()] class Scanner: def __init__(self, id = int): self.raw_beacons = [] self.beacons = set() self.id = id self.all = [] self.offset = None def _rotate_coordinate(...
null
v0
[]
List[List[Tuple[int]]]
def v0(self) -> List[List[Tuple[int]]]: if len(self.all) != 0: return self.all for v1 in range(4): for v2 in range(4): for v3 in range(4): self.all.append([self._rotate_coordinate(coord, v1, v2, v3) for v4 in self.raw_beacons]) self.all = [list(x) for v5 in set((t...
[]
[]
[]
9
from typing import List, Tuple f = open("nineteen.txt", "r") lines = [x.strip() for x in f.readlines()] class Scanner: def __init__(self, id = int): self.raw_beacons = [] self.beacons = set() self.id = id self.all = [] self.offset = None def _rotate_coordinate(...
null
v4
[ "v0" ]
Any
def v4(self, v5: v0): self.variant_intervals = list(self._filter_range(v5)) return self
[]
[]
[]
3
import abc from typing import Tuple, Iterable, List from tqdm import tqdm from kipoiseq.dataclasses import Variant, Interval class BaseVariantQuery: __metaclass__ = abc.ABCMeta @abc.abstractmethod def __call__(self, variant: Variant): raise NotImplementedError def __or__(self, other): ...
[ "class v0(BaseVariantIntervalQuery):\n\n def __init__(self, v1):\n self.func = v1\n\n def __call__(self, v2: List[Variant], v3: Interval):\n return self.func(v2, v3)" ]
v4
[ "v0" ]
Any
def v4(self, v5: v0): for (v6, v7) in self.variant_intervals: v6 = list(v6) yield ((v for (v8, v9) in zip(v6, v5(v6, v7)) if v9), v7)
[]
[]
[]
4
import abc from typing import Tuple, Iterable, List from tqdm import tqdm from kipoiseq.dataclasses import Variant, Interval class BaseVariantQuery: __metaclass__ = abc.ABCMeta @abc.abstractmethod def __call__(self, variant: Variant): raise NotImplementedError def __or__(self, other): ...
[ "class v0(BaseVariantIntervalQuery):\n\n def __init__(self, v1):\n self.func = v1\n\n def __call__(self, v2: List[Variant], v3: Interval):\n return self.func(v2, v3)" ]
v0
[ "str" ]
str
def v0(self, v1: str) -> str: v2 = self.method_permission_name.get(v1) if v2: return v2 else: return getattr(getattr(self, v1), '_permission_name')
[]
[]
[]
6
from datetime import date, datetime from inspect import isclass import json import logging import re from flask import ( abort, Blueprint, current_app, flash, render_template, request, session, url_for, ) from ._compat import as_unicode from .actions import ActionItem from .const impor...
null
v0
[ "xr.Dataset" ]
Tuple[xr.Dataset, Dict[str, Dict[str, Any]]]
def v0(self, v1: xr.Dataset) -> Tuple[xr.Dataset, Dict[str, Dict[str, Any]]]: if self._process_rename: v1 = v1.rename(self._process_rename) if self._process_rechunk: v2 = self._get_chunk_encodings(v1, self._process_rechunk) else: v2 = dict() return (v1, self._merge_encodings(v1, ...
[]
[]
[]
8
# The MIT License (MIT) # Copyright (c) 2020 by Brockmann Consult GmbH and contributors # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the...
null
v0
[ "sp.Symbol", "Mapping", "Optional[Mapping]" ]
Any
def v0(v1: sp.Symbol, v2: Mapping, v3: Optional[Mapping]=None) -> Any: try: assert v3 is not None return v3[v1.name] except Exception: return v2[v1.name]
[]
[]
[]
6
"""Formulation of data matrices and absorption of fixed effects.""" import functools import numbers import token from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Union import numpy as np import patsy import patsy.builtins import patsy.contrasts import patsy.desc import patsy.desi...
null
v0
[ "str" ]
sp.Expr
def v0(self, v1: str) -> sp.Expr: v2 = self.derivatives.get(v1) if v2 is None: v2 = self.expression.diff(sp.Symbol(v1)) self.derivatives[v1] = v2 return v2
[]
[ "sympy" ]
[ "import sympy as sp", "import sympy.parsing.sympy_parser" ]
6
"""Formulation of data matrices and absorption of fixed effects.""" import functools import numbers import token from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Union import numpy as np import patsy import patsy.builtins import patsy.contrasts import patsy.desc import patsy.desi...
null
v0
[ "Optional[str]" ]
Any
def v0(v1: Optional[str]): if v1: sys.stderr.write(str(v1) + '\n') sys.exit(1) else: sys.exit(0)
[]
[ "sys" ]
[ "import sys" ]
6
#!/usr/bin/env python3 import copy import logging import optparse import os import random import string import sys import threading from typing import Optional import pump import pump_bfd import pump_csv import pump_cb import pump_gen import pump_mc import pump_dcp from pump import PumpingStation def exit_handler...
null
v0
[ "str" ]
Any
def v0(self, v1: str): if v1 not in self.uuid_cache.inv: try: v2 = self.req_future_session.get('https://api.mojang.com/users/profiles/minecraft/{}'.format(v1)).result().json()['id'] v3 = uuid.UUID(v2) self.uuid_cache.inv[v1] = str(v3) return v2 except ...
[]
[ "requests", "uuid" ]
[ "import uuid", "from requests import RequestException" ]
11
#!/usr/bin/env python # # Copyright (c) 2018 Tristan Gosselin-Hane. # # This file is part of minecraft-discord-bridge # (see https://github.com/starcraft66/minecraft-discord-bridge). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # ...
null
v0
[]
None
def v0(self) -> None: super().setUp() self.test_models = {'meeting/1': {'name': 'bla'}, 'projector/23': {'meeting_id': 1, 'current_projection_ids': [33]}, 'projection/33': {'meeting_id': 1, 'current_projector_id': 23}}
[]
[]
[]
3
from openslides_backend.permissions.permissions import Permissions from tests.system.action.base import BaseActionTestCase class ProjectionUpdateOptions(BaseActionTestCase): def setUp(self) -> None: super().setUp() self.test_models = { "meeting/1": {"name": "bla"}, "project...
null
v0
[]
None
def v0(self) -> None: self.set_models(self.test_models) v1 = self.request('projection.update_options', {'id': 33, 'options': {'bla': []}}) self.assert_status_code(v1, 200) self.assert_model_exists('projection/33', {'options': {'bla': []}})
[]
[]
[]
5
from openslides_backend.permissions.permissions import Permissions from tests.system.action.base import BaseActionTestCase class ProjectionUpdateOptions(BaseActionTestCase): def setUp(self) -> None: super().setUp() self.test_models = { "meeting/1": {"name": "bla"}, "project...
null
v0
[ "bool" ]
onp.ndarray
def v0(self, v1: bool=True) -> onp.ndarray: if v1: v2 = onp.linalg.inv(self.L.todense()) return v2.T @ v2 else: return self._compute_marginal(range(self.local_storage_metadata.dim))
[]
[ "numpy" ]
[ "import numpy as onp" ]
6
import dataclasses from typing import Dict, List, Sequence, Tuple import numpy as onp import scipy import sksparse from .. import core @dataclasses.dataclass class SparseCovariance: """Helper class for recovering marginal covariances. Implements the algorithm described in [1]. [1] Covariance Recovery f...
null
v0
[]
onp.ndarray
def v0(self, *v1: core.VariableBase) -> onp.ndarray: v2: List[int] = [] for v3 in v1: v4 = self.local_storage_metadata.index_from_variable[v3] v2.extend(range(v4, v4 + v3.get_local_parameter_dim())) return self._compute_marginal(v2)
[]
[]
[]
6
import dataclasses from typing import Dict, List, Sequence, Tuple import numpy as onp import scipy import sksparse from .. import core @dataclasses.dataclass class SparseCovariance: """Helper class for recovering marginal covariances. Implements the algorithm described in [1]. [1] Covariance Recovery f...
null
v0
[ "Sequence[int]" ]
onp.ndarray
def v0(self, v1: Sequence[int]) -> onp.ndarray: v2 = len(v1) v3 = onp.zeros((v2, v2)) for v4 in range(v2): for v5 in range(v2): v3[v4, v5] = self[v1[v4], v1[v5]] return v3
[]
[ "numpy" ]
[ "import numpy as onp" ]
7
import dataclasses from typing import Dict, List, Sequence, Tuple import numpy as onp import scipy import sksparse from .. import core @dataclasses.dataclass class SparseCovariance: """Helper class for recovering marginal covariances. Implements the algorithm described in [1]. [1] Covariance Recovery f...
null
v0
[ "int", "int" ]
float
def v0(self, v1: int, v2: int) -> float: v3: scipy.sparse.csc_matrix = self.L.getcol(v1) v4: float = 0.0 v5: int v6: float for (v5, v6) in zip(v3.indices, v3.data): if v1 != v5: v4 += v6 * self[v5, v2] return v4
[]
[]
[]
9
import dataclasses from typing import Dict, List, Sequence, Tuple import numpy as onp import scipy import sksparse from .. import core @dataclasses.dataclass class SparseCovariance: """Helper class for recovering marginal covariances. Implements the algorithm described in [1]. [1] Covariance Recovery f...
null
v0
[ "Any", "dict", "list", "dict", "float", "float" ]
Any
def v0(v1, v2: dict, v3: list, v4: dict, v5: float, v6: float): for v7 in v1: v8 = v7.text.replace('\n', ' ').split(' ') v9 = round(float(v8[1]), 3) if (v6 is None or v9 >= v6) and (v5 is None or v9 <= v5): v3.append(v9) for v10 in v2: for v11 in v2[v1...
[]
[]
[]
12
import os import xml.etree.ElementTree as et import pickle SHRUNK_RES_SUFFIX = '_shrunk' XML_REF = 'http://www.mscsoftware.com/:xrf10' STEPMAP_TAG = 'StepMap' ENTITY_TAG = 'Entity' COMPONENT_TAG = 'Component' STEP_TAG = '{' + XML_REF + '}' + 'Step' def get_results(result_file, reqs_to_get=None, t_min=None, t_max=None,...
null
v0
[]
int or None
def v0() -> int or None: v1 = int(input('Введи целое число от 1 до 1000 ')) return v1
[]
[]
[]
3
__author__ = 'Шелест Леонид Викторович' """ Найти сумму n элементов следующего ряда чисел: 1 -0.5 0.25 -0.125 ... Количество элементов (n) вводится с клавиатуры. """ def get_data() -> int or None: n = int(input('Введи целое число от 1 до 1000 ')) return n def f_n(n: int): if n == 1: return 1 ...
null
v0
[ "Any" ]
List[torch.tensor]
def v0(self, v1) -> List[torch.tensor]: v2 = [] v1 = self.conv1(v1) v1 = self.bn1(v1) v1 = self.act1(v1) if 0 in self._out_idx: v2.append(v1) v1 = self.conv2(v1) v1 = self.bn2(v1) v1 = self.act2(v1) v1 = self.stages(v1) if self.incre_modules is not None: v1 = [inc...
[]
[]
[]
17
# Copyright [yyyy] [name of copyright owner] # Copyright 2021 Huawei Technologies Co., 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.or...
null
v0
[ "Any" ]
List[torch.Tensor]
def v0(self, v1) -> List[torch.Tensor]: v1 = self.layer1(v1) v2 = [t(v1) for (v3, v4) in enumerate(self.transition1)] v5 = self.stage2(v2) v2 = [v4(v5[-1]) if not isinstance(v4, nn.Identity) else v5[v3] for (v3, v4) in enumerate(self.transition2)] v5 = self.stage3(v2) v2 = [v4(v5[-1]) if not isi...
[]
[ "torch" ]
[ "import torch", "import torch.nn as nn", "import torch.nn.functional as F" ]
9
# Copyright [yyyy] [name of copyright owner] # Copyright 2021 Huawei Technologies Co., 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.or...
null
v3
[ "obspy.Trace", "config.Duration" ]
Tuple[np.ndarray, np.ndarray]
def v3(v4: obspy.Trace, v5: config.Duration=config.Duration) -> Tuple[np.ndarray, np.ndarray]: if v5.moving_average_window == 0: v6 = v4.data v7 = v0(v4) else: v8 = v5.moving_average_window * int(v4.stats.sampling_rate) v9 = v0(v4) v10 = pd.Series(v9).rolling(window=v8).m...
[ { "name": "v0", "input_types": [ "obspy.Trace" ], "output_type": "np.ndarray", "code": "def v0(v1: obspy.Trace) -> np.ndarray:\n v2 = v1.stats.o - v1.stats.starttime + v1.stats.p\n return np.arange(0, len(v1.data)) * v1.stats.delta - v2", "dependencies": [] } ]
[ "numpy", "pandas", "scipy" ]
[ "import numpy as np", "import pandas as pd", "from scipy.signal import hilbert", "from scipy.optimize import lsq_linear as lsq" ]
12
""" duration.py measure the duration using the coda envelope """ import obspy import types import warnings import numpy as np import pandas as pd import madpy.noise as n from typing import Tuple import madpy.checks as ch import madpy.config as config import matplotlib.pyplot as plt from scipy.signal import hilbert im...
null
v0
[ "obspy.Trace" ]
np.ndarray
def v0(v1: obspy.Trace) -> np.ndarray: v2 = v1.stats.o - v1.stats.starttime + v1.stats.p return np.arange(0, len(v1.data)) * v1.stats.delta - v2
[]
[ "numpy" ]
[ "import numpy as np" ]
3
""" duration.py measure the duration using the coda envelope """ import obspy import types import warnings import numpy as np import pandas as pd import madpy.noise as n from typing import Tuple import madpy.checks as ch import madpy.config as config import matplotlib.pyplot as plt from scipy.signal import hilbert im...
null
v0
[ "np.ndarray" ]
np.ndarray
def v0(v1: np.ndarray) -> np.ndarray: v2 = np.where(v1 > 0, v1, np.nan) v3 = np.log10(v2) v3[np.isinf(v3)] = np.nan v3[np.isneginf(v3)] = np.nan return v3
[]
[ "numpy" ]
[ "import numpy as np" ]
6
""" duration.py measure the duration using the coda envelope """ import obspy import types import warnings import numpy as np import pandas as pd import madpy.noise as n from typing import Tuple import madpy.checks as ch import madpy.config as config import matplotlib.pyplot as plt from scipy.signal import hilbert im...
null
v30
[ "obspy.Trace", "config.Duration", "np.ndarray", "np.ndarray", "float" ]
Tuple[int, int]
def v30(v31: obspy.Trace, v32: config.Duration, v33: np.ndarray, v34: np.ndarray, v35: float) -> Tuple[int, int]: v36 = v17(v31, v33, v32, 'begin') v37 = v17(v31, v33, v32, 'end') v38 = np.where(v34 == np.nanmax(v34[v36:v37]))[0][0] v39 = v0(v31, v32, v34, v38, v35) v40 = v8(v32, v38, v39) retur...
[ { "name": "v0", "input_types": [ "obspy.Trace", "config.Duration", "np.ndarray", "int", "float" ], "output_type": "int", "code": "def v0(v1: obspy.Trace, v2: config.Duration, v3: np.ndarray, v4: int, v5: float) -> int:\n v6 = v3[v4:] - np.log10(v2.end_fit_noise *...
[ "numpy" ]
[ "import numpy as np" ]
7
""" duration.py measure the duration using the coda envelope """ import obspy import types import warnings import numpy as np import pandas as pd import madpy.noise as n from typing import Tuple import madpy.checks as ch import madpy.config as config import matplotlib.pyplot as plt from scipy.signal import hilbert im...
null
v10
[ "obspy.Trace", "np.ndarray", "config.Duration", "str" ]
int
def v10(v11: obspy.Trace, v12: np.ndarray, v13: config.Duration, v14: str) -> int: v15 = v4(v11, v13, v14) v16 = np.where(np.sign(v12 - v15) == 1)[0][0] return v16
[ { "name": "v0", "input_types": [ "obspy.Trace", "str" ], "output_type": "obspy.UTCDateTime", "code": "def v0(v1: obspy.Trace, v2: str) -> obspy.UTCDateTime:\n if v2 == 'O':\n v3 = -v1.stats.p\n elif v2 == 'P':\n v3 = v1.stats.p - v1.stats.p\n elif v2 == 'S':\n ...
[ "numpy" ]
[ "import numpy as np" ]
4
""" duration.py measure the duration using the coda envelope """ import obspy import types import warnings import numpy as np import pandas as pd import madpy.noise as n from typing import Tuple import madpy.checks as ch import madpy.config as config import matplotlib.pyplot as plt from scipy.signal import hilbert im...
null
v4
[ "obspy.Trace", "config.Duration", "str" ]
float
def v4(v5: obspy.Trace, v6: config.Duration, v7: str) -> float: v8 = v0(v5, v6.signal_phase) assert v7 in ['begin', 'end'], f'(ValueError) Position {v7} unrecognized' if v7 == 'begin': v9 = v8 + v6.signal_window_begin elif v7 == 'end': v9 = v8 + v6.signal_window_end return v9
[ { "name": "v0", "input_types": [ "obspy.Trace", "str" ], "output_type": "obspy.UTCDateTime", "code": "def v0(v1: obspy.Trace, v2: str) -> obspy.UTCDateTime:\n if v2 == 'O':\n v3 = -v1.stats.p\n elif v2 == 'P':\n v3 = v1.stats.p - v1.stats.p\n elif v2 == 'S':\n ...
[]
[]
8
""" duration.py measure the duration using the coda envelope """ import obspy import types import warnings import numpy as np import pandas as pd import madpy.noise as n from typing import Tuple import madpy.checks as ch import madpy.config as config import matplotlib.pyplot as plt from scipy.signal import hilbert im...
null
v0
[ "obspy.Trace", "str" ]
obspy.UTCDateTime
def v0(v1: obspy.Trace, v2: str) -> obspy.UTCDateTime: if v2 == 'O': v3 = -v1.stats.p elif v2 == 'P': v3 = v1.stats.p - v1.stats.p elif v2 == 'S': v3 = v1.stats.s - v1.stats.p return v3
[]
[]
[]
8
""" duration.py measure the duration using the coda envelope """ import obspy import types import warnings import numpy as np import pandas as pd import madpy.noise as n from typing import Tuple import madpy.checks as ch import madpy.config as config import matplotlib.pyplot as plt from scipy.signal import hilbert im...
null
v0
[ "config.Duration", "int", "int" ]
int
def v0(v1: config.Duration, v2: int, v3: int) -> int: if v1.start_fit_max > 1: v4 = (v3 - v2) / v1.start_fit_max + v2 else: v4 = np.copy(v2) return int(v4)
[]
[ "numpy" ]
[ "import numpy as np" ]
6
""" duration.py measure the duration using the coda envelope """ import obspy import types import warnings import numpy as np import pandas as pd import madpy.noise as n from typing import Tuple import madpy.checks as ch import madpy.config as config import matplotlib.pyplot as plt from scipy.signal import hilbert im...
null
v0
[ "float", "float", "float", "float", "float" ]
Tuple[np.ndarray, np.ndarray]
def v0(v1: float, v2: float, v3: float, v4: float, v5: float) -> Tuple[np.ndarray, np.ndarray]: v6 = np.arange(v3, v4, v5) v7 = v1 * v6 + v2 return (v6, v7)
[]
[ "numpy" ]
[ "import numpy as np" ]
4
""" duration.py measure the duration using the coda envelope """ import obspy import types import warnings import numpy as np import pandas as pd import madpy.noise as n from typing import Tuple import madpy.checks as ch import madpy.config as config import matplotlib.pyplot as plt from scipy.signal import hilbert im...
null
v0
[ "config.Duration", "float" ]
float
def v0(v1: config.Duration, v2: float) -> float: if v1.threshold_type == 'absolute': v3 = v1.duration_absolute_threshold elif v1.threshold_type == 'noise': v3 = v1.duration_noise_threshold * np.log10(v2) return v3
[]
[ "numpy" ]
[ "import numpy as np" ]
6
""" duration.py measure the duration using the coda envelope """ import obspy import types import warnings import numpy as np import pandas as pd import madpy.noise as n from typing import Tuple import madpy.checks as ch import madpy.config as config import matplotlib.pyplot as plt from scipy.signal import hilbert im...
null
v12
[ "np.ndarray", "np.ndarray", "np.ndarray", "int", "int", "float" ]
np.ndarray
def v12(v13: np.ndarray, v14: np.ndarray, v15: np.ndarray, v16: int, v17: int, v18: float=0.9) -> np.ndarray: (v19, v20) = v4(v13[1], v13[0], 0, 10000, 0.001) v21 = np.where(np.sign(v19 - v14[v16]) == 1)[0][0] v22 = np.where(np.sign(v14 - v19[v17]) == 1)[0] if len(v22) == 0: v23 = int(np.around(...
[ { "name": "v0", "input_types": [ "np.ndarray", "np.ndarray" ], "output_type": "np.ndarray", "code": "def v0(v1: np.ndarray, v2: np.ndarray) -> np.ndarray:\n v3 = np.corrcoef(v1, v2, rowvar=False)\n ch.check_cc(v3, 0, 3)\n return v3", "dependencies": [] }, { "name...
[ "numpy", "warnings" ]
[ "import warnings", "import numpy as np" ]
19
""" duration.py measure the duration using the coda envelope """ import obspy import types import warnings import numpy as np import pandas as pd import madpy.noise as n from typing import Tuple import madpy.checks as ch import madpy.config as config import matplotlib.pyplot as plt from scipy.signal import hilbert im...
null