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 | [
"dict",
"str"
] | Any | async def v0(self, v1: dict, v2: str):
await self.session.hiveRefreshTokens()
v3 = False
if v1['hiveID'] in self.session.data.products and v1['deviceData']['online']:
await self.session.hiveRefreshTokens()
v4 = self.session.data.products[v1['hiveID']]
v5 = await self.session.api.setS... | [] | [] | [] | 11 | """Hive Heating Module."""
from .helper.const import HIVETOHA
class HiveHeating:
"""Hive Heating Code.
Returns:
object: heating
"""
heatingType = "Heating"
async def getMinTemperature(self, device: dict):
"""Get heating minimum target temperature.
Args:
dev... | null |
v0 | [
"dict"
] | Any | async def v0(self, v1: dict):
v1['deviceData'].update({'online': await self.session.attr.onlineOffline(v1['device_id'])})
v2 = {}
if v1['deviceData']['online']:
self.session.helper.deviceRecovered(v1['device_id'])
v3 = self.session.data.devices[v1['device_id']]
v2 = {'hiveID': v1['hi... | [] | [] | [] | 14 | """Hive Switch Module."""
from .helper.const import HIVETOHA
class HiveSmartPlug:
"""Plug Device.
Returns:
object: Returns Plug object
"""
plugType = "Switch"
async def getState(self, device: dict):
"""Get smart plug state.
Args:
device (dict): Device to ge... | null |
v0 | [
"dict"
] | Any | async def v0(self, v1: dict):
if v1['hiveType'] == 'Heating_Heat_On_Demand':
return await self.session.heating.setHeatOnDemand(v1, 'DISABLED')
else:
return await self.setStatusOff(v1) | [] | [] | [] | 5 | """Hive Switch Module."""
from .helper.const import HIVETOHA
class HiveSmartPlug:
"""Plug Device.
Returns:
object: Returns Plug object
"""
plugType = "Switch"
async def getState(self, device: dict):
"""Get smart plug state.
Args:
device (dict): Device to ge... | null |
v0 | [] | 'ExecutionResult' | def v0(self) -> 'ExecutionResult':
print(f'[{self.code}] {self.message}')
return self | [] | [] | [] | 3 | import argparse
import dataclasses
import typing
@dataclasses.dataclass(frozen=True)
class CliContext:
"""Data structure for CLI execution context."""
#: Parsed arguments for the CLI invocation.
args: argparse.Namespace
@dataclasses.dataclass(frozen=True)
class ExecutionResult:
"""Data structure fo... | null |
v17 | [
"v0",
"int",
"int"
] | int | def v17(v18: v0, v19: int, v20: int) -> int:
v21 = 0
for v22 in range(-1, 2):
for v23 in range(-1, 2):
if not v22 == v23 == 0:
(v24, v25) = v1(v18, x=v19, y=v20, dx=v22, dy=v23)
v21 += v11(v18, v24, v25)
return v21 | [
{
"name": "v1",
"input_types": [
"v0",
"int",
"int",
"int",
"int"
],
"output_type": "tuple[int, int]",
"code": "def v1(v2: v0, v3: int, v4: int, v5: int, v6: int) -> tuple[int, int]:\n (v7, v8) = (len(v2[0]), len(v2))\n (v9, v10) = (v3 + v5, v4 + v6)\n whil... | [] | [] | 8 | from typing import List
from enum import Enum
class Seat(Enum):
Floor = 0
Empty = 1
Occupied = 2
@staticmethod
def from_str(s: str):
if s == '.':
return Seat.Floor
if s == 'L':
return Seat.Empty
if s == '#':
return Seat.Occupied
SeatM... | [
"v0 = List[List[Seat]]"
] |
v36 | [
"v0"
] | int | def v36(v37: v0) -> int:
v38 = 1
while v38:
(v37, v38) = v28(v37)
return v1(v37) | [
{
"name": "v1",
"input_types": [
"v0"
],
"output_type": "int",
"code": "def v1(v2: v0) -> int:\n return sum(map(lambda row: sum(map(lambda seat: seat == Seat.Occupied, row)), v2))",
"dependencies": []
},
{
"name": "v3",
"input_types": [
"v0",
"int",
"in... | [] | [] | 5 | from typing import List
from enum import Enum
class Seat(Enum):
Floor = 0
Empty = 1
Occupied = 2
@staticmethod
def from_str(s: str):
if s == '.':
return Seat.Floor
if s == 'L':
return Seat.Empty
if s == '#':
return Seat.Occupied
SeatM... | [
"v0 = List[List[Seat]]"
] |
v0 | [
"torch.Tensor"
] | torch.Tensor | def v0(v1: torch.Tensor) -> torch.Tensor:
v2 = v1 ** 2 / (torch.sum(v1, 0) + 1e-09)
return (v2.t() / torch.sum(v2, 1)).t() | [] | [
"torch"
] | [
"import torch",
"import torch.nn as nn"
] | 3 | """
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved
Author: Dejiao Zhang (dejiaoz@amazon.com)
Date: 02/26/2021
"""
import torch
import torch.nn as nn
eps = 1e-8
class KLDiv(nn.Module):
def forward(self, predict, target):
assert predict.ndimension()==2,'Input dimension must be 2'
... | null |
v0 | [
"Any",
"Callable"
] | Any | def v0(self, v1, v2: Callable):
self.logger.debug('Handler registered started {0}'.format(v1))
self.handlers.append((v1, v2)) | [] | [] | [] | 3 | import threading
import requests
import traceback
import uuid
import time
import ssl
from typing import Callable
from aiosignalrcore.messages.message_type import MessageType
from aiosignalrcore.messages.stream_invocation_message \
import StreamInvocationMessage
from aiosignalrcore.messages.ping_message import PingM... | null |
v0 | [
"np.ndarray",
"float"
] | Any | def v0(v1: np.ndarray, v2: float=0.1):
if v2 == 0:
return np.array([], dtype=int)
v1 = np.copy(v1)
v3 = np.argmax(v1)
v4 = v1[v3]
v5 = v4 * v2
v6 = v4 - v5
v1[v3] = 0
v7 = np.argmax(v1)
v1[v7] = 0
return np.where(v1 >= v6)[0] | [] | [
"numpy"
] | [
"import numpy as np"
] | 12 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 13 18:23:27 2020
@author: John
"""
import numpy as np
import functools
import votesim
from votesim import votemethods
from votesim import utilities
from votesim.models.vcalcs import distance2rank
from votesim.metrics.metrics import regret_tally
from votesim.ballot import... | null |
v0 | [
"object"
] | Any | def v0(self, v1: object) -> Any:
if isinstance(v1, Decimal):
return float(v1)
if isinstance(v1, (datetime.datetime, datetime.date)):
return v1.isoformat()
if hasattr(v1, 'to_dict'):
return v1.to_dict()
return super().default(v1) | [] | [
"datetime",
"decimal"
] | [
"import datetime",
"from decimal import Decimal"
] | 8 | """Utilities."""
from __future__ import annotations
import datetime
import json
from decimal import Decimal
from typing import Any
class JsonEncoder(json.JSONEncoder):
"""Encode Python objects to JSON data.
This class can be used with ``json.dumps()`` to handle most data types
that can occur in response... | null |
v0 | [
"torch.Tensor"
] | torch.Tensor | def v0(v1: torch.Tensor) -> torch.Tensor:
assert v1.shape[0] == 2
v2 = (v1.shape[1] + 1) // 2
v3 = (v1.shape[2] + 1) // 2
v4 = v1.dtype
v1 = v1.float()
v5 = torch.nn.Unfold((v2, v3))(v1.unsqueeze(0)).view((2, v2, v3, v2, v3)).permute(3, 4, 1, 2, 0)
v5 = v5.flip(0)
v5 = v5.flip(1)
ret... | [] | [] | [] | 10 | import torch
def extract_patches(indices: torch.Tensor) -> torch.Tensor:
"""Extract patches of relative indices from the full table.
Args:
indices: Tensor of shape (2, 2 * height - 1, 2 * width - 1)
Returns:
Relative indices tensor of shape (height, width, height, width, 2)
"""
a... | null |
v1 | [
"str",
"v0"
] | Sequence[Mapping[str, str]] | def v1(v2: str, v3: v0) -> Sequence[Mapping[str, str]]:
v4 = []
v5 = []
for (v6, v7) in v3.items():
if v6.startswith(v2):
v4.append(v6)
v5.append(v7)
assert all([len(xs) == len(v5[0]) for v8 in v5]), 'mmCIF error: Not all loops are the same length: %s' % v4
return [di... | [] | [] | [] | 9 | # Copyright 2021 AlQuraishi Laboratory
# Copyright 2021 DeepMind Technologies Limited
#
# 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
#
# U... | [
"v0 = Mapping[str, Sequence[str]]"
] |
v9 | [
"str",
"str",
"v0"
] | Mapping[str, Mapping[str, str]] | def v9(v10: str, v11: str, v12: v0) -> Mapping[str, Mapping[str, str]]:
v13 = v1(v10, v12)
return {entry[v11]: entry for v14 in v13} | [
{
"name": "v1",
"input_types": [
"str",
"v0"
],
"output_type": "Sequence[Mapping[str, str]]",
"code": "def v1(v2: str, v3: v0) -> Sequence[Mapping[str, str]]:\n v4 = []\n v5 = []\n for (v6, v7) in v3.items():\n if v6.startswith(v2):\n v4.append(v6)\n ... | [] | [] | 3 | # Copyright 2021 AlQuraishi Laboratory
# Copyright 2021 DeepMind Technologies Limited
#
# 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
#
# U... | [
"v0 = Mapping[str, Sequence[str]]"
] |
v1 | [
"v0"
] | str | def v1(v2: v0) -> str:
v3 = v2['_pdbx_audit_revision_history.revision_date']
return min(v3) | [] | [] | [] | 3 | # Copyright 2021 AlQuraishi Laboratory
# Copyright 2021 DeepMind Technologies Limited
#
# 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
#
# U... | [
"v0 = Mapping[str, Sequence[str]]"
] |
v13 | [
"v0"
] | v1 | def v13(v14: v0) -> v1:
v15 = {}
v16 = v5('_exptl.', v14)
v15['structure_method'] = ','.join([experiment['_exptl.method'].lower() for v17 in v16])
if '_pdbx_audit_revision_history.revision_date' in v14:
v15['release_date'] = v2(v14)
else:
logging.warning('Could not determine release_... | [
{
"name": "v2",
"input_types": [
"v0"
],
"output_type": "str",
"code": "def v2(v3: v0) -> str:\n v4 = v3['_pdbx_audit_revision_history.revision_date']\n return min(v4)",
"dependencies": []
},
{
"name": "v5",
"input_types": [
"str",
"v0"
],
"output_... | [
"logging"
] | [
"import logging"
] | 17 | # Copyright 2021 AlQuraishi Laboratory
# Copyright 2021 DeepMind Technologies Limited
#
# 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
#
# U... | [
"v0 = Mapping[str, Sequence[str]]",
"v1 = Mapping[str, Any]"
] |
v0 | [
"Optional[List[str]]"
] | int | def v0(v1: Optional[List[str]]=None) -> int:
v2 = argparse.ArgumentParser()
v2.add_argument('input', nargs='?', default='input.txt', help='input file to read')
v3 = v2.parse_args()
v4 = []
with open(v3.input) as v5:
v4 = [line.rstrip() for v6 in v5]
v7 = 0
v8 = 0
v9 = 0
while... | [] | [
"argparse"
] | [
"import argparse"
] | 20 | #!/usr/bin/env python3
import argparse
from typing import List
from typing import Optional
def main(argv: Optional[List[str]] = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument(
'input', nargs='?', default='input.txt',
help='input file to read',
)
args = parser.pars... | null |
v29 | [
"str"
] | v0 | def v29(v30: str) -> v0:
with open(v30, 'rb') as v31:
v32 = pickle.load(v31)
return v32 | [] | [
"pickle"
] | [
"import pickle"
] | 4 | from datetime import date
import numpy as np
import pandas as pd
import pickle
import pandas_datareader.yahoo.daily as pdr
import yahooquery as yq
#
class Portfolio:
"""Bundle of assets with different weights"""
def __init__(self, tickers: list = None, period: int = 10, weights: list = None,
... | [
"class v0:\n\n def __init__(self, v1: list=None, v2: int=10, v3: list=None, v4: pd.DataFrame=None, v5: pd.DataFrame=None):\n self.period = v2\n if v4 is not None:\n self.finance = v4\n self.summary = v5\n elif v1 is not None:\n self.finance = get_all_ticker_c... |
v0 | [
"pd.DataFrame",
"str"
] | pd.DataFrame | def v0(v1: pd.DataFrame, v2: str) -> pd.DataFrame:
v3 = dict()
for v4 in v1[v2].unique():
v3[v4] = ((v1[v2] == v4) * v1['weight']).sum()
return pd.DataFrame.from_dict(v3, orient='index', columns=['weight']) | [] | [
"pandas"
] | [
"import pandas as pd"
] | 5 | from datetime import date
import numpy as np
import pandas as pd
import pickle
import pandas_datareader.yahoo.daily as pdr
import yahooquery as yq
#
class Portfolio:
"""Bundle of assets with different weights"""
def __init__(self, tickers: list = None, period: int = 10, weights: list = None,
... | null |
v0 | [
"str"
] | Any | def v0(self, v1: str):
with open(os.path.join(v1, 'indices.pkl'), 'wb') as v2:
pickle.dump(self.indices, v2) | [] | [
"os",
"pickle"
] | [
"import os",
"import pickle"
] | 3 | import argparse
import os
import pickle
from glob import glob
from pprint import pprint
import numpy as np
import torch
import torchvision.transforms as T
from numpy.lib.format import open_memmap
from PIL import Image
from torch.utils.data import DataLoader, Dataset
from torchvision.datasets import ImageFolder
from to... | null |
v12 | [
"list",
"int",
"list"
] | Any | def v12(self, v13: list=None, v14: int=None, v15: list=None):
if v13:
self.finance = v0(v13, v14 or self.period)
self.summary = v7(v13)
elif v14:
v13 = self.finance.columns
self.finance = v0(v13, v14)
if v15 and len(v15) == self.summary.shape[0]:
self.summary['weight'... | [
{
"name": "v0",
"input_types": [
"str or list",
"int"
],
"output_type": "pd.DataFrame",
"code": "def v0(v1: str or list, v2: int) -> pd.DataFrame:\n v3 = date.today().replace(year=date.today().year - v2)\n v4 = date.today()\n v5 = pdr.YahooDailyReader(v1, start=v3, end=v4, i... | [
"datetime",
"numpy",
"pandas"
] | [
"from datetime import date",
"import numpy as np",
"import pandas as pd"
] | 12 | from datetime import date
import numpy as np
import pandas as pd
import pickle
import pandas_datareader.yahoo.daily as pdr
import yahooquery as yq
#
class Portfolio:
"""Bundle of assets with different weights"""
def __init__(self, tickers: list = None, period: int = 10, weights: list = None,
... | null |
v0 | [
"str"
] | Any | def v0(self, v1: str):
if v1 in self.finance.columns:
self.summary.drop(v1, axis=0, inplace=True)
self.finance.drop(v1, axis=1, inplace=True)
return self.update() | [] | [] | [] | 5 | from datetime import date
import numpy as np
import pandas as pd
import pickle
import pandas_datareader.yahoo.daily as pdr
import yahooquery as yq
#
class Portfolio:
"""Bundle of assets with different weights"""
def __init__(self, tickers: list = None, period: int = 10, weights: list = None,
... | null |
v12 | [
"str"
] | Any | def v12(self, v13: str):
v14 = v0(v13, self.period).to_frame().rename(columns={'Adj Close': v13})
self.finance = self.finance.join(v14)
v15 = v7(v13)
self.summary.drop('weight', axis=1, inplace=True)
self.summary = self.summary.append(v15)
return self.update() | [
{
"name": "v0",
"input_types": [
"str or list",
"int"
],
"output_type": "pd.DataFrame",
"code": "def v0(v1: str or list, v2: int) -> pd.DataFrame:\n v3 = date.today().replace(year=date.today().year - v2)\n v4 = date.today()\n v5 = pdr.YahooDailyReader(v1, start=v3, end=v4, i... | [
"datetime",
"pandas"
] | [
"from datetime import date",
"import pandas as pd"
] | 7 | from datetime import date
import numpy as np
import pandas as pd
import pickle
import pandas_datareader.yahoo.daily as pdr
import yahooquery as yq
#
class Portfolio:
"""Bundle of assets with different weights"""
def __init__(self, tickers: list = None, period: int = 10, weights: list = None,
... | null |
v3 | [
"s_pointers.PointerLike",
"context.ContextLevel"
] | bool | def v3(v4: s_pointers.PointerLike, *, v5: context.ContextLevel) -> bool:
try:
v6 = v5.source_map[v4].qlexpr
except KeyError:
pass
else:
return v6 is not None
return v4.is_pure_computable(v5.env.schema) or v0(v4, ctx=v5) | [
{
"name": "v0",
"input_types": [
"s_pointers.PointerLike",
"context.ContextLevel"
],
"output_type": "bool",
"code": "def v0(v1: s_pointers.PointerLike, *, v2: context.ContextLevel) -> bool:\n return v2.env.options.apply_query_rewrites and v1 not in v2.disable_shadowing and bool(v1... | [] | [] | 8 | #
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB authors.
#
# 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... | null |
v0 | [
"irast.PathId",
"irast.Set",
"context.ContextLevel"
] | None | def v0(v1: irast.PathId, v2: irast.Set, *, v3: context.ContextLevel) -> None:
v3.view_map = v3.view_map.new_child()
v4 = v1.strip_namespace(v1.namespace)
v5 = v3.view_map.get(v4, ())
v3.view_map[v4] = ((v1, v2),) + v5 | [] | [] | [] | 5 | #
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB authors.
#
# 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... | null |
v9 | [
"irast.PathId",
"context.ContextLevel"
] | irast.PathId | def v9(v10: irast.PathId, v11: context.ContextLevel) -> irast.PathId:
v12 = None
v13 = False
for v14 in v10.iter_prefixes():
if not v12:
v12 = v14
else:
(v15, v16) = (v14.rptr(), v14.rptr_dir())
assert v15 and v16
v12 = v12.extend(ptrref=v15, d... | [
{
"name": "v0",
"input_types": [
"irast.PathId",
"context.ContextLevel"
],
"output_type": "Optional[irast.Set]",
"code": "def v0(v1: irast.PathId, v2: context.ContextLevel) -> Optional[irast.Set]:\n v3 = v1.strip_namespace(v1.namespace)\n v4 = v2.view_map.get(v3, ())\n v5 = ... | [] | [] | 15 | #
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB authors.
#
# 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... | null |
v0 | [
"List[int]"
] | int | def v0(self, v1: List[int]) -> int:
v2 = 0
(v3, v4) = (0, float('inf'))
(v5, v6) = (0, float('-inf'))
for v7 in v1:
v3 = min(v3 + v7, v7)
v4 = min(v4, v3)
v5 = max(v5 + v7, v7)
v6 = max(v6, v5)
v2 += v7
if v6 > 0:
return max(v2 - v4, v6)
else:
... | [] | [] | [] | 14 | '''
Description:
Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty subarray of C.
Here, a circular array means the end of the array connects to the beginning of the array. (Formally, C[i] = A[i] when 0 <= i < A.length, and C[i+A.length] = C[i] when i >= 0.)
Also, a... | null |
v0 | [
"vapi.NpuBlockOperation"
] | Any | def v0(v1: vapi.NpuBlockOperation):
v2 = v1.activation.min
v3 = v1.activation.max
v4 = (v2 - v1.ofm.quantization.zero_point) * v1.ofm.quantization.scale_f32
v5 = (v3 - v1.ofm.quantization.zero_point) * v1.ofm.quantization.scale_f32
v1.activation.min = v4
v1.activation.max = v5 | [] | [] | [] | 7 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | null |
v0 | [
"str"
] | Iterator[int] | def v0(v1: str) -> Iterator[int]:
if '..' in v1:
(v2, v3) = [int(c, 16) for v4 in v1.split('..')]
else:
v2 = v3 = int(v1, 16)
for v5 in range(v2, v3 + 1):
yield v5 | [] | [] | [] | 7 | #
# (re)generate unicode property and type databases
#
# This script converts Unicode database files to Modules/unicodedata_db.h,
# Modules/unicodename_db.h, and Objects/unicodetype_db.h
#
# history:
# 2000-09-24 fl created (based on bits and pieces from unidb)
# 2000-09-25 fl merged tim's splitbin fixes, separate ... | null |
v5 | [] | Iterator[List[str]] | def v5(self) -> Iterator[List[str]]:
with v0(self.template, self.version) as v6:
for v7 in v6:
v7 = v7.split('#', 1)[0].strip()
if not v7:
continue
yield [field.strip() for v8 in v7.split(';')] | [
{
"name": "v0",
"input_types": [
"Any",
"Any"
],
"output_type": "Any",
"code": "def v0(v1, v2):\n v3 = os.path.join(DATA_DIR, v1 % ('-' + v2,))\n if not os.path.exists(v3):\n import urllib.request\n if v2 == '3.2.0':\n v4 = ('http://www.unicode.org/Publ... | [
"os"
] | [
"import os"
] | 7 | #
# (re)generate unicode property and type databases
#
# This script converts Unicode database files to Modules/unicodedata_db.h,
# Modules/unicodename_db.h, and Objects/unicodetype_db.h
#
# history:
# 2000-09-24 fl created (based on bits and pieces from unidb)
# 2000-09-25 fl merged tim's splitbin fixes, separate ... | null |
v6 | [] | Iterator[Tuple[int, List[str]]] | def v6(self) -> Iterator[Tuple[int, List[str]]]:
for v7 in self.records():
(v8, v9) = (v7[0], v7[1:])
for v10 in v0(v8):
yield (v10, v9) | [
{
"name": "v0",
"input_types": [
"str"
],
"output_type": "Iterator[int]",
"code": "def v0(v1: str) -> Iterator[int]:\n if '..' in v1:\n (v2, v3) = [int(c, 16) for v4 in v1.split('..')]\n else:\n v2 = v3 = int(v1, 16)\n for v5 in range(v2, v3 + 1):\n yield v5",... | [] | [] | 5 | #
# (re)generate unicode property and type databases
#
# This script converts Unicode database files to Modules/unicodedata_db.h,
# Modules/unicodename_db.h, and Objects/unicodetype_db.h
#
# history:
# 2000-09-24 fl created (based on bits and pieces from unidb)
# 2000-09-25 fl merged tim's splitbin fixes, separate ... | null |
v0 | [
"torch.Tensor"
] | Any | def v0(v1: torch.Tensor):
v2 = 1.0 / v1.shape[1]
print(f'Setting default gamma={v2}')
return v2 | [] | [] | [] | 4 | import torch
def default_gamma(X:torch.Tensor):
gamma = 1.0 / X.shape[1]
print(f'Setting default gamma={gamma}')
return gamma
def rbf_kernel(X:torch.Tensor, gamma:float=None):
assert len(X.shape) == 2
if gamma is None:
gamma = default_gamma(X)
K = torch.cdist(X, X)
K.fill_diagon... | null |
v3 | [
"torch.Tensor",
"float"
] | Any | def v3(v4: torch.Tensor, v5: float=None):
assert len(v4.shape) == 2
if v5 is None:
v5 = v0(v4)
v6 = torch.cdist(v4, v4)
v6.fill_diagonal_(0)
v6.pow_(2)
v6.mul_(-v5)
v6.exp_()
return v6 | [
{
"name": "v0",
"input_types": [
"torch.Tensor"
],
"output_type": "Any",
"code": "def v0(v1: torch.Tensor):\n v2 = 1.0 / v1.shape[1]\n print(f'Setting default gamma={v2}')\n return v2",
"dependencies": []
}
] | [
"torch"
] | [
"import torch"
] | 10 | import torch
def default_gamma(X:torch.Tensor):
gamma = 1.0 / X.shape[1]
print(f'Setting default gamma={gamma}')
return gamma
def rbf_kernel(X:torch.Tensor, gamma:float=None):
assert len(X.shape) == 2
if gamma is None:
gamma = default_gamma(X)
K = torch.cdist(X, X)
K.fill_diagon... | null |
v7 | [
"torch.Tensor",
"torch.Tensor",
"float"
] | Any | def v7(v8: torch.Tensor, v9: torch.Tensor, v10: float=None):
assert len(v8.shape) == 2
assert len(v9.shape) == 1
assert torch.all(v9 == v9.sort()[0]), 'This function assumes the dataset is sorted by y'
if v10 is None:
v10 = v0(v8)
v11 = torch.zeros((v8.shape[0], v8.shape[0]))
v12 = v9.un... | [
{
"name": "v0",
"input_types": [
"torch.Tensor"
],
"output_type": "Any",
"code": "def v0(v1: torch.Tensor):\n v2 = 1.0 / v1.shape[1]\n print(f'Setting default gamma={v2}')\n return v2",
"dependencies": []
},
{
"name": "v3",
"input_types": [
"torch.Tensor",
... | [
"torch"
] | [
"import torch"
] | 14 | import torch
def default_gamma(X:torch.Tensor):
gamma = 1.0 / X.shape[1]
print(f'Setting default gamma={gamma}')
return gamma
def rbf_kernel(X:torch.Tensor, gamma:float=None):
assert len(X.shape) == 2
if gamma is None:
gamma = default_gamma(X)
K = torch.cdist(X, X)
K.fill_diagon... | null |
v0 | [
"torch.Tensor",
"float",
"float"
] | Any | def v0(v1: torch.Tensor, v2: float, v3: float):
assert v1.shape[0] == v1.shape[1]
v1.log_()
v1.div_(-v2)
v1.mul_(-v3)
v1.exp_()
return v1 | [] | [] | [] | 7 | import torch
def default_gamma(X:torch.Tensor):
gamma = 1.0 / X.shape[1]
print(f'Setting default gamma={gamma}')
return gamma
def rbf_kernel(X:torch.Tensor, gamma:float=None):
assert len(X.shape) == 2
if gamma is None:
gamma = default_gamma(X)
K = torch.cdist(X, X)
K.fill_diagon... | null |
v0 | [
"str",
"Any"
] | Any | def v0(self, v1: str, v2=Const.INPUT_LEN):
if self.has_field(field_name=v1):
self.apply_field(len, v1, new_field_name=v2)
else:
raise KeyError(f'Field:{v1} not found.')
return self | [] | [] | [] | 6 | r"""
:class:`~fastNLP.core.dataset.DataSet` 是fastNLP中用于承载数据的容器。可以将DataSet看做是一个表格,
每一行是一个sample (在fastNLP中被称为 :mod:`~fastNLP.core.instance` ),
每一列是一个feature (在fastNLP中称为 :mod:`~fastNLP.core.field` )。
.. csv-table:: Following is a demo layout of DataSet
:header: "sentence", "words", "seq_len"
"This is the first i... | null |
v0 | [
"str | csv.Dialect",
"str | None | lib.NoDefault",
"bool",
"CSVEngine | None",
"str | None | lib.NoDefault",
"bool | None",
"bool | None",
"str | Callable | None",
"ArrayLike | None | lib.NoDefault",
"str | None | lib.NoDefault",
"dict[str, Any]"
] | Any | def v0(v1: str | csv.Dialect, v2: str | None | lib.NoDefault, v3: bool, v4: CSVEngine | None, v5: str | None | lib.NoDefault, v6: bool | None, v7: bool | None, v8: str | Callable | None, v9: ArrayLike | None | lib.NoDefault, v10: str | None | lib.NoDefault, v11: dict[str, Any]):
v12 = v11['delimiter']
v13: dict... | [] | [
"pandas"
] | [
"import pandas._libs.lib as lib",
"from pandas._libs.parsers import STR_NA_VALUES",
"from pandas._typing import ArrayLike, CompressionOptions, CSVEngine, DtypeArg, FilePath, ReadCsvBuffer, StorageOptions",
"from pandas.errors import AbstractMethodError, ParserWarning",
"from pandas.util._decorators import A... | 56 | """
Module contains tools for processing files into DataFrames or other objects
"""
from __future__ import annotations
from collections import abc
import csv
import sys
from textwrap import fill
from typing import (
IO,
Any,
Callable,
Literal,
NamedTuple,
Sequence,
overload,
)
import warnin... | null |
v3 | [
"dict[str, Any]"
] | csv.Dialect | None | def v3(v4: dict[str, Any]) -> csv.Dialect | None:
if v4.get('dialect') is None:
return None
v5 = v4['dialect']
if v5 in csv.list_dialects():
v5 = csv.get_dialect(v5)
v0(v5)
return v5 | [
{
"name": "v0",
"input_types": [
"csv.Dialect"
],
"output_type": "None",
"code": "def v0(v1: csv.Dialect) -> None:\n for v2 in MANDATORY_DIALECT_ATTRS:\n if not hasattr(v1, v2):\n raise ValueError(f'Invalid dialect {v1} provided')",
"dependencies": []
}
] | [
"csv"
] | [
"import csv"
] | 8 | """
Module contains tools for processing files into DataFrames or other objects
"""
from __future__ import annotations
from collections import abc
import csv
import sys
from textwrap import fill
from typing import (
Any,
NamedTuple,
)
import warnings
import numpy as np
import pandas._libs.lib as lib
from pan... | null |
v0 | [
"Dict[str, Any]"
] | None | def v0(v1: Dict[str, Any]) -> None:
if v1.get('skipfooter'):
if v1.get('iterator') or v1.get('chunksize'):
raise ValueError("'skipfooter' not supported for 'iteration'")
if v1.get('nrows'):
raise ValueError("'skipfooter' not supported with 'nrows'") | [] | [] | [] | 6 | """
Module contains tools for processing files into DataFrames or other objects
"""
from collections import abc, defaultdict
import csv
import datetime
from io import StringIO, TextIOWrapper
import itertools
import re
import sys
from textwrap import fill
from typing import Any, Dict, Iterable, List, Optional, Sequence... | null |
v0 | [
"List[str]"
] | bool | def v0(v1: List[str]) -> bool:
v2 = ['CHROM', 'POS', 'ID', 'REF', 'ALT', 'QUAL', 'FILTER', 'INFO', 'FORMAT']
for (v3, v4) in enumerate(v2):
if v1[v3] != v4:
return False
return True | [] | [] | [] | 6 | import argparse
import pegasusio as io
import numpy as np
import pandas as pd
from collections import namedtuple
from typing import List, Dict, Tuple
demux_type_dict = {'SNG': 'singlet', 'DBL': 'doublet', 'AMB': 'unknown'}
SNP = namedtuple('SNP', ['CHROM', 'POS', 'REF', 'ALT'])
def check_colnames(fields: List[str]... | null |
v0 | [
"List[str]",
"List[str]",
"np.array"
] | None | def v0(v1: List[str], v2: List[str], v3: np.array) -> None:
for (v4, v5) in enumerate(v2):
for (v6, v7) in enumerate(v1):
v3[v4, v6] += v5 == v7 | [] | [] | [] | 4 | import argparse
import pegasusio as io
import numpy as np
import pandas as pd
from collections import namedtuple
from typing import List, Dict, Tuple
demux_type_dict = {'SNG': 'singlet', 'DBL': 'doublet', 'AMB': 'unknown'}
SNP = namedtuple('SNP', ['CHROM', 'POS', 'REF', 'ALT'])
def check_colnames(fields: List[str]... | null |
v0 | [
"str",
"List[str]",
"bool"
] | List[str] | def v0(v1: str, v2: List[str], v3: bool) -> List[str]:
if v1 is not None:
v4 = v1.split(',')
assert len(v4) == len(v2)
v2 = v4
elif not v3:
v2 = ['Donor' + str(int(x[5:]) + 1) for v5 in v2]
v2 = ['_ref_' + v5 for v5 in v2]
return v2 | [] | [] | [] | 9 | import argparse
import pegasusio as io
import numpy as np
import pandas as pd
from collections import namedtuple
from typing import List, Dict, Tuple
demux_type_dict = {'SNG': 'singlet', 'DBL': 'doublet', 'AMB': 'unknown'}
SNP = namedtuple('SNP', ['CHROM', 'POS', 'REF', 'ALT'])
def check_colnames(fields: List[str]... | null |
v0 | [
"str",
"dict"
] | str | def v0(v1: str, v2: dict) -> str:
if v1 == '':
return v1
v3 = []
for v4 in v1.split(','):
v3.append(v2[f'CLUST{v4}'][5:])
return ','.join(v3) | [] | [] | [] | 7 | import argparse
import pegasusio as io
import numpy as np
import pandas as pd
from collections import namedtuple
from typing import List, Dict, Tuple
demux_type_dict = {'SNG': 'singlet', 'DBL': 'doublet', 'AMB': 'unknown'}
SNP = namedtuple('SNP', ['CHROM', 'POS', 'REF', 'ALT'])
def check_colnames(fields: List[str]... | null |
v0 | [
"List[str]",
"List[str]"
] | dict | def v0(v1: List[str], v2: List[str]) -> dict:
assert len(v1) == len(v2)
v3 = dict()
v4 = list(zip(v1, v2))
for (v5, v6) in v4:
v3[v5] = v6
v3[v6] = v5
return v3 | [] | [] | [] | 8 | import argparse
import pegasusio as io
import numpy as np
import pandas as pd
from collections import namedtuple
from typing import List, Dict, Tuple
demux_type_dict = {'SNG': 'singlet', 'DBL': 'doublet', 'AMB': 'unknown'}
SNP = namedtuple('SNP', ['CHROM', 'POS', 'REF', 'ALT'])
def check_colnames(fields: List[str]... | null |
v5 | [
"List[str]",
"str"
] | str | def v5(self, v6: List[str], v7: str) -> str:
def v8():
return collections.defaultdict(v8)
v9 = v8()
v10 = '*'
for v11 in v6:
functools.reduce(dict.__getitem__, v11, v9)[v10] = v11
def v12(v13):
v14 = v9
for v15 in v13:
if v15 not in v14 or v10 in v14:
... | [
{
"name": "v0",
"input_types": [],
"output_type": "Any",
"code": "def v0():\n return collections.defaultdict(v0)",
"dependencies": []
},
{
"name": "v1",
"input_types": [
"Any"
],
"output_type": "Any",
"code": "def v1(v2):\n v3 = trie\n for v4 in v2:\n ... | [
"collections",
"functools"
] | [
"import collections",
"import functools"
] | 17 | import collections
import functools
from typing import List
class RootTrie:
def replaceWords(self, roots: List[str], sentence: str) -> str:
def Trie():
return collections.defaultdict(Trie)
trie = Trie()
END_SYMBOL = '*'
for root in roots:
functools.reduce(... | null |
v0 | [
"Index",
"Any"
] | Any | def v0(v1: Index, v2):
if isinstance(v2, dict):
return v2.get
elif isinstance(v2, Series):
if v2.index.equals(v1):
return v2._values
else:
return v2.reindex(v1)._values
elif isinstance(v2, MultiIndex):
return v2._values
elif isinstance(v2, (list, t... | [] | [
"numpy",
"pandas"
] | [
"import numpy as np",
"from pandas._typing import ArrayLike, NDFrameT, npt",
"from pandas.errors import InvalidIndexError",
"from pandas.util._decorators import cache_readonly",
"from pandas.util._exceptions import find_stack_level",
"from pandas.core.dtypes.cast import sanitize_to_nanoseconds",
"from p... | 18 | """
Provide user facing operators for doing the split part of the
split-apply-combine paradigm.
"""
from __future__ import annotations
from typing import (
TYPE_CHECKING,
Any,
Hashable,
final,
)
import warnings
import numpy as np
from pandas._typing import (
ArrayLike,
NDFrameT,
npt,
)
fr... | null |
v40 | [
"FrameOrSeries",
"bool"
] | Any | def v40(self, v41: FrameOrSeries, v42: bool=True):
self._set_grouper(v41)
(self.grouper, v43, self.obj) = v2(self.obj, [self.key], axis=self.axis, level=self.level, sort=self.sort, validate=v42, dropna=self.dropna)
return (self.binner, self.grouper, self.obj) | [
{
"name": "v0",
"input_types": [
"Any"
],
"output_type": "bool",
"code": "def v0(v1) -> bool:\n return isinstance(v1, (str, tuple)) or (v1 is not None and is_scalar(v1))",
"dependencies": []
},
{
"name": "v2",
"input_types": [
"FrameOrSeries",
"Any",
"i... | [
"numpy",
"pandas"
] | [
"import numpy as np",
"from pandas._typing import FrameOrSeries, final",
"from pandas.errors import InvalidIndexError",
"from pandas.util._decorators import cache_readonly",
"from pandas.core.dtypes.common import is_categorical_dtype, is_datetime64_dtype, is_list_like, is_scalar, is_timedelta64_dtype",
"i... | 4 | """
Provide user facing operators for doing the split part of the
split-apply-combine paradigm.
"""
from __future__ import annotations
from typing import Hashable
import warnings
import numpy as np
from pandas._typing import (
FrameOrSeries,
final,
)
from pandas.errors import InvalidIndexError
from pandas.ut... | null |
v0 | [
"FrameOrSeries",
"bool"
] | Any | def v0(self, v1: FrameOrSeries, v2: bool=False):
assert v1 is not None
if self.key is not None and self.level is not None:
raise ValueError('The Grouper cannot specify both a key and a level!')
if self._grouper is None:
self._grouper = self.grouper
if self.key is not None:
v3 = s... | [] | [
"pandas"
] | [
"from pandas.util._decorators import cache_readonly",
"from pandas.core.dtypes.common import ensure_categorical, is_categorical_dtype, is_datetime64_dtype, is_list_like, is_scalar, is_timedelta64_dtype",
"from pandas.core.dtypes.generic import ABCSeries",
"from pandas._typing import FrameOrSeries",
"import ... | 30 | """
Provide user facing operators for doing the split part of the
split-apply-combine paradigm.
"""
from typing import Hashable, List, Optional, Tuple
import numpy as np
from pandas.util._decorators import cache_readonly
from pandas.core.dtypes.common import (
ensure_categorical,
is_categorical_dtype,
i... | null |
v0 | [] | None | def v0(self) -> None:
if self._codes is None or self._group_index is None:
if isinstance(self.grouper, ops.BaseGrouper):
v1 = self.grouper.codes_info
v2 = self.grouper.result_index
else:
print('Calling this factorize function')
(v1, v2) = algorithms.fa... | [] | [
"pandas"
] | [
"from pandas.util._decorators import cache_readonly",
"from pandas.core.dtypes.common import ensure_categorical, is_categorical_dtype, is_datetime64_dtype, is_list_like, is_scalar, is_timedelta64_dtype",
"from pandas.core.dtypes.generic import ABCSeries",
"from pandas._typing import FrameOrSeries",
"import ... | 14 | """
Provide user facing operators for doing the split part of the
split-apply-combine paradigm.
"""
from typing import Hashable, List, Optional, Tuple
import numpy as np
from pandas.util._decorators import cache_readonly
from pandas.core.dtypes.common import (
ensure_categorical,
is_categorical_dtype,
i... | null |
v0 | [
"dict[str, Any]"
] | Optional[str] | def v0(v1: dict[str, Any]) -> Optional[str]:
v2 = v1.get('display_name')
v3 = v1.get('fullname')
v4 = v1.get('title')
v5 = v1.get('name')
return v2 or v3 or v4 or v5 | [] | [] | [] | 6 | # -*- coding: utf-8 -*-
from __future__ import annotations
import logging
from datetime import datetime
from typing import Any, Optional, Union, cast
from flask import Blueprint
import ckan.plugins.toolkit as tk
import ckan.model as model
from ckan.views.group import (
set_org,
# TODO: don't use hidden funci... | null |
v0 | [
"str"
] | dict[str, Any] | def v0(self, v1: str) -> dict[str, Any]:
if self._disable_cache:
return self._get_package_info(v1)
v2: dict[str, Any] = self._cache.store('packages').remember_forever(v1, lambda : self._get_package_info(v1))
return v2 | [] | [] | [] | 5 | from __future__ import annotations
import logging
from collections import defaultdict
from typing import TYPE_CHECKING
from typing import Any
import requests
from cachecontrol.controller import logger as cache_control_logger
from html5lib.html5parser import parse
from poetry.core.packages.package import Package
fro... | null |
v0 | [
"str"
] | Union[dict, None] | def v0(self, v1: str) -> Union[dict, None]:
try:
v2 = self.session.get(self._base_url + v1)
except requests.exceptions.TooManyRedirects:
self._cache_control_cache.delete(self._base_url + v1)
v2 = self.session.get(self._base_url + v1)
if v2.status_code == 404:
return None
... | [] | [
"requests"
] | [
"import requests"
] | 10 | import logging
import os
import urllib.parse
from collections import defaultdict
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Dict
from typing import List
from typing import Union
import requests
from cachecontrol import CacheControl
from cachecontrol.caches.file_cache import FileCach... | null |
v0 | [
"List[str]",
"bool"
] | Any | def v0(self, v1: List[str]=None, v2: bool=False):
v3 = v1 if v1 is not None else self.pnl_names
v4 = self.df['xcat'].isin(v3)
v5 = self.df['cid'] == 'ALL' if not v2 else True
return self.df[v4 & v5] | [] | [] | [] | 5 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from typing import List, Union, Tuple
from macrosynergy.management.simulate_quantamental_data import make_qdf
from macrosynergy.management.shape_dfs import reduce_df
class NaivePnL:
"""Computes and collects illustrativ... | null |
v0 | [
"str",
"str",
"Any"
] | Any | def v0(v1: str, v2: str, v3):
v4 = '.'
v5 = os.path.join(v4, v1 + v2 + '.png')
v6 = plt.get_current_fig_manager()
v6.window.showMaximized()
v3.set_size_inches((16, 9), forward=False)
plt.savefig(v5, dpi=150, facecolor='w', edgecolor='w', orientation='landscape', transparent=False, bbox_inches='t... | [] | [
"matplotlib",
"os"
] | [
"import os",
"import matplotlib",
"import matplotlib.pyplot as plt"
] | 7 | from typing import List
import functools
import os
import matplotlib
# TkAgg with default tk leads to the matplotlib mainloop not terminating although all plot windows are closed
matplotlib.use('qt5agg') # MUST BE CALLED BEFORE IMPORTING plt
import matplotlib.pyplot as plt
import numpy as np
import scipy # don't rem... | null |
v0 | [
"plt.axes",
"List",
"List",
"str",
"List[str]",
"List",
"List",
"List",
"Any",
"Any",
"Any",
"Any"
] | Any | def v0(v1: plt.axes, v2: List, v3: List, v4: str, v5: List[str], v6: List, v7: List, v8: List, v9, v10, v11=True, v12=True):
for v13 in range(len(v2)):
v1.scatter(x=v2[v13], y=v3[v13], c=v6[v13], s=v7[v13], alpha=v8[v13], label=v5[v13])
v1.set_xlabel(v9)
v1.set_ylabel(v10)
v1.set_title(v4)
i... | [] | [
"numpy"
] | [
"import numpy as np"
] | 25 | from typing import List
import functools
import os
import matplotlib
# TkAgg with default tk leads to the matplotlib mainloop not terminating although all plot windows are closed
matplotlib.use('qt5agg') # MUST BE CALLED BEFORE IMPORTING plt
import matplotlib.pyplot as plt
import numpy as np
import scipy # don't rem... | null |
v23 | [
"Any",
"pd.PlotData"
] | Any | def v23(v24, v25: pd.PlotData):
v26 = np.unique(v25.gear)
v26 = np.sort(v26)
v27 = ['Gear {}'.format(str(g)) for v28 in v26]
v29 = []
v30 = []
for (v31, v28) in enumerate(v26):
v32 = v25.gear == v28
v29 += [v25.pos_x[v32]]
v30 += [v25.pos_y[v32]]
v0(v24, plot_data=v25... | [
{
"name": "v0",
"input_types": [
"Any",
"pd.PlotData",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any"
],
"output_type": "Any",
"code": "def v0(v1, v2: pd.PlotData, v3, v4, v5, v6, v7, v8):\n (v9, v10, v11) = data_processing.get_min_middle_max(v2.pos_x... | [
"numpy"
] | [
"import numpy as np"
] | 11 | from typing import List
import functools
import os
import matplotlib
# TkAgg with default tk leads to the matplotlib mainloop not terminating although all plot windows are closed
matplotlib.use('qt5agg') # MUST BE CALLED BEFORE IMPORTING plt
import matplotlib.pyplot as plt
import numpy as np
import scipy # don't rem... | null |
v29 | [
"Any",
"pd.PlotData"
] | Any | def v29(v30, v31: pd.PlotData):
v32 = v31.run_time
v33 = v31.throttle
v34 = v31.brakes
v35 = v31.steering
v36 = np.array([v33, v34, v35])
v37 = ['Throttle', 'Brakes', 'Steering']
v38 = v36
v39 = np.array([v32] * v38.shape[0])
v0(v30, x_points=v39, y_points=v38, title='Inputs over tim... | [
{
"name": "v0",
"input_types": [
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any"
],
"output_type": "Any",
"code": "def v0(v1, v2, v3, v4, v5, v6, v7, v8, v9=None, v10=False, v11=True):\n v12 = np.con... | [
"numpy"
] | [
"import numpy as np"
] | 10 | from typing import List
import functools
import os
import matplotlib
# TkAgg with default tk leads to the matplotlib mainloop not terminating although all plot windows are closed
matplotlib.use('qt5agg') # MUST BE CALLED BEFORE IMPORTING plt
import matplotlib.pyplot as plt
import numpy as np
import scipy # don't rem... | null |
v29 | [
"Any",
"pd.PlotData"
] | Any | def v29(v30, v31: pd.PlotData):
v32 = v31.run_time
v33 = v31.speed_ms
v34 = v31.wsp_fl
v35 = v31.wsp_fr
v36 = v31.wsp_rl
v37 = v31.wsp_rr
v38 = [v34, v35, v36, v37]
v39 = [w - v33 for v40 in v38]
v41 = np.array(v39)
v42 = [np.var(d) for v43 in v41]
v44 = ['Front left', 'Front... | [
{
"name": "v0",
"input_types": [
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any"
],
"output_type": "Any",
"code": "def v0(v1, v2, v3, v4, v5, v6, v7, v8, v9=None, v10=False, v11=True):\n v12 = np.con... | [
"numpy"
] | [
"import numpy as np"
] | 16 | from typing import List
import functools
import os
import matplotlib
# TkAgg with default tk leads to the matplotlib mainloop not terminating although all plot windows are closed
matplotlib.use('qt5agg') # MUST BE CALLED BEFORE IMPORTING plt
import matplotlib.pyplot as plt
import numpy as np
import scipy # don't rem... | null |
v29 | [
"Any",
"pd.PlotData"
] | Any | def v29(v30, v31: pd.PlotData):
v32 = v31.run_time
v33 = v31.susp_fl
v34 = v31.susp_fr
v35 = v31.susp_rl
v36 = v31.susp_rr
v37 = (v33 + v35) * 0.5 - (v34 + v36) * 0.5
v38 = (v33 + v34) * 0.5 - (v35 + v36) * 0.5
v39 = np.array([v37, v38])
v40 = [np.sqrt(np.var(d)) for v41 in v39]
... | [
{
"name": "v0",
"input_types": [
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any"
],
"output_type": "Any",
"code": "def v0(v1, v2, v3, v4, v5, v6, v7, v8, v9=None, v10=False, v11=True):\n v12 = np.con... | [
"numpy"
] | [
"import numpy as np"
] | 15 | from typing import List
import functools
import os
import matplotlib
# TkAgg with default tk leads to the matplotlib mainloop not terminating although all plot windows are closed
matplotlib.use('qt5agg') # MUST BE CALLED BEFORE IMPORTING plt
import matplotlib.pyplot as plt
import numpy as np
import scipy # don't rem... | null |
v29 | [
"Any",
"pd.PlotData"
] | Any | def v29(v30, v31: pd.PlotData):
v32 = v31.run_time
v33 = v31.susp_fl
v34 = v31.susp_fr
v35 = v31.susp_rl
v36 = v31.susp_rr
v37 = (v33 + v35) * 0.5
v38 = (v34 + v36) * 0.5
v39 = (v33 + v34) * 0.5
v40 = (v35 + v36) * 0.5
v41 = np.array([v37, v38, v39, v40])
v42 = [np.sqrt(np.va... | [
{
"name": "v0",
"input_types": [
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any"
],
"output_type": "Any",
"code": "def v0(v1, v2, v3, v4, v5, v6, v7, v8, v9=None, v10=False, v11=True):\n v12 = np.con... | [
"numpy"
] | [
"import numpy as np"
] | 17 | from typing import List
import functools
import os
import matplotlib
# TkAgg with default tk leads to the matplotlib mainloop not terminating although all plot windows are closed
matplotlib.use('qt5agg') # MUST BE CALLED BEFORE IMPORTING plt
import matplotlib.pyplot as plt
import numpy as np
import scipy # don't rem... | null |
v0 | [
"Any",
"pd.PlotData"
] | Any | def v0(v1, v2: pd.PlotData):
v3 = v2.distance
v4 = np.abs(v2.pos_z)
v1.plot(v3, v4, label='Height')
v1.set(xlabel='Distance (m)', ylabel='Height (m)', title='Track Elevation')
v1.grid() | [] | [
"numpy"
] | [
"import numpy as np"
] | 6 | from typing import List
import functools
import os
import matplotlib
# TkAgg with default tk leads to the matplotlib mainloop not terminating although all plot windows are closed
matplotlib.use('qt5agg') # MUST BE CALLED BEFORE IMPORTING plt
import matplotlib.pyplot as plt
import numpy as np
import scipy # don't rem... | null |
v29 | [
"Any",
"pd.PlotData"
] | Any | def v29(v30, v31: pd.PlotData):
v32 = v31.run_time
v33 = np.array([v31.wsp_fl, v31.wsp_fr, v31.wsp_rl, v31.wsp_rr])
v34 = ['Front left', 'Front right', 'Rear left', 'Rear right']
v35 = np.array([v32] * len(v33))
v36 = np.array(v33)
v0(v30, x_points=v35, y_points=v36, title='Wheel speed over time... | [
{
"name": "v0",
"input_types": [
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any"
],
"output_type": "Any",
"code": "def v0(v1, v2, v3, v4, v5, v6, v7, v8, v9=None, v10=False, v11=True):\n v12 = np.con... | [
"numpy"
] | [
"import numpy as np"
] | 7 | from typing import List
import functools
import os
import matplotlib
# TkAgg with default tk leads to the matplotlib mainloop not terminating although all plot windows are closed
matplotlib.use('qt5agg') # MUST BE CALLED BEFORE IMPORTING plt
import matplotlib.pyplot as plt
import numpy as np
import scipy # don't rem... | null |
v29 | [
"Any",
"pd.PlotData"
] | Any | def v29(v30, v31: pd.PlotData):
v32 = v31.run_time
v33 = (v31.wsp_fl + v31.wsp_rl) * 0.5 - (v31.wsp_fr + v31.wsp_rr) * 0.5
v34 = (v31.wsp_fl + v31.wsp_fr) * 0.5 - (v31.wsp_rl + v31.wsp_rr) * 0.5
v35 = np.array([v33, v34])
v36 = ['left-right', 'front-rear']
v37 = np.array([v32] * len(v35))
v3... | [
{
"name": "v0",
"input_types": [
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any",
"Any"
],
"output_type": "Any",
"code": "def v0(v1, v2, v3, v4, v5, v6, v7, v8, v9=None, v10=False, v11=True):\n v12 = np.con... | [
"numpy"
] | [
"import numpy as np"
] | 9 | from typing import List
import functools
import os
import matplotlib
# TkAgg with default tk leads to the matplotlib mainloop not terminating although all plot windows are closed
matplotlib.use('qt5agg') # MUST BE CALLED BEFORE IMPORTING plt
import matplotlib.pyplot as plt
import numpy as np
import scipy # don't rem... | null |
v33 | [
"Any",
"pd.PlotData"
] | Any | def v33(v34, v35: pd.PlotData):
v36 = v35.run_time
v37 = v35.susp_fl
v38 = v35.susp_fr
v39 = v35.susp_rl
v40 = v35.susp_rr
v41 = (v37 + v39) * 0.5 - (v38 + v40) * 0.5
v42 = (v37 + v38) * 0.5 - (v39 + v40) * 0.5
def v43(v44, v45):
v46 = np.arcsin(v44 / v45)
return np.rad2... | [
{
"name": "v0",
"input_types": [
"Any",
"Any"
],
"output_type": "Any",
"code": "def v0(v1, v2):\n v3 = np.arcsin(v1 / v2)\n return np.rad2deg(v3)",
"dependencies": []
},
{
"name": "v4",
"input_types": [
"Any",
"Any",
"Any",
"Any",
"... | [
"numpy"
] | [
"import numpy as np"
] | 21 | from typing import List
import functools
import os
import matplotlib
# TkAgg with default tk leads to the matplotlib mainloop not terminating although all plot windows are closed
matplotlib.use('qt5agg') # MUST BE CALLED BEFORE IMPORTING plt
import matplotlib.pyplot as plt
import numpy as np
import scipy # don't rem... | null |
v7 | [
"str"
] | Any | def v7(v8: str='default'):
v9 = v0(v8)
v9.barrier() | [
{
"name": "v0",
"input_types": [
"Any"
],
"output_type": "Any",
"code": "def v0(v1):\n _check_inside_actor()\n if not is_group_initialized(v1):\n raise RuntimeError(\"The collective group '{}' is not initialized in the process.\".format(v1))\n v2 = _group_mgr.get_group_by_n... | [] | [] | 3 | """APIs exposed under the namespace ray.util.collective."""
import logging
import numpy as np
import ray
from ray.util.collective import types
from ray.util.collective.const import get_nccl_store_name
_MPI_AVAILABLE = False
_NCCL_AVAILABLE = True
# try:
# from ray.util.collective.collective_group.mpi_collective_... | null |
v0 | [
"Any",
"int"
] | Any | def v0(v1, v2: int):
if v2 < 0:
raise ValueError("rank '{}' is negative.".format(v2))
if v2 >= v1.world_size:
raise ValueError("rank '{}' must be less than world size '{}'".format(v2, v1.world_size)) | [] | [] | [] | 5 | """APIs exposed under the namespace ray.util.collective."""
import logging
import os
from typing import List
import numpy as np
import ray
from ray.util.collective import types
_NCCL_AVAILABLE = True
_GLOO_AVAILABLE = True
logger = logging.getLogger(__name__)
try:
from ray.util.collective.collective_group.nccl_... | null |
v4 | [
"list",
"Any"
] | bool | def v4(v5: list, v6=False) -> bool:
if len(v5) < 2:
return True
v7 = operator.gt
if v6:
v7 = operator.lt
return v0(v5, 0, v7) | [
{
"name": "v0",
"input_types": [
"list",
"int",
"Any"
],
"output_type": "bool",
"code": "def v0(v1: list, v2: int, v3) -> bool:\n if v2 == len(v1) - 1:\n return True\n if v3(v1[v2], v1[v2 + 1]):\n return False\n else:\n return v0(v1, v2 + 1, v3)",
... | [
"operator"
] | [
"import operator"
] | 7 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# Meta-info
Author: Nelson Brochado
Created: 21/01/2017
Updated: 19/09/2017
# Description
is_sorted checks if a list or tuple contains elements in sorted order by using
recursion. This algorithm can potentially be modified to work with other
collections. The othe... | null |
v0 | [
"Any",
"Any"
] | bool | def v0(v1, v2=False) -> bool:
if len(v1) < 2:
return True
v3 = operator.gt
if v2:
v3 = operator.lt
for v4 in range(len(v1) - 1):
if v3(v1[v4], v1[v4 + 1]):
return False
return True | [] | [
"operator"
] | [
"import operator"
] | 10 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# Meta-info
Author: Nelson Brochado
Created: 21/01/2017
Updated: 19/09/2017
# Description
is_sorted checks if a list or tuple contains elements in sorted order by using
recursion. This algorithm can potentially be modified to work with other
collections. The othe... | null |
v0 | [
"Any",
"Any"
] | bool | def v0(v1, v2=False) -> bool:
v3 = operator.le
if v2:
v3 = operator.ge
return all((v3(v1[i], v1[i + 1]) for v4 in range(len(v1) - 1))) | [] | [
"operator"
] | [
"import operator"
] | 5 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# Meta-info
Author: Nelson Brochado
Created: 21/01/2017
Updated: 19/09/2017
# Description
is_sorted checks if a list or tuple contains elements in sorted order by using
recursion. This algorithm can potentially be modified to work with other
collections. The othe... | null |
v0 | [
"np.ndarray",
"np.ndarray",
"np.ndarray",
"int"
] | Tuple[np.ndarray, np.ndarray, np.ndarray] | def v0(v1: np.ndarray, v2: np.ndarray, v3: np.ndarray, v4: int=500) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
v1 = v1[:v4]
v2 = v2[:v4]
v3 = v3[:v4]
return (v1, v2, v3) | [] | [] | [] | 5 | import sys
from typing import Tuple
import cmgp.logger as log
import numpy as np
import pytest
from cmgp import CMGP
from cmgp.datasets import load
from cmgp.utils.metrics import sqrt_PEHE_with_diff
log.add(sink=sys.stderr, level="DEBUG")
def downsample(
X: np.ndarray, W: np.ndarray, Y: np.ndarray, downsample: ... | null |
v0 | [
"Any"
] | bytes | def v0(v1: Any) -> bytes:
if isinstance(v1, bytes):
return v1
elif isinstance(v1, str):
return bytes(v1, encoding='utf-8')
else:
return bytes(v1) | [] | [] | [] | 7 | #!/usr/bin/env python
# coding: utf-8
__author__ = 'ChenyangGao <https://chenyanggao.github.io/>'
__version__ = (0, 0, 1)
__all__ = ['make_element', 'make_html_element', 'xml_fromstring', 'xml_tostring',
'html_fromstring', 'html_tostring']
from typing import (
cast, Any, Final, List, Mapping, Optiona... | null |
v0 | [
"Any",
"datetime.datetime"
] | Any | def v0(self, v1, v2: datetime.datetime=None):
self.state = v1
self.__class__.objects.filter(id=self.id).update(state=str(v1.id))
v3 = getattr(self, 'invalidate_caches', None)
if v3:
v3()
self.state.on_enter_state(self) | [] | [] | [] | 7 | # ----------------------------------------------------------------------
# @workflow decorator
# ----------------------------------------------------------------------
# Copyright (C) 2007-2017 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# Python m... | null |
v0 | [
"str",
"bool"
] | str | def v0(v1: str, v2: bool=False) -> str:
try:
v3 = datetime.fromisoformat(v1.strip())
except ValueError:
return v1
if v2:
return v3.strftime('%A %d %B %Y %H:%M')
return v3.strftime('%A %d %B %Y') | [] | [
"datetime"
] | [
"from datetime import datetime"
] | 8 | """
helpers: Module containing helper functions
"""
from datetime import datetime
from typing import Dict
from typing import List
from rdflib import Graph, Literal, URIRef
from rdflib.namespace import DCTERMS, Namespace, OWL, PROV, SH
from rdflib.term import Node
BESLUIT = Namespace("http://data.vlaanderen.be/ns/bes... | null |
v0 | [
"List[Union[int, float]]",
"float",
"Optional[str]"
] | Tuple[Union[int, float], Union[int, float]] | def v0(v1: List[Union[int, float]], v2: float, v3: Optional[str]=None) -> Tuple[Union[int, float], Union[int, float]]:
v4 = max(v1)
v5 = min(v1)
if v3 == 'log':
v6 = (math.log10(v4) - math.log10(v5)) * v2
return (math.pow(10, math.log10(v5) - v6), math.pow(10, math.log10(v4) + v6))
elif ... | [] | [
"math"
] | [
"import math"
] | 13 | import math
from typing import List
from typing import Optional
from typing import Tuple
from typing import Union
from optuna._experimental import experimental
from optuna.logging import get_logger
from optuna.study import Study
from optuna.trial import FrozenTrial
from optuna.trial import TrialState
from optuna.visua... | null |
v0 | [
"Any",
"Any",
"Any",
"Any",
"Any"
] | int | def v0(v1, v2=0, v3=MAX_ITERATIONS + 1, v4=abs, v5=range) -> int:
for v6 in v5(v3):
v2 = v2 * v2 + v1
if v4(v2) > 2:
return v6
return -1 | [] | [] | [] | 6 | # python3: CircuitPython 3.0
# Author: Gregory P. Smith (@gpshead) <greg@krypto.org>
#
# Copyright 2018 Google LLC
#
# 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.... | null |
v0 | [
"str",
"float"
] | Any | def v0(v1: str, v2: float=0.2):
random.seed(0)
assert os.path.exists(v1), 'dataset root: {} does not exist.'.format(v1)
if os.path.exists('./biecaibaikuai/json/train_images_path.json'):
with open('./biecaibaikuai/json/train_images_path.json', 'r') as v3:
v4 = json.load(v3)
with o... | [] | [
"json",
"matplotlib",
"os",
"random"
] | [
"import os",
"import json",
"import random",
"import matplotlib.pyplot as plt"
] | 60 | import os
import sys
import json
import pickle
import random
import torch
from tqdm import tqdm
import matplotlib.pyplot as plt
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter('./mnist/tensorboard')
def read_split_data(root: str, val_rate: float = 0.2):
ra... | null |
v0 | [
"str"
] | list | def v0(v1: str) -> list:
v2: list = []
with open(v1, 'r') as v3:
v4: list = v3.readlines()
for v5 in v4:
v2.append(v5)
return v2 | [] | [] | [] | 7 | from math import isnan
from os import stat
from splunklib.client import connect
import click
import json
import numpy as np
import os
import pandas as pd
import re
import shlex
import splunklib.client as client
import splunklib.results as results
import time
import warnings
# command_line_args = {}
# logging.basicCo... | null |
v0 | [
"int",
"int"
] | None | def v0(self, v1: int=12, v2: int=222) -> None:
v3 = v1 + 100
v4 = str(v3)
self.create_model('motion_workflow/' + str(v1), {'name': 'name_workflow1', 'first_state_id': v3, 'state_ids': [v3]})
self.create_model('motion_state/' + v4, {'name': 'name_state' + v4, 'meeting_id': v2}) | [] | [] | [] | 5 | import threading
from tests.system.action.base import BaseActionTestCase
from tests.system.action.lock import (
monkeypatch_datastore_adapter_write,
pytest_thread_local,
)
class MotionCreateActionTestSequenceNumber(BaseActionTestCase):
def create_workflow(self, workflow_id: int = 12, meeting_id: int = 22... | null |
v0 | [] | None | def v0(self) -> None:
self.create_model('meeting/222', {'name': 'meeting222'})
self.create_workflow()
v1 = self.client.post('/', json=[{'action': 'motion.create', 'data': [{'title': 'motion_title', 'meeting_id': 222, 'workflow_id': 12, 'text': 'test'}]}])
self.assert_status_code(v1, 200)
v2 = self.g... | [] | [] | [] | 15 | import threading
from tests.system.action.base import BaseActionTestCase
from tests.system.action.lock import (
monkeypatch_datastore_adapter_write,
pytest_thread_local,
)
class MotionCreateActionTestSequenceNumber(BaseActionTestCase):
def create_workflow(self, workflow_id: int = 12, meeting_id: int = 22... | null |
v0 | [
"Any",
"str",
"Any",
"Any"
] | Dict[str, str] | def v0(v1, v2: str, v3, v4) -> Dict[str, str]:
v2 = v2.encode()
v5 = f'{v3}{v4}'.encode()
v6 = hmac.new(key=v2, msg=v5, digestmod=hashlib.sha256).hexdigest()
return {'X-Revinate-Porter-Username': v3, 'X-Revinate-Porter-Timestamp': v4, 'X-Revinate-Porter-Key': v1, 'X-Revinate-Porter-Encoded': v6} | [] | [
"hashlib",
"hmac"
] | [
"import hashlib",
"import hmac"
] | 5 | """Modules containing the helper functions for the Revinate connector"""
import hashlib
import hmac
from typing import Dict
def build_headers(api_key, api_secret: str, username, timestamp) -> Dict[str, str]:
"""
Takes a Revinate api_key, api_secret, username and the current timestamp in POSIX epochs and gener... | null |
v0 | [
"str",
"str"
] | str | def v0(v1: str, v2: str) -> str:
(v1, v2) = (list(v1), list(v2))
(v3, v4) = (0, [])
while len(v1) > 0 or len(v2) > 0:
v5 = v6 = 0
if v1:
v5 = ord(v1.pop()) - ord('0')
if v2:
v6 = ord(v2.pop()) - ord('0')
v7 = v5 + v6 + v3
v4.append(v7 % 10)
... | [] | [] | [] | 15 | def addStrings(num1: str, num2: str) -> str:
num1, num2 = list(num1), list(num2)
carry, res = 0, []
while len(num1) > 0 or len(num2) > 0:
n1 = n2 = 0
if num1:
n1 = ord(num1.pop()) - ord('0')
if num2:
n2 = ord(num2.pop()) - ord('0')
temp = n1 + n2 + ... | null |
v1 | [
"int",
"int"
] | int | def v1(v2: int, v3: int) -> int:
if v3 == 0:
if v2 == 0 or v2 == -4:
return 5
else:
return -4
elif v3 == 1:
if v2 == 0 or v2 == 6:
return -5
else:
return 6
else:
raise SystemExit(f"Invalid 'stepType' in func 'stepIndex' ... | [
{
"name": "v0",
"input_types": [],
"output_type": "Any",
"code": "def v0():\n return currentframe().f_back.f_lineno",
"dependencies": []
}
] | [
"inspect"
] | [
"from inspect import currentframe"
] | 13 | #!/usr/bin/env python3
import json
import math
import random
from inspect import currentframe
# Import from custom utilities
from util.mockStudents import getSampleStudents
from util.generateCourses import getSampleCourses
'''
Block 1-5 is first semester while
block 6-10 is second semester
schedule example:
... | null |
v0 | [] | Dict[str, str] | def v0(self) -> Dict[str, str]:
v1 = input('Please enter the number of members in your party: ')
v2 = input('Please enter the age of the youngest member in your party: ')
v3 = input('Please enter the age of the oldest member in your party: ')
v4 = input('Please enter your current zip code: ')
v5 = i... | [] | [] | [] | 16 | from typing import Dict
class View:
def build_profile(self) -> Dict[str, str]:
"""
Displays prompt bar and obtains user input
"""
num_members = input("Please enter the number of members in your party: ")
min_age = input("Please enter the age of the youngest member in your ... | null |
v0 | [] | None | def v0(self) -> None:
v1 = '\n from django.utils.decorators import available_attrs\n\n def my_decorator(func):\n @wraps(func, assigned=available_attrs(func))\n def inner(*args, **kwargs):\n return func(*args, **kwargs)\n\n return ... | [] | [] | [] | 4 | from django_codemod.visitors.decorators import (
AvailableAttrsTransformer,
ContextDecoratorTransformer,
)
from tests.visitors.base import BaseVisitorTest
class TestContextDecoratorTransformer(BaseVisitorTest):
transformer = ContextDecoratorTransformer
def test_simple_substitution(self) -> None:
... | null |
v0 | [
"int"
] | Any | def v0(v1: int):
v2 = int(str(v1)[0])
v3 = False
v4 = False
for v5 in str(v1):
if int(v5) > v2:
v3 = True
if int(v5) < v2:
v4 = True
v2 = int(v5)
return (v3 and v4) is True | [] | [] | [] | 11 |
def is_bouncy(num: int):
prevnum = int(str(num)[0])
inc = False
dec = False
for c in str(num):
if int(c) > prevnum:
inc = True
if int(c) < prevnum:
dec = True
prevnum = int(c)
return (inc and dec) is True
def main():
criteria = 99
total = 0
... | null |
v0 | [
"np.ndarray"
] | np.ndarray | def v0(v1: np.ndarray) -> np.ndarray:
(v2, v3) = v1.shape[:2]
v4 = max(v2, v3)
v5 = min(v2, v3)
v6 = np.array([(0, 0), (0, 0)])
v7 = np.argmin(v1.shape[:2])
v8 = (v4 - v5) // 2
v6[v7] = np.array((v8, v8))
if len(v1.shape) != 2:
v6 = v6.tolist()
v6.append((0, 0))
v... | [] | [
"numpy"
] | [
"import numpy as np"
] | 14 | import cv2
import numpy as np
def pad_image(image: np.ndarray) -> np.ndarray:
"""Pad image to make it a square image
Args:
image (np.ndarray): Absolute path of image file
Returns:
np.ndarray: padded image
"""
ht, wt = image.shape[:2]
final_shape = max(ht,wt)
small_shape = ... | null |
v10 | [
"str"
] | (np.ndarray, tuple, tuple) | def v10(v11: str) -> (np.ndarray, tuple, tuple):
v12 = cv2.cvtColor(cv2.imread(v11), cv2.COLOR_BGR2RGB)
v13 = v12.shape
v12 = v0(v12)
v14 = v12.shape
return (v12, v13, v14) | [
{
"name": "v0",
"input_types": [
"np.ndarray"
],
"output_type": "np.ndarray",
"code": "def v0(v1: np.ndarray) -> np.ndarray:\n (v2, v3) = v1.shape[:2]\n v4 = max(v2, v3)\n v5 = min(v2, v3)\n v6 = np.array([(0, 0), (0, 0)])\n v7 = np.argmin(v1.shape[:2])\n v8 = (v4 - v5) /... | [
"cv2",
"numpy"
] | [
"import cv2",
"import numpy as np"
] | 6 | import cv2
import numpy as np
def pad_image(image: np.ndarray) -> np.ndarray:
"""Pad image to make it a square image
Args:
image (np.ndarray): Absolute path of image file
Returns:
np.ndarray: padded image
"""
ht, wt = image.shape[:2]
final_shape = max(ht,wt)
small_shape = ... | null |
v0 | [
"np.ndarray",
"tuple"
] | np.ndarray | def v0(v1: np.ndarray, v2: tuple) -> np.ndarray:
(v3, v4) = v2[:2]
v5 = min(v3, v4)
v6 = max(v3, v4)
v7 = int((v6 - v5) / 2)
if v3 == v6:
v8 = 0
elif v4 == v6:
v8 = 1
if len(v1.shape) == 3:
v1[:, :, v8] += v7
else:
v1[:, v8] += v7
return v1 | [] | [] | [] | 14 | import cv2
import numpy as np
def pad_image(image: np.ndarray) -> np.ndarray:
"""Pad image to make it a square image
Args:
image (np.ndarray): Absolute path of image file
Returns:
np.ndarray: padded image
"""
ht, wt = image.shape[:2]
final_shape = max(ht,wt)
small_shape = ... | null |
v0 | [
"str"
] | Optional[dict] | def v0(self, v1: str) -> Optional[dict]:
(v2, *v3) = v1.split('.')
return self._get_tag_info(v2, v3) | [] | [] | [] | 3 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2021 Ian Ottoway <ian@ottoway.dev>
# Copyright (c) 2014 Agostino Ruscito <ruscito@gmail.com>
#
# 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 withou... | null |
v0 | [
"'CovergroupModel'"
] | bool | def v0(self, v1: 'CovergroupModel') -> bool:
v2 = True
v2 &= self.name == v1.name
if len(self.coverpoint_l) == len(v1.coverpoint_l):
for v3 in range(len(self.coverpoint_l)):
v2 &= self.coverpoint_l[v3].equals(v1.coverpoint_l[v3])
else:
v2 = False
if len(self.cross_l) == l... | [] | [] | [] | 14 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not ... | null |
v0 | [] | None | def v0(self) -> None:
v1: List[ROI] = self._load_unset_rois()
if len(v1) == 0:
return
self._show_roi_settings(v1)
self._set_priorities(v1)
self._show_roi_settings(v1)
self._save_changes(v1) | [] | [] | [] | 8 | """
This module can be used to set the priority for the ROI's that are stored in the database
"""
from typing import List
import colorama
from logic.logic import Logic
from logic.entities.roi import ROI
class ROIPrioritySetter:
"""
This class changes the priorities of the ROI's
"""
def __init__(se... | null |
v0 | [
"Union[bytes, str]"
] | bytes | def v0(v1: Union[bytes, str]) -> bytes:
if isinstance(v1, str):
v1 = v1.encode('utf-8')
v1 = v1.replace(b'&', b'&').replace(b'<', b'<').replace(b'>', b'>')
return v1 | [] | [] | [] | 5 | # -*- test-case-name: twisted.web.test.test_flatten,twisted.web.test.test_template -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Context-free flattener/serializer for rendering Python objects, possibly
complex or arbitrarily nested, as strings.
"""
from io import BytesIO
from sys i... | null |
v0 | [
"Union[bytes, str]"
] | bytes | def v0(v1: Union[bytes, str]) -> bytes:
if isinstance(v1, str):
v2 = v1.encode('utf-8')
else:
v2 = v1
return v2 | [] | [] | [] | 6 | """
Knowing the difference between bytes and str
there are two types that represent sequences of character data: bytes and str.
Instances of bytes contain raw, unsigned 8-bit values (often displayed in the
ASCII encoding). Instances of str contain Unicode code points that represent
... | null |
v4 | [
"Callable[[bytes], object]"
] | Callable[[bytes], None] | def v4(v5: Callable[[bytes], object]) -> Callable[[bytes], None]:
def v6(v7: bytes) -> None:
v5(v2(v7).replace(b'"', b'"'))
return v6 | [
{
"name": "v0",
"input_types": [
"bytes"
],
"output_type": "None",
"code": "def v0(v1: bytes) -> None:\n write(escapeForContent(v1).replace(b'\"', b'"'))",
"dependencies": [
"v2"
]
},
{
"name": "v2",
"input_types": [
"Union[bytes, str]"
],
"o... | [] | [] | 5 | # -*- test-case-name: twisted.web.test.test_flatten,twisted.web.test.test_template -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Context-free flattener/serializer for rendering Python objects, possibly
complex or arbitrarily nested, as strings.
"""
from io import BytesIO
from sys i... | null |
v0 | [
"Union[bytes, str]"
] | bytes | def v0(v1: Union[bytes, str]) -> bytes:
if isinstance(v1, str):
v1 = v1.encode('utf-8')
return v1.replace(b']]>', b']]]]><![CDATA[>') | [] | [] | [] | 4 | # -*- test-case-name: twisted.web.test.test_flatten,twisted.web.test.test_template -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Context-free flattener/serializer for rendering Python objects, possibly
complex or arbitrarily nested, as strings.
"""
from io import BytesIO
from sys i... | null |
v0 | [
"Union[bytes, str]"
] | bytes | def v0(v1: Union[bytes, str]) -> bytes:
if isinstance(v1, str):
v1 = v1.encode('utf-8')
v1 = v1.replace(b'--', b'- - ').replace(b'>', b'>')
if v1 and v1[-1:] == b'-':
v1 += b' '
return v1 | [] | [] | [] | 7 | # -*- test-case-name: twisted.web.test.test_flatten,twisted.web.test.test_template -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Context-free flattener/serializer for rendering Python objects, possibly
complex or arbitrarily nested, as strings.
"""
from io import BytesIO
from sys i... | null |
v0 | [
"ndarray",
"int"
] | ndarray | def v0(v1: ndarray, v2: int) -> ndarray:
v3 = zeros(v2, dtype=int)
for v4 in asarray(v1, dtype=int64):
v3[v4] += 1
return v3 | [] | [
"numpy"
] | [
"from numpy import array, asarray, block, complex128, diag, eye, int64, ndarray, power, sqrt, transpose, zeros, zeros_like, square, flip, pi, ones, exp",
"from numpy.linalg import svd",
"from numpy.random import rand"
] | 5 | __author__ = "Tomasz Rybotycki"
"""
This script contains various auxiliary methods useful for boson sampling
experiments.
TODO TR: Consider making this file a package along with exact distribution
calculator.
"""
import itertools
from typing import List, Optional, Sequence, Tuple, Set... | null |
v0 | [
"Any",
"Any"
] | None | async def v0(self, v1, v2) -> None:
if v2:
self.obj[v1] = v2 | [] | [] | [] | 3 | """Fixtures and configuration for PyTest."""
# pylint: disable=invalid-name,redefined-builtin,unused-argument,comparison-with-callable
import os
from pathlib import Path
from typing import TYPE_CHECKING
import pytest
from fastapi.testclient import TestClient
if TYPE_CHECKING:
from typing import Dict, List
class... | null |
v0 | [] | typing.List[str] | def v0(self) -> typing.List[str]:
if self.info.is_windows() or self.info.is_cygwin() or self.info.is_darwin():
return []
return ['-fPIC'] | [] | [] | [] | 4 | # Copyright 2019 The meson development team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | null |
v0 | [
"str"
] | typing.List[str] | def v0(self, v1: str) -> typing.List[str]:
if not isinstance(v1, str):
raise RuntimeError('Module definitions file should be str')
if self.info.is_windows() or self.info.is_cygwin():
return [v1]
return [] | [] | [] | [] | 6 | # Copyright 2019 The meson development team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | null |
v0 | [
"T.List[str]",
"str"
] | T.List[str] | def v0(self, v1: T.List[str], v2: str) -> T.List[str]:
for (v3, v4) in enumerate(v1):
if v4[:2] == '-I' or v4[:2] == '/I':
v1[v3] = v4[:2] + os.path.normpath(os.path.join(v2, v4[2:]))
elif v4[:9] == '/LIBPATH:':
v1[v3] = v4[:9] + os.path.normpath(os.path.join(v2, v4[9:]))
... | [] | [
"os"
] | [
"import os"
] | 7 | # Copyright 2019 The meson development team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.