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 | [] | Iterator['Module'] | def v0(self) -> Iterator['Module']:
for (v1, v2) in self.named_children():
yield v2 | [] | [] | [] | 3 | from collections import OrderedDict, namedtuple
import itertools
import warnings
import functools
import torch
from ..parameter import Parameter
import torch.utils.hooks as hooks
from torch import Tensor, device, dtype
from typing import Union, Tuple, Any, Callable, Iterator, Set, Optional, overload, TypeVar, Mapping... | null |
v0 | [] | Iterator[Tuple[str, 'Module']] | def v0(self) -> Iterator[Tuple[str, 'Module']]:
v1 = set()
for (v2, v3) in self._modules.items():
if v3 is not None and v3 not in v1:
v1.add(v3)
yield (v2, v3) | [] | [] | [] | 6 | from collections import OrderedDict, namedtuple
import itertools
import warnings
import functools
import torch
from ..parameter import Parameter
import torch.utils.hooks as hooks
from torch import Tensor, device, dtype
from typing import Union, Tuple, Any, Callable, Iterator, Set, Optional, overload, TypeVar, Mapping... | null |
v0 | [
"Optional[Set['Module']]",
"str",
"bool"
] | Any | def v0(self, v1: Optional[Set['Module']]=None, v2: str='', v3: bool=True):
if v1 is None:
v1 = set()
if self not in v1:
if v3:
v1.add(self)
yield (v2, self)
for (v4, v5) in self._modules.items():
if v5 is None:
continue
v6 = v2 ... | [] | [] | [] | 13 | from collections import OrderedDict, namedtuple
import itertools
import warnings
import functools
import torch
from ..parameter import Parameter
import torch.utils.hooks as hooks
from torch import Tensor, device, dtype
from typing import Union, Tuple, Any, Callable, Iterator, Set, Optional, overload, TypeVar, Mapping... | null |
v1 | [
"bool"
] | v0 | def v1(self: v0, v2: bool=True) -> v0:
if not isinstance(v2, bool):
raise ValueError('training mode is expected to be boolean')
self.training = v2
for v3 in self.children():
v3.train(v2)
return self | [] | [] | [] | 7 | from collections import OrderedDict, namedtuple
import itertools
import warnings
import functools
import torch
from ..parameter import Parameter
import torch.utils.hooks as hooks
from torch import Tensor, device, dtype
from typing import Union, Tuple, Any, Callable, Iterator, Set, Optional, overload, TypeVar, Mapping... | [
"v0 = TypeVar('T', bound='Module')"
] |
v1 | [
"bool"
] | v0 | def v1(self: v0, v2: bool=True) -> v0:
for v3 in self.parameters():
v3.requires_grad_(v2)
return self | [] | [] | [] | 4 | from collections import OrderedDict, namedtuple
import itertools
import warnings
import functools
import torch
from ..parameter import Parameter
import torch.utils.hooks as hooks
from torch import Tensor, device, dtype
from typing import Union, Tuple, Any, Callable, Iterator, Set, Optional, overload, TypeVar, Mapping... | [
"v0 = TypeVar('T', bound='Module')"
] |
v0 | [
"bool"
] | None | def v0(self, v1: bool=False) -> None:
if getattr(self, '_is_replica', False):
warnings.warn("Calling .zero_grad() from a module created with nn.DataParallel() has no effect. The parameters are copied (in a differentiable manner) from the original module. This means they are not leaf nodes in autograd and so... | [] | [
"warnings"
] | [
"import warnings"
] | 13 | from collections import OrderedDict, namedtuple
import itertools
import warnings
import functools
import torch
from ..parameter import Parameter
import torch.utils.hooks as hooks
from torch import Tensor, device, dtype
from typing import Union, Tuple, Any, Callable, Iterator, Set, Optional, overload, TypeVar, Mapping... | null |
v0 | [
"Dict"
] | Dict | def v0(v1: Dict) -> Dict:
v2 = v1.get('table_name')
v3 = v1.get('schema')
v4 = v1.get('cluster')
v5 = v1.get('database')
return {'name': v2, 'schema_name': v3, 'cluster': v4, 'database': v5, 'description': v1.get('table_description'), 'key': '{0}://{1}.{2}/{3}'.format(v5, v4, v3, v2), 'type': 'table... | [] | [] | [] | 6 | import logging
from http import HTTPStatus
from typing import Any, Dict
from flask import Response, jsonify, make_response, request
from flask import current_app as app
from flask.blueprints import Blueprint
from amundsen_application.log.action_log import action_logging
from amundsen_application.models.user import ... | null |
v0 | [
"str"
] | Any | def v0(self, v1: str):
assert isinstance(v1, str), "Wrong data type for param 'mode'."
self.mode = v1 | [] | [] | [] | 3 | from sklearn.linear_model import SGDRegressor, SGDClassifier
from collections import Iterable
from utils.dbms_utils import DBMSUtils
class SGDModelSQL(object):
"""
This class implements the SQL wrapper for a Sklearn's SGDRegressor/Classifier object.
"""
def __init__(self):
self.dbms = None
... | null |
v0 | [
"Any",
"Any",
"Any",
"Any"
] | str | def v0(v1, v2=False, v3='{:0.2f}', v4=True) -> str:
v5 = str(fractions.Fraction(v1).limit_denominator()).split('/')
if not v2:
if len(v5) == 2:
if not v2:
v6 = str('\\frac{%d}{%d}' % (abs(int(v5[0])), abs(int(v5[1]))))
if v1 < 0:
v6 = '-' +... | [] | [
"fractions"
] | [
"import fractions"
] | 20 | __version__ = '1.0'
__all__ = ['formatPoly', 'latex_matrix', '__version__']
__author__ = u'Rahul Gupta'
__license__ = 'MIT'
__copyright__ = 'Copyright 2021 Rahul Gupta'
# Source for numpyrett
# Some code is inspired from StackExchange , namely
# https://stackoverflow.com/questions/3862310/
# https://stackoverflow.co... | null |
v0 | [
"Any",
"Any"
] | array | def v0(self, v1, v2=13627678) -> array:
v3 = array('b', '.'.encode('ascii') * v2)
with open(v1, 'r') as v4:
v5 = 0
for v6 in v4:
v6 = v6.rstrip().split('\t')
if float(v6[4]) > 0.5:
v3[v5] = ord(self.alphabet[v6[3]])
v5 += 1
return v3 | [] | [
"array"
] | [
"from array import array"
] | 10 | #!/usr/bin/env python3
import argparse
import contextlib
import sys
from array import array
from typing import TextIO
import regex as re
@contextlib.contextmanager
def smart_open(filename: str = None) -> TextIO:
# along lines of https://stackoverflow.com/questions/17602878/
if filename and filename != '-':
... | null |
v0 | [
"str"
] | List[str] | def v0(v1: str) -> List[str]:
with open(v1, 'r', encoding='utf-8') as v2:
v3 = v2.readlines()
return v3 | [] | [] | [] | 4 | import datetime, json, re, string, random
from typing import List, Dict, NoReturn, Any
LEVEL = {
1: '【success】',
2: '【warning】',
3: '【error】',
}
def out_infos(info: str, level: int=None) -> str:
"""正常提示信息"""
d = datetime.datetime.now()
if level:
l_info = LEVEL[level]
else:
... | null |
v0 | [
"LinearOperator",
"int",
"bool"
] | Tuple[ndarray, ndarray] | def v0(v1: LinearOperator, v2: int, v3: bool=False) -> Tuple[ndarray, ndarray]:
(v4, v5) = (zeros(v2), zeros(v2 - 1))
v6 = v1.shape[1]
(v7, v8) = (None, None)
for v9 in range(v2):
if v9 == 0:
v7 = randn(v6)
v7 /= norm(v7)
v10 = v1 @ v7
else:
... | [] | [
"numpy",
"scipy"
] | [
"from numpy import exp, inner, linspace, log, ndarray, pi, sqrt, zeros, zeros_like",
"from numpy.linalg import norm",
"from numpy.random import randn",
"from scipy.linalg import eigh, eigh_tridiagonal",
"from scipy.sparse import diags",
"from scipy.sparse.linalg import LinearOperator, eigsh"
] | 25 | """Spectral analysis methods for SciPy linear operators."""
from typing import Tuple
from numpy import exp, inner, linspace, log, ndarray, pi, sqrt, zeros, zeros_like
from numpy.linalg import norm
from numpy.random import randn
from scipy.linalg import eigh, eigh_tridiagonal
from scipy.sparse import diags
from scipy.... | null |
v0 | [
"LinearOperator",
"float"
] | Tuple[float, float] | def v0(v1: LinearOperator, v2: float=0.01) -> Tuple[float, float]:
(v3,) = eigsh(v1, k=1, which='LM', tol=v2, return_eigenvectors=False)
(v4,) = eigsh(v1, k=1, which='SM', tol=v2, return_eigenvectors=False)
return (abs(v4), abs(v3)) | [] | [
"scipy"
] | [
"from scipy.linalg import eigh, eigh_tridiagonal",
"from scipy.sparse import diags",
"from scipy.sparse.linalg import LinearOperator, eigsh"
] | 4 | """Spectral analysis methods for SciPy linear operators."""
from typing import Tuple
from numpy import exp, inner, linspace, log, ndarray, pi, sqrt, zeros, zeros_like
from numpy.linalg import norm
from numpy.random import randn
from scipy.linalg import eigh, eigh_tridiagonal
from scipy.sparse import diags
from scipy.... | null |
v24 | [
"LinearOperator",
"int",
"int",
"int",
"float",
"Tuple[float, float]",
"float",
"float"
] | Tuple[ndarray, ndarray] | def v24(v25: LinearOperator, v26: int, v27: int=1024, v28: int=1, v29: float=3.0, v30: Tuple[float, float]=None, v31: float=0.05, v32: float=0.01) -> Tuple[ndarray, ndarray]:
if v30 is None:
v30 = v4(v25, tol=v32)
(v33, v34) = v30
v35 = v34 - v33
v36 = v31 * v35
(v33, v34) = (v33 - v36, v34 ... | [
{
"name": "v0",
"input_types": [
"ndarray",
"ndarray",
"float"
],
"output_type": "ndarray",
"code": "def v0(v1: ndarray, v2: ndarray, v3: float) -> ndarray:\n return exp(-0.5 * ((v1 - v2) / v3) ** 2) / (v3 * sqrt(2 * pi))",
"dependencies": []
},
{
"name": "v4",
... | [
"numpy",
"scipy"
] | [
"from numpy import exp, inner, linspace, log, ndarray, pi, sqrt, zeros, zeros_like",
"from numpy.linalg import norm",
"from numpy.random import randn",
"from scipy.linalg import eigh, eigh_tridiagonal",
"from scipy.sparse import diags",
"from scipy.sparse.linalg import LinearOperator, eigsh"
] | 21 | """Spectral analysis methods for SciPy linear operators."""
from typing import Tuple
from numpy import exp, inner, linspace, log, ndarray, pi, sqrt, zeros, zeros_like
from numpy.linalg import norm
from numpy.random import randn
from scipy.linalg import eigh, eigh_tridiagonal
from scipy.sparse import diags
from scipy.... | null |
v24 | [
"LinearOperator",
"int",
"int",
"int",
"float",
"Tuple[float, float]",
"float",
"float",
"float"
] | Tuple[ndarray, ndarray] | def v24(v25: LinearOperator, v26: int, v27: int=1024, v28: int=1, v29: float=1.04, v30: Tuple[float, float]=None, v31: float=0.05, v32: float=0.01, v33: float=1e-05) -> Tuple[ndarray, ndarray]:
if v30 is None:
v30 = v4(v25, tol=v32)
(v34, v35) = (log(boundary + v33) for v36 in v30)
v37 = v35 - v34
... | [
{
"name": "v0",
"input_types": [
"ndarray",
"ndarray",
"float"
],
"output_type": "ndarray",
"code": "def v0(v1: ndarray, v2: ndarray, v3: float) -> ndarray:\n return exp(-0.5 * ((v1 - v2) / v3) ** 2) / (v3 * sqrt(2 * pi))",
"dependencies": []
},
{
"name": "v4",
... | [
"numpy",
"scipy"
] | [
"from numpy import exp, inner, linspace, log, ndarray, pi, sqrt, zeros, zeros_like",
"from numpy.linalg import norm",
"from numpy.random import randn",
"from scipy.linalg import eigh, eigh_tridiagonal",
"from scipy.sparse import diags",
"from scipy.sparse.linalg import LinearOperator, eigsh"
] | 24 | """Spectral analysis methods for SciPy linear operators."""
from typing import Tuple
from numpy import exp, inner, linspace, log, ndarray, pi, sqrt, zeros, zeros_like
from numpy.linalg import norm
from numpy.random import randn
from scipy.linalg import eigh, eigh_tridiagonal
from scipy.sparse import diags
from scipy.... | null |
v0 | [] | None | def v0(self) -> None:
for v1 in self._connected_brokers:
v1.close()
self._connected_brokers = list() | [] | [] | [] | 4 | from time import sleep
from typing import Dict, TypeVar, Any, Set, Union, Optional, Type, List, NamedTuple, Callable
from uuid import uuid4
from unipipeline.errors.uni_payload_error import UniPayloadSerializationError
from unipipeline.errors.uni_work_flow_error import UniWorkFlowError
from unipipeline.answer.uni_answe... | null |
v0 | [
"Any"
] | (bytes, int) | def v0(self, v1) -> (bytes, int):
(v2, v3) = librosa.load(v1, sr=self.sample_rate)
return (v2, v3) | [] | [
"librosa"
] | [
"import librosa"
] | 3 | import logging
from typing import List, Optional
import torch
import librosa
import numpy as np
import scipy.signal
import sonosco.common.audio_tools as audio_tools
import sonosco.common.utils as utils
import sonosco.common.noise_makers as noise_makers
windows = {'hamming': scipy.signal.hamming, 'hann': scipy.signal.... | null |
v0 | [
"str",
"bool"
] | torch.FloatTensor | def v0(self, v1: str, v2: bool=False) -> torch.FloatTensor:
(v3, v4) = self.retrieve_file(v1)
if v2:
return v3
v5 = self.parse_audio(v3, v4)
return v5 | [] | [] | [] | 6 | import logging
from typing import List, Optional
import torch
import librosa
import numpy as np
import scipy.signal
import sonosco.common.audio_tools as audio_tools
import sonosco.common.utils as utils
import sonosco.common.noise_makers as noise_makers
windows = {'hamming': scipy.signal.hamming, 'hann': scipy.signal.... | null |
v0 | [
"np.ndarray",
"int"
] | torch.FloatTensor | def v0(self, v1: np.ndarray, v2: int) -> torch.FloatTensor:
if v2 != self.sample_rate:
raise ValueError(f'The stated sample rate {self.sample_rate} and the factual rate {v2} differ!')
if self.augment:
v1 = self.augment_audio(v1)
v3 = librosa.stft(v1, n_fft=self.window_size_samples, hop_lengt... | [] | [
"librosa",
"numpy",
"torch"
] | [
"import torch",
"import librosa",
"import numpy as np"
] | 15 | import logging
from typing import List, Optional
import torch
import librosa
import numpy as np
import scipy.signal
import sonosco.common.audio_tools as audio_tools
import sonosco.common.utils as utils
import sonosco.common.noise_makers as noise_makers
windows = {'hamming': scipy.signal.hamming, 'hann': scipy.signal.... | null |
v0 | [
"str"
] | (np.ndarray, torch.IntTensor) | def v0(self, v1: str) -> (np.ndarray, torch.IntTensor):
v2 = self.parse_audio_from_file(v1)
v2 = v2.view(1, v2.size(0), v2.size(1)).transpose(1, 2)
v3 = torch.IntTensor([v2.shape[1]]).int()
return (v2, v3) | [] | [
"torch"
] | [
"import torch"
] | 5 | import logging
from typing import List, Optional
import torch
import librosa
import numpy as np
import scipy.signal
import sonosco.common.audio_tools as audio_tools
import sonosco.common.utils as utils
import sonosco.common.noise_makers as noise_makers
windows = {'hamming': scipy.signal.hamming, 'hann': scipy.signal.... | null |
v0 | [
"int"
] | bool | def v0(v1: int) -> bool:
v2 = list(map(int, list(str(v1))))
v3 = int(''.join(list(map(str, v2[:-1]))))
v4 = int(v2[-1])
return (v3 - v4 * 2) % 7 == 0 | [] | [] | [] | 5 | def divisibility_by_3(number: int) -> bool:
"""
:type number: int
"""
return sum(list(map(int, list(str(number))))) % 3 == 0 # if true then divisble
def divisibility_by_5(number: int) -> bool:
"""
:type number: int
"""
return list(map(int, list(str(number))))[-1] == 5 # if true the... | null |
v0 | [
"str"
] | Tuple[int] | def v0(v1: str) -> Tuple[int]:
print('Attempting to load saved hyperparameters from: ' + v1)
v2 = torch.load(v1)
return (v2['embedding_dim'], v2['char_embedding_dim'], v2['hidden_dim'], v2['char_hidden_dim'], v2['use_bert_cased'], v2['use_bert_uncased'], v2['use_bert_large']) | [] | [
"torch"
] | [
"import torch",
"from torch.optim.adam import Adam"
] | 4 | #Code for training the model
# WRITTEN BY:
# John Torr (john.torr@cantab.net)
#standard library imports
import os
from numpy import float64
from typing import DefaultDict, Union, Tuple, Optional, List
from collections import defaultdict
#third party imports
import torch
from torch.optim.adam import Adam
from torch... | null |
v0 | [
"str"
] | int | def v0(self, v1: str) -> int:
(v2, v3) = (0, 0)
v4 = 0
for v5 in v1:
if v5 == 'L':
v2 += 1
elif v5 == 'R':
v3 += 1
if v2 == v3:
v4 += 1
(v2, v3) = (0, 0)
return v4 | [] | [] | [] | 12 | class Solution:
"""
Time Complexity: O(N)
Space Complexity: O(1)
"""
def balanced_string_split(self, s: str) -> int:
# initialize variables
L_count, R_count = 0, 0
balanced_substring_count = 0
# parse the string
for char in s:
# update the numbe... | null |
v0 | [
"str",
"str"
] | Any | def v0(self, v1: str, v2: str):
self.driver.get(f"{os.getenv('SITE')}/products/{v1}")
self.by_css_selector('body')
assert v2 in self.driver.title | [] | [
"os"
] | [
"import os"
] | 4 | import os
from selenium.webdriver.common.by import By
from auto.fenrir import CorePage
import typing
class ProductPage(CorePage):
"""
/
"""
BREADCRUMBS = 'nav[aria-label="Breadcrumbs"]'
IMAGES = ""
def __init__(self, driver):
super().__init__(driver)
def go_to_product_page(self... | null |
v0 | [] | typing.List | def v0(self) -> typing.List:
v1 = self.by_css_selector(self.BREADCRUMBS)
v2 = v1.driver.find_elements("//nav[aria-label='Breadcrumbs']//li//a")
v3 = []
for v4 in v2:
v3.append(v4.text)
return v3 | [] | [] | [] | 7 | import os
from selenium.webdriver.common.by import By
from auto.fenrir import CorePage
import typing
class ProductPage(CorePage):
"""
/
"""
BREADCRUMBS = 'nav[aria-label="Breadcrumbs"]'
IMAGES = ""
def __init__(self, driver):
super().__init__(driver)
def go_to_product_page(self... | null |
v0 | [
"Any",
"Any",
"Any",
"tuple",
"Any"
] | Any | def v0(v1, v2, v3, v4: tuple=(0, 0, 255), v5=0):
v6 = v1.copy()
cv2.floodFill(v6, None, (v2, v3), v4, (v5, v5, v5), (v5, v5, v5), cv2.FLOODFILL_FIXED_RANGE)
return v6 | [] | [
"cv2"
] | [
"import cv2"
] | 4 | import gc
import math
import os
import re
import sys
import time
import cv2
from numpy import array, zeros, uint8, float32
from PyQt5.QtCore import QPoint, QRectF, QMimeData
from PyQt5.QtCore import QRect, Qt, pyqtSignal, QStandardPaths, QTimer, QSettings, QUrl
from PyQt5.QtGui import QCursor, QBrush
from PyQt5.QtGui ... | null |
v0 | [
"int"
] | float | def v0(self, v1: int) -> float:
v2 = v1 - 0.5
return math.exp(-(v2 * v2) / self._split_coeff) | [] | [
"math"
] | [
"import math"
] | 3 | import abc
import math
from typing import Callable, Tuple, Any
from hues import huestr
from amino import Either, List, L, Boolean, _, __, Maybe, Map, Eval, Right, Left
from amino.regex import Regex
from amino.lazy import lazy
from amino.logging import indent
from ribosome.nvim import NvimFacade
from ribosome.util.ca... | null |
v0 | [] | str | def v0(self) -> str:
v1 = hashlib.md5()
for v2 in self.instructions.values():
v1.update(v2.rev_bytestring.encode('utf-8'))
return v1.hexdigest() | [] | [
"hashlib"
] | [
"import hashlib"
] | 5 | # ------------------------------------------------------------------------------
# CodeHawk Binary Analyzer
# Author: Henny Sipma
# ------------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2021-2022 Aarno Labs LLC
#
# Permission is hereby granted, free of ... | null |
v4 | [
"clusterlib.ClusterLib"
] | dict | def v4(v5: clusterlib.ClusterLib) -> dict:
v6 = v0(v5)
if not v6:
return {}
v7: dict = json.loads(v6)
return v7 | [
{
"name": "v0",
"input_types": [
"clusterlib.ClusterLib"
],
"output_type": "str",
"code": "def v0(v1: clusterlib.ClusterLib) -> str:\n v2 = ' '.join(['cardano-cli', 'query', 'ledger-state', *v1.magic_args, f'--{v1.protocol}-mode'])\n v3 = f\"\"\"{v2} | jq -n --stream -c 'fromstream(i... | [
"json"
] | [
"import json"
] | 6 | import itertools
import json
import logging
import time
from pathlib import Path
from typing import Any
from typing import List
from typing import NamedTuple
from typing import Optional
from typing import Union
import cbor2
from cardano_clusterlib import clusterlib
from cardano_node_tests.utils import helpers
from ca... | null |
v0 | [
"Union[List[clusterlib.UTXOData], List[clusterlib.TxOut]]",
"str"
] | int | def v0(v1: Union[List[clusterlib.UTXOData], List[clusterlib.TxOut]], v2: str=clusterlib.DEFAULT_COIN) -> int:
v3 = [r.amount for v4 in v1 if v4.coin == v2]
v5 = sum(v3)
return v5 | [] | [] | [] | 4 | import itertools
import json
import logging
import time
from pathlib import Path
from typing import Any
from typing import List
from typing import NamedTuple
from typing import Optional
from typing import Union
import cbor2
from cardano_clusterlib import clusterlib
from cardano_node_tests.utils import helpers
from ca... | null |
v0 | [] | int | async def v0(self) -> int:
await self._count_stable.wait()
return self._last_count | [] | [] | [] | 3 | """Baseclass for ball device ball counters.
The duty of this device is to maintain the current ball count of the device.
"""
import asyncio
from typing import List
from mpf.core.utility_functions import Util
MYPY = False
if MYPY: # pragma: no cover
from mpf.devices.ball_device.ball_device import BallDevice #... | null |
v2 | [
"v0"
] | None | def v2(self, v3: v0) -> None:
for v4 in self._activity_queues:
v4.put_nowait(v3) | [] | [] | [] | 3 | """Baseclass for ball device ball counters.
The duty of this device is to maintain the current ball count of the device.
"""
import asyncio
from typing import List
from mpf.core.utility_functions import Util
MYPY = False
if MYPY: # pragma: no cover
from mpf.devices.ball_device.ball_device import BallDevice #... | [
"class v0:\n v1 = []"
] |
v0 | [
"int"
] | Any | async def v0(self, v1: int):
while True:
v2 = await self.count_balls()
if v2 != v1:
return v2
await self.wait_for_ball_activity() | [] | [] | [] | 6 | """Baseclass for ball device ball counters.
The duty of this device is to maintain the current ball count of the device.
"""
import asyncio
from typing import List
from mpf.core.utility_functions import Util
MYPY = False
if MYPY: # pragma: no cover
from mpf.devices.ball_device.ball_device import BallDevice #... | null |
v0 | [
"str"
] | np.ndarray | def v0(v1: str) -> np.ndarray:
with open(v1, 'rb') as v2:
v3 = None
v4 = None
v5 = None
v6 = None
v7 = None
v8 = v2.readline().rstrip()
if v8 == b'PF':
v3 = True
elif v8 == b'Pf':
v3 = False
else:
raise Value... | [] | [
"numpy",
"re"
] | [
"import re",
"import numpy as np"
] | 33 | """Functions taken and adapted from https://github.com/princeton-vl/RAFT/blob/master/core/utils/utils.py."""
# Original license below
# BSD 3-Clause License
# Copyright (c) 2020, princeton-vl
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted pr... | null |
v2 | [
"DataFrame",
"Any",
"str",
"Any",
"Optional[bool]",
"Any"
] | Any | def v2(v3: DataFrame, v4, v5: str='auto', v6='snappy', v7: Optional[bool]=None, v8=None, **v9):
if isinstance(v8, str):
v8 = [v8]
v10 = v0(v5)
return v10.write(v3, v4, compression=v6, index=v7, partition_cols=v8, **v9) | [
{
"name": "v0",
"input_types": [
"str"
],
"output_type": "'BaseImpl'",
"code": "def v0(v1: str) -> 'BaseImpl':\n if v1 == 'auto':\n v1 = get_option('io.parquet.engine')\n if v1 == 'auto':\n try:\n return PyArrowImpl()\n except ImportError:\n ... | [
"pandas"
] | [
"from pandas.compat._optional import import_optional_dependency",
"from pandas.errors import AbstractMethodError",
"from pandas import DataFrame, get_option",
"from pandas.io.common import get_filepath_or_buffer, is_gcs_url, is_s3_url"
] | 5 | """ parquet compat """
from typing import Any, Dict, Optional
from warnings import catch_warnings
from pandas.compat._optional import import_optional_dependency
from pandas.errors import AbstractMethodError
from pandas import DataFrame, get_option
from pandas.io.common import get_filepath_or_buffer, is_gcs_url, is_... | null |
v2 | [
"Any",
"str",
"Any"
] | Any | def v2(v3, v4: str='auto', v5=None, **v6):
v7 = v0(v4)
return v7.read(v3, columns=v5, **v6) | [
{
"name": "v0",
"input_types": [
"str"
],
"output_type": "'BaseImpl'",
"code": "def v0(v1: str) -> 'BaseImpl':\n if v1 == 'auto':\n v1 = get_option('io.parquet.engine')\n if v1 == 'auto':\n try:\n return PyArrowImpl()\n except ImportError:\n ... | [
"pandas"
] | [
"from pandas.compat._optional import import_optional_dependency",
"from pandas.errors import AbstractMethodError",
"from pandas import DataFrame, get_option",
"from pandas.io.common import get_filepath_or_buffer, is_gcs_url, is_s3_url"
] | 3 | """ parquet compat """
from typing import Any, Dict, Optional
from warnings import catch_warnings
from pandas.compat._optional import import_optional_dependency
from pandas.errors import AbstractMethodError
from pandas import DataFrame, get_option
from pandas.io.common import get_filepath_or_buffer, is_gcs_url, is_... | null |
v0 | [
"DataFrame",
"Any",
"Any",
"Any",
"Any"
] | Any | def v0(self, v1: DataFrame, v2, v3='snappy', v4=None, v5=None, **v6):
self.validate_dataframe(v1)
if 'partition_on' in v6 and v5 is not None:
raise ValueError('Cannot use both partition_on and partition_cols. Use partition_cols for partitioning data')
elif 'partition_on' in v6:
v5 = v6.pop('... | [] | [
"pandas",
"warnings"
] | [
"from warnings import catch_warnings",
"from pandas.compat._optional import import_optional_dependency",
"from pandas.errors import AbstractMethodError",
"from pandas import DataFrame, get_option",
"from pandas.io.common import get_filepath_or_buffer, is_gcs_url, is_s3_url"
] | 15 | """ parquet compat """
from typing import Any, Dict, Optional
from warnings import catch_warnings
from pandas.compat._optional import import_optional_dependency
from pandas.errors import AbstractMethodError
from pandas import DataFrame, get_option
from pandas.io.common import get_filepath_or_buffer, is_gcs_url, is_... | null |
v0 | [
"Module",
"Union[Tensor, Tuple[Tensor, ...]]",
"Union[Tensor, Tuple[Tensor, ...]]"
] | Any | def v0(self, v1: Module, v2: Union[Tensor, Tuple[Tensor, ...]], v3: Union[Tensor, Tuple[Tensor, ...]]):
v4 = v3 if self.use_relu_grad_output else v2
if isinstance(v4, tuple):
return tuple((F.relu(to_override_grad) for v5 in v4))
else:
return F.relu(v4) | [] | [
"torch"
] | [
"import torch",
"import torch.nn.functional as F",
"from torch import Tensor",
"from torch.nn import Module",
"from torch.utils.hooks import RemovableHandle"
] | 6 | #!/usr/bin/env python3
import warnings
from typing import Any, List, Tuple, Union
import torch
import torch.nn.functional as F
from captum._utils.common import (
_format_input,
_format_output,
_is_tuple,
_register_backward_hook,
)
from captum._utils.gradient import (
apply_gradient_requirements,
... | null |
v0 | [
"int",
"int",
"int",
"int"
] | Tuple[int, int, int, int] | def v0(v1: int, v2: int, v3: int, v4: int) -> Tuple[int, int, int, int]:
v5 = onp.gcd(v1, v2) // v4
v6 = min(v3, v5)
if v6 != v3:
warnings.warn('Batch size is reduced from requested %d to effective %d to fit the dataset.' % (v3, v6))
v7 = v6 * v4
(v8, v9) = divmod(v1, v7)
if v9:
... | [] | [
"numpy",
"warnings"
] | [
"import warnings",
"import numpy as onp"
] | 16 | # Copyright 2019 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.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | null |
v0 | [
"Path",
"Path"
] | str | def v0(v1: Path, v2: Path=None) -> str:
if v2 is not None:
v3 = v1.absolute().relative_to(v2.absolute())
else:
v3 = v1
v4 = str(v3.parent).strip('.')
v5 = str(v3.stem).lower().replace(' ', '_')
if v5 == 'index':
v6 = v4
else:
v6 = v4 + '/' + v5
if not v6.start... | [] | [] | [] | 16 | from pathlib import Path
def path_to_url(filename: Path, content_dir: Path = None) -> str:
""" Transforms a file path to an url by following some simple rules such as transforming spaces to _ and setting
all the characters to lowercase.
"""
if content_dir is not None:
rel_name = filename.absol... | null |
v2 | [
"str",
"str"
] | Any | def v2(v3: str, v4: str='ns'):
v3 = v0(v3)
return np.datetime64(v3, v4) | [
{
"name": "v0",
"input_types": [
"Any"
],
"output_type": "Any",
"code": "def v0(v1):\n if isinstance(v1, str):\n if v1.endswith('Z'):\n v1 = v1[:-1]\n elif _tz_regex.search(v1):\n v1 = v1[:-5]\n return v1",
"dependencies": []
}
] | [
"numpy"
] | [
"import numpy as np"
] | 3 | """ support numpy compatibility across versions """
import re
import numpy as np
from pandas.util.version import Version
# numpy versioning
_np_version = np.__version__
_nlv = Version(_np_version)
np_version_under1p18 = _nlv < Version("1.18")
np_version_under1p19 = _nlv < Version("1.19")
np_version_under1p20 = _nlv... | null |
v0 | [
"Union[BufferedIOBase, RawIOBase]"
] | bool | def v0(v1: Union[BufferedIOBase, RawIOBase]) -> bool:
v1.seek(0)
v2 = False
if v1.read(4) == b'PK\x03\x04':
v1.seek(30)
v2 = v1.read(54) == b'mimetypeapplication/vnd.oasis.opendocument.spreadsheet'
v1.seek(0)
return v2 | [] | [] | [] | 8 | import abc
import datetime
from io import BufferedIOBase, BytesIO, RawIOBase
import os
from textwrap import fill
from typing import Any, Mapping, Union
from pandas._config import config
from pandas._libs.parsers import STR_NA_VALUES
from pandas._typing import StorageOptions
from pandas.errors import EmptyDataError
fr... | null |
v0 | [
"Callable"
] | Any | def v0(self, v1: Callable):
self.state_changed_callback = v1
if self.wallet_state_manager is not None:
self.wallet_state_manager.set_callback(self.state_changed_callback)
self.wallet_state_manager.set_pending_callback(self._pending_tx_handler) | [] | [] | [] | 5 | import asyncio
import json
import logging
import socket
import time
import traceback
from pathlib import Path
from typing import Callable, Dict, List, Optional, Set, Tuple, Union, Any
from blspy import PrivateKey
from cannabis.consensus.block_record import BlockRecord
from cannabis.consensus.constants import Consensu... | null |
v0 | [] | None | async def v0(self) -> None:
v1 = 0
while not self._shut_down and v1 < 5:
if self.has_full_node():
await self.wallet_peers.ensure_is_closed()
if self.wallet_state_manager is not None:
self.wallet_state_manager.state_changed('add_connection')
break
... | [] | [
"asyncio"
] | [
"import asyncio"
] | 10 | import asyncio
import json
import logging
import socket
import time
import traceback
from pathlib import Path
from typing import Callable, Dict, List, Optional, Set, Tuple, Union, Any
from blspy import PrivateKey
from cannabis.consensus.block_record import BlockRecord
from cannabis.consensus.constants import Consensu... | null |
v0 | [] | None | def v0(self) -> None:
self.log.info('self.sync_event.set()')
self.sync_event.set() | [] | [] | [] | 3 | import asyncio
import json
import logging
import socket
import time
import traceback
from pathlib import Path
from typing import Callable, Dict, List, Optional, Set, Tuple, Union, Any
from blspy import PrivateKey
from cannabis.consensus.block_record import BlockRecord
from cannabis.consensus.constants import Consensu... | null |
v0 | [] | None | async def v0(self) -> None:
if self.wallet_state_manager is None:
return None
v1: Optional[BlockRecord] = self.wallet_state_manager.blockchain.get_peak()
if v1 is None:
return None
v2: List[Tuple[bytes32, HeaderBlock]] = self.wallet_state_manager.sync_store.get_potential_peaks_tuples()
... | [] | [
"asyncio"
] | [
"import asyncio"
] | 12 | import asyncio
import json
import logging
import socket
import time
import traceback
from pathlib import Path
from typing import Callable, Dict, List, Optional, Set, Tuple, Union, Any
from blspy import PrivateKey
from cannabis.consensus.block_record import BlockRecord
from cannabis.consensus.constants import Consensu... | null |
v0 | [
"bool"
] | str | def v0(self, v1: bool=False) -> str:
if not v1:
return 'ElastiCache Replication Group'
else:
return 'ElastiCache Replication Groups' | [] | [] | [] | 5 | from typing import List, Optional
from cloudrail.knowledge.context.aws.networking_config.network_configuration import NetworkConfiguration
from cloudrail.knowledge.context.aws.networking_config.network_entity import NetworkEntity
from cloudrail.knowledge.context.aws.service_name import AwsServiceName
class ElastiCac... | null |
v0 | [
"str"
] | Any | def v0(v1: str, *v2, **v3):
if 'args' in v3:
v2 = v3['args']
elif v2 is None:
v2 = []
v4 = ''
if 'prefixes' in v3:
for v5 in v3['prefixes']:
v4 += f'[{v5}] '
for v6 in v2:
v4 += f'[{v6}] '
return f'{v4}{v1}' | [] | [] | [] | 12 | import json
import os
import subprocess
import threading
from datetime import datetime, timedelta, time
from typing import List
from dayofweek import DayOfWeek, parse as parse_dayofweek, parse_today
class SettingsController:
data: {}
def __init__(self, path: str):
if not type(path) is str or os.pat... | null |
v0 | [
"str"
] | Any | def v0(v1: str):
if v1 is None:
return None
v2: List[str] = v1.split(':')
v3 = len(v2)
if v3 > 3:
return None
v4 = int(v2[0])
v5 = int(v2[1]) if v3 >= 2 else 0
v6 = int(v2[2]) if v3 == 3 else 0
return time(v4, v5, v6) | [] | [
"datetime"
] | [
"from datetime import datetime, timedelta, time"
] | 11 | import json
import os
import subprocess
import threading
from datetime import datetime, timedelta, time
from typing import List
from dayofweek import DayOfWeek, parse as parse_dayofweek, parse_today
class SettingsController:
data: {}
def __init__(self, path: str):
if not type(path) is str or os.pat... | null |
v0 | [] | List[str] | def v0(self) -> List[str]:
v1 = f'{self.apps_dir}{os.path.sep}'
v2 = []
for v3 in os.listdir(v1):
if os.path.isfile(f'{v1}{v3}') and v3.endswith('.json'):
v2.append(v3[0:len(v3) - 5])
return v2 | [] | [
"os"
] | [
"import os"
] | 7 | import json
import os
import subprocess
import threading
from datetime import datetime, timedelta, time
from typing import List
from dayofweek import DayOfWeek, parse as parse_dayofweek, parse_today
class SettingsController:
data: {}
def __init__(self, path: str):
if not type(path) is str or os.pat... | null |
v0 | [
"str",
"Any"
] | Any | def v0(self, v1: str, v2=True):
v3 = self.get_app(v1) if self.has_app(v1) else self.load_app(v1)
if (v3.in_working_time() or not v2) and v3.settings.enabled:
v3.start()
return v3 | [] | [] | [] | 5 | import json
import os
import subprocess
import threading
from datetime import datetime, timedelta, time
from typing import List
from dayofweek import DayOfWeek, parse as parse_dayofweek, parse_today
class SettingsController:
data: {}
def __init__(self, path: str):
if not type(path) is str or os.pat... | null |
v0 | [] | Tuple[bool, Optional[str]] | async def v0(self) -> Tuple[bool, Optional[str]]:
if shutil.which('ionice'):
return (True, None)
else:
return (False, "'ionice' is not installed. It will not be possible to change a process IO scheduling") | [] | [
"shutil"
] | [
"import shutil"
] | 5 | import asyncio
import os
import shutil
from abc import ABC
from io import StringIO
from typing import Optional, Tuple
from guapow.common.system import async_syscall
from guapow.common.users import is_root_user
from guapow.service.optimizer.renicer import Renicer
from guapow.service.optimizer.task.model import Task, Op... | null |
v15 | [
"Union[tf.keras.models.Model]",
"List[tf.DType]",
"List[np.ndarray]",
"List[np.ndarray]",
"List[np.ndarray]",
"Optional[List[int]]",
"bool"
] | np.ndarray | def v15(v16: Union[tf.keras.models.Model], v17: List[tf.DType], v18: List[np.ndarray], v19: List[np.ndarray], v20: List[np.ndarray], v21: Optional[List[int]], v22: bool) -> np.ndarray:
if v22:
v19 = [tf.convert_to_tensor(v19[k], dtype=v17[k]) for v23 in range(len(v17))]
v20 = [tf.convert_to_tensor(v... | [
{
"name": "v0",
"input_types": [
"Union[tf.keras.models.Model]",
"Union[List[tf.Tensor], List[np.ndarray]]",
"Union[None, tf.Tensor, np.ndarray, list]"
],
"output_type": "tf.Tensor",
"code": "def v0(v1: Union[tf.keras.models.Model], v2: Union[List[tf.Tensor], List[np.ndarray]],... | [
"numpy",
"string",
"tensorflow"
] | [
"import numpy as np",
"import string",
"import tensorflow as tf",
"from tensorflow.keras.models import Model"
] | 33 | import copy
import logging
import numpy as np
import string
import tensorflow as tf
from alibi.api.defaults import DEFAULT_DATA_INTGRAD, DEFAULT_META_INTGRAD
from alibi.utils.approximation_methods import approximation_parameters
from alibi.api.interfaces import Explainer, Explanation
from tensorflow.keras.models impor... | null |
v3 | [
"Union[tf.keras.models.Model, 'keras.models.Model']",
"Union[tf.Tensor, np.ndarray]",
"Union[None, tf.Tensor, np.ndarray, list]"
] | tf.Tensor | def v3(v4: Union[tf.keras.models.Model, 'keras.models.Model'], v5: Union[tf.Tensor, np.ndarray], v6: Union[None, tf.Tensor, np.ndarray, list]) -> tf.Tensor:
def v7(v8, v9):
if v9 is not None:
if isinstance(v8, tf.Tensor):
v8 = tf.linalg.diag_part(tf.gather(v8, v9, axis=1))
... | [
{
"name": "v0",
"input_types": [
"Any",
"Any"
],
"output_type": "Any",
"code": "def v0(v1, v2):\n if v2 is not None:\n if isinstance(v1, tf.Tensor):\n v1 = tf.linalg.diag_part(tf.gather(v1, v2, axis=1))\n else:\n raise NotImplementedError\n e... | [
"tensorflow"
] | [
"import tensorflow as tf"
] | 15 | import copy
import logging
import numpy as np
import string
import tensorflow as tf
from alibi.api.defaults import DEFAULT_DATA_INTGRAD, DEFAULT_META_INTGRAD
from alibi.utils.approximation_methods import approximation_parameters
from alibi.api.interfaces import Explainer, Explanation
from typing import Callable, TYPE... | null |
v11 | [
"Union[tf.keras.models.Model, 'keras.models.Model']",
"tf.Tensor",
"Union[None, tf.Tensor]"
] | tf.Tensor | def v11(v12: Union[tf.keras.models.Model, 'keras.models.Model'], v13: tf.Tensor, v14: Union[None, tf.Tensor]) -> tf.Tensor:
with tf.GradientTape() as v15:
v15.watch(v13)
v16 = v0(v12, v13, v14)
v17 = v15.gradient(v16, v13)
return v17 | [
{
"name": "v0",
"input_types": [
"Union[tf.keras.models.Model, 'keras.models.Model']",
"Union[tf.Tensor, np.ndarray]",
"Union[None, tf.Tensor, np.ndarray, list]"
],
"output_type": "tf.Tensor",
"code": "def v0(v1: Union[tf.keras.models.Model, 'keras.models.Model'], v2: Union[tf.... | [
"tensorflow"
] | [
"import tensorflow as tf"
] | 6 | import copy
import logging
import numpy as np
import string
import tensorflow as tf
from alibi.api.defaults import DEFAULT_DATA_INTGRAD, DEFAULT_META_INTGRAD
from alibi.utils.approximation_methods import approximation_parameters
from alibi.api.interfaces import Explainer, Explanation
from typing import Callable, TYPE... | null |
v27 | [
"Union[tf.keras.models.Model, 'keras.models.Model']",
"Union[tf.keras.layers.Layer, 'keras.layers.Layer']",
"Callable",
"tf.Tensor",
"Union[None, tf.Tensor]"
] | tf.Tensor | def v27(v28: Union[tf.keras.models.Model, 'keras.models.Model'], v29: Union[tf.keras.layers.Layer, 'keras.layers.Layer'], v30: Callable, v31: tf.Tensor, v32: Union[None, tf.Tensor]) -> tf.Tensor:
def v33(v34, v35):
"""
Make an intermediate hidden `layer` watchable by the `tape`.
After calli... | [
{
"name": "v0",
"input_types": [
"Union[tf.keras.models.Model, 'keras.models.Model']",
"Union[tf.Tensor, np.ndarray]",
"Union[None, tf.Tensor, np.ndarray, list]"
],
"output_type": "tf.Tensor",
"code": "def v0(v1: Union[tf.keras.models.Model, 'keras.models.Model'], v2: Union[tf.... | [
"tensorflow"
] | [
"import tensorflow as tf"
] | 28 | import copy
import logging
import numpy as np
import string
import tensorflow as tf
from alibi.api.defaults import DEFAULT_DATA_INTGRAD, DEFAULT_META_INTGRAD
from alibi.utils.approximation_methods import approximation_parameters
from alibi.api.interfaces import Explainer, Explanation
from typing import Callable, TYPE... | null |
v0 | [
"list",
"Union[tf.Tensor, np.ndarray]"
] | Union[tf.Tensor, np.ndarray] | def v0(v1: list, v2: Union[tf.Tensor, np.ndarray]) -> Union[tf.Tensor, np.ndarray]:
v3 = string.ascii_lowercase[1:len(v2.shape)]
if isinstance(v2, tf.Tensor):
v1 = tf.convert_to_tensor(v1)
v4 = 'a,a{}->{}'.format(v3, v3)
v5 = tf.einsum(v4, v1, v2).numpy()
elif isinstance(v2, np.ndarr... | [] | [
"numpy",
"string",
"tensorflow"
] | [
"import numpy as np",
"import string",
"import tensorflow as tf",
"from tensorflow.keras.models import Model"
] | 12 | import copy
import logging
import numpy as np
import string
import tensorflow as tf
from alibi.api.defaults import DEFAULT_DATA_INTGRAD, DEFAULT_META_INTGRAD
from alibi.utils.approximation_methods import approximation_parameters
from alibi.api.interfaces import Explainer, Explanation
from tensorflow.keras.models impor... | null |
v0 | [
"np.ndarray",
"Union[None, int, float, np.ndarray]"
] | np.ndarray | def v0(v1: np.ndarray, v2: Union[None, int, float, np.ndarray]) -> np.ndarray:
if v2 is None:
v3 = np.zeros(v1.shape).astype(v1.dtype)
elif isinstance(v2, int) or isinstance(v2, float):
v3 = np.full(v1.shape, v2).astype(v1.dtype)
elif isinstance(v2, np.ndarray):
v3 = v2.astype(v1.dty... | [] | [
"numpy"
] | [
"import numpy as np"
] | 10 | import copy
import logging
import numpy as np
import string
import tensorflow as tf
from alibi.api.defaults import DEFAULT_DATA_INTGRAD, DEFAULT_META_INTGRAD
from alibi.utils.approximation_methods import approximation_parameters
from alibi.api.interfaces import Explainer, Explanation
from typing import Callable, TYPE... | null |
v0 | [
"Union[None, int, list, np.ndarray]",
"int"
] | Union[None, List[int]] | def v0(v1: Union[None, int, list, np.ndarray], v2: int) -> Union[None, List[int]]:
if v1 is not None:
if isinstance(v1, int):
v1 = [v1 for v3 in range(v2)]
elif isinstance(v1, list) or isinstance(v1, np.ndarray):
v1 = [t.astype(int) for v4 in v1]
else:
rai... | [] | [
"numpy"
] | [
"import numpy as np"
] | 9 | import copy
import logging
import numpy as np
import string
import tensorflow as tf
from alibi.api.defaults import DEFAULT_DATA_INTGRAD, DEFAULT_META_INTGRAD
from alibi.utils.approximation_methods import approximation_parameters
from alibi.api.interfaces import Explainer, Explanation
from tensorflow.keras.models impor... | null |
v6 | [
"List[List[tf.Tensor]]",
"Union[tf.keras.Model]",
"Union[None, List[int]]",
"np.ndarray",
"int",
"int",
"List[float]",
"int"
] | Union[tf.Tensor, np.ndarray] | def v6(v7: List[List[tf.Tensor]], v8: Union[tf.keras.Model], v9: Union[None, List[int]], v10: np.ndarray, v11: int, v12: int, v13: List[float], v14: int) -> Union[tf.Tensor, np.ndarray]:
v15 = tf.concat(v7[v14], 0)
v16 = v15.shape[1:]
if isinstance(v16, tf.TensorShape):
v16 = tuple(v16.as_list())
... | [
{
"name": "v0",
"input_types": [
"list",
"Union[tf.Tensor, np.ndarray]"
],
"output_type": "Union[tf.Tensor, np.ndarray]",
"code": "def v0(v1: list, v2: Union[tf.Tensor, np.ndarray]) -> Union[tf.Tensor, np.ndarray]:\n v3 = string.ascii_lowercase[1:len(v2.shape)]\n if isinstance(... | [
"numpy",
"string",
"tensorflow"
] | [
"import numpy as np",
"import string",
"import tensorflow as tf",
"from tensorflow.keras.models import Model"
] | 11 | import copy
import logging
import numpy as np
import string
import tensorflow as tf
from alibi.api.defaults import DEFAULT_DATA_INTGRAD, DEFAULT_META_INTGRAD
from alibi.utils.approximation_methods import approximation_parameters
from alibi.api.interfaces import Explainer, Explanation
from tensorflow.keras.models impor... | null |
v0 | [
"str"
] | Any | def v0(self, v1: str):
for v2 in self._handlers:
v3 = v2.handle(v1, self._stats_manager)
self._notify_manager.process_events(v3) | [] | [] | [] | 4 | # std
from typing import Optional
# project
from src.chia_log.handlers.daily_stats.stats_manager import StatsManager
from src.chia_log.handlers.harvester_activity_handler import HarvesterActivityHandler
from src.chia_log.handlers.partial_handler import PartialHandler
from src.chia_log.handlers.block_handler import Blo... | null |
v0 | [] | List[str] | def v0(self) -> List[str]:
if self._batch_identifiers is None:
self._batch_identifiers = list(set([validation_result_identifier.batch_identifier for v1 in self.list_validation_result_identifiers()]))
return self._batch_identifiers | [] | [] | [] | 4 | import json
from copy import deepcopy
from typing import Dict, List, Union
from marshmallow import Schema, fields, post_load, pre_dump
from great_expectations.core import (
ExpectationSuiteValidationResult,
RunIdentifier,
RunIdentifierSchema,
convert_to_json_serializable,
)
from great_expectations.cor... | null |
v0 | [] | List[str] | def v0(self) -> List[str]:
if self._data_asset_names is None:
self._data_asset_names = list(set([data_asset['batch_kwargs'].get('data_asset_name') or '__none__' for v1 in self.list_data_assets_validated()]))
return self._data_asset_names | [] | [] | [] | 4 | import json
from copy import deepcopy
from typing import Dict, List, Union
from marshmallow import Schema, fields, post_load, pre_dump
from great_expectations.core import (
ExpectationSuiteValidationResult,
RunIdentifier,
RunIdentifierSchema,
convert_to_json_serializable,
)
from great_expectations.cor... | null |
v0 | [] | List[str] | def v0(self) -> List[str]:
if self._expectation_suite_names is None:
self._expectation_suite_names = list(set([validation_result_identifier.expectation_suite_identifier.expectation_suite_name for v1 in self.run_results.keys()]))
return self._expectation_suite_names | [] | [] | [] | 4 | import json
from copy import deepcopy
from typing import Dict, List, Union
from marshmallow import Schema, fields, post_load, pre_dump
from great_expectations.core import (
ExpectationSuiteValidationResult,
RunIdentifier,
RunIdentifierSchema,
convert_to_json_serializable,
)
from great_expectations.cor... | null |
v0 | [] | dict | def v0(self) -> dict:
if self._validation_results_by_validation_result_identifier is None:
self._validation_results_by_validation_result_identifier = {validation_result_identifier: run_result['validation_result'] for (v1, v2) in self.run_results.items()}
return self._validation_results_by_validation_res... | [] | [] | [] | 4 | import json
from copy import deepcopy
from typing import Dict, List, Optional, Union
from great_expectations.core.expectation_validation_result import (
ExpectationSuiteValidationResult,
)
from great_expectations.core.id_dict import BatchKwargs
from great_expectations.core.run_identifier import RunIdentifier, RunI... | null |
v0 | [] | dict | def v0(self) -> dict:
if self._validation_results_by_expectation_suite_name is None:
self._validation_results_by_expectation_suite_name = {expectation_suite_name: [run_result['validation_result'] for v1 in self.run_results.values() if v1['validation_result'].meta['expectation_suite_name'] == expectation_sui... | [] | [] | [] | 4 | import json
from copy import deepcopy
from typing import Dict, List, Optional, Union
from great_expectations.core.expectation_validation_result import (
ExpectationSuiteValidationResult,
)
from great_expectations.core.id_dict import BatchKwargs
from great_expectations.core.run_identifier import RunIdentifier, RunI... | null |
v0 | [] | dict | def v0(self) -> dict:
if self._validation_results_by_data_asset_name is None:
v1 = {}
for v2 in self.list_data_asset_names():
if v2 == '__none__':
v1[v2] = [data_asset['validation_results'] for v3 in self.list_data_assets_validated() if v3['batch_kwargs'].get('data_asset_... | [] | [] | [] | 10 | import json
from copy import deepcopy
from typing import Dict, List, Optional, Union
from great_expectations.core.expectation_validation_result import (
ExpectationSuiteValidationResult,
)
from great_expectations.core.id_dict import BatchKwargs
from great_expectations.core.run_identifier import RunIdentifier, RunI... | null |
v0 | [
"str"
] | Union[List[dict], dict] | def v0(self, v1: str=None) -> Union[List[dict], dict]:
if v1 is None:
if self._data_assets_validated is None:
self._data_assets_validated = list(self._list_data_assets_validated_by_batch_id().values())
return self._data_assets_validated
if v1 == 'batch_id':
return self._list_... | [] | [] | [] | 7 | import json
from copy import deepcopy
from typing import Dict, List, Optional, Union
from great_expectations.core.expectation_validation_result import (
ExpectationSuiteValidationResult,
)
from great_expectations.core.id_dict import BatchKwargs
from great_expectations.core.run_identifier import RunIdentifier, RunI... | null |
v0 | [] | dict | def v0(self) -> dict:
if self._statistics is None:
v1 = len(self.list_data_assets_validated())
v2 = len(self.list_validation_results())
v3 = len([validation_result for v4 in self.list_validation_results() if v4.success])
v5 = v2 - v3
v6 = v2 and v3 / v2 * 100
self._st... | [] | [] | [] | 9 | import json
from copy import deepcopy
from typing import Dict, List, Optional, Union
from great_expectations.core.expectation_validation_result import (
ExpectationSuiteValidationResult,
)
from great_expectations.core.id_dict import BatchKwargs
from great_expectations.core.run_identifier import RunIdentifier, RunI... | null |
v0 | [
"str",
"str",
"Optional[Callable[[str], Any]]"
] | List[Any] | def v0(v1: str, v2: str=',', v3: Optional[Callable[[str], Any]]=None) -> List[Any]:
v4 = v1.strip().split(v2)
v4 = map(str.strip, v4)
if v3 is not None:
v4 = map(v3, v4)
return list(v4) | [] | [] | [] | 6 | from ipaddress import ip_address
from typing import Callable, List, Optional, Any
from functools import partial
import re
def ip_range_to_list(x):
def ip_range_generator(ip1, ip2):
ip1 = int(ip_address(ip1))
ip2 = int(ip_address(ip2))
ip1, ip2 = min(ip1, ip2), max(ip1, ip2)
for i i... | null |
v11 | [] | Callable[[str], List[Any]] | def v11(*v12: Callable) -> Callable[[str], List[Any]]:
def v13(v14: str, **v15):
v16 = v0(v14)
if len(v16) != len(v12):
raise ValueError('Key & Input lists have mismatched lengths')
v16 = (f(i) for (v17, v18) in zip(v16, v12))
return list(v16)
return v13 | [
{
"name": "v0",
"input_types": [
"str",
"str",
"Optional[Callable[[str], Any]]"
],
"output_type": "List[Any]",
"code": "def v0(v1: str, v2: str=',', v3: Optional[Callable[[str], Any]]=None) -> List[Any]:\n v4 = v1.strip().split(v2)\n v4 = map(str.strip, v4)\n if v3 is ... | [] | [] | 9 | from ipaddress import ip_address
from typing import Callable, List, Optional, Any
from functools import partial
import re
def ip_range_to_list(x):
def ip_range_generator(ip1, ip2):
ip1 = int(ip_address(ip1))
ip2 = int(ip_address(ip2))
ip1, ip2 = min(ip1, ip2), max(ip1, ip2)
for i i... | null |
v0 | [
"str"
] | range | def v0(v1: str) -> range:
v1 = v1.strip()
if re.match('^\\s*\\d+\\s*-\\s*\\d+$', v1):
(v2, v3) = v1.split('-')
v2 = v2.strip()
v3 = v3.strip()
return range(int(v2), int(v3))
if re.match('^(-?\\d+)?:-?\\d+(:-?\\d+)?$', v1):
(v2, v3, *v4) = v1.split(':')
v2 = in... | [] | [
"re"
] | [
"import re"
] | 19 | from ipaddress import ip_address
from typing import Callable, List, Optional, Any
from functools import partial
import re
def ip_range_to_list(x):
def ip_range_generator(ip1, ip2):
ip1 = int(ip_address(ip1))
ip2 = int(ip_address(ip2))
ip1, ip2 = min(ip1, ip2), max(ip1, ip2)
for i i... | null |
v0 | [
"List[str]"
] | Any | def v0(self, v1: List[str]):
for v2 in self._tools.yum.find_rhel_repo_id(v1):
if not self._tools.yum.is_repo_enabled(v2):
self._tools.yum_config_manager.enable_repo(v2) | [] | [] | [] | 4 | import logging
import shutil
from pathlib import Path
from typing import List, Set
from src.command.command import Command
from src.config import Config
from src.error import PackageNotfound
from src.mode.base_mode import BaseMode
class RedHatFamilyMode(BaseMode):
"""
Used by distros based of RedHat GNU/Linu... | null |
v0 | [] | Set[str] | def v0(self) -> Set[str]:
v1 = self._cfg.dest_packages / 'repo-prereqs'
v1.mkdir(exist_ok=True, parents=True)
v2: List[str] = []
v3: List[str] = self._requirements['prereq-packages']
for v4 in v3:
v2.extend(self._tools.repoquery.query(v4, queryformat='%{ui_nevra}', arch=self._cfg.os_arch.val... | [] | [
"logging"
] | [
"import logging"
] | 12 | import logging
import shutil
from pathlib import Path
from typing import List, Set
from src.command.command import Command
from src.config import Config
from src.error import PackageNotfound
from src.mode.base_mode import BaseMode
class RedHatFamilyMode(BaseMode):
"""
Used by distros based of RedHat GNU/Linu... | null |
v4 | [
"Any"
] | int | def v4(self, v5) -> int:
self.max_path = 0
def v6(v7):
if v7 == None:
return 0
v8 = v6(v7.left)
v9 = v6(v7.right)
self.max_path = max(v8 + v9, self.max_path)
return max(v8, v9) + 1
v6(v5)
return self.max_path | [
{
"name": "v0",
"input_types": [
"Any"
],
"output_type": "Any",
"code": "def v0(v1):\n if v1 == None:\n return 0\n v2 = v0(v1.left)\n v3 = v0(v1.right)\n self.max_path = max(v2 + v3, self.max_path)\n return max(v2, v3) + 1",
"dependencies": []
}
] | [] | [] | 12 | '''
Given the root of a binary tree, return the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
The length of a path between two nodes is represented by the number of edges between them... | null |
v3 | [
"float",
"v0"
] | float | def v3(self, v4: float, v5: v0) -> float:
v6 = self.lookup_table_values[v5.value]
v7 = self.lookup_table_values[0]
return interp(v4, v7, v6) | [] | [
"numpy"
] | [
"from numpy import interp, loadtxt"
] | 4 | from enum import Enum
from numpy import interp, loadtxt
class Axis(Enum):
Y_AXIS = 1
X_AXIS = 2
class DetectorDistanceToBeamXYConverter:
lookup_file: str
lookup_table_values: list
def __init__(self, lookup_file: str):
self.lookup_file = lookup_file
self.lookup_table_values = se... | [
"class v0(Enum):\n v1 = 1\n v2 = 2"
] |
v3 | [
"float",
"int",
"float",
"v0"
] | float | def v3(self, v4: float, v5: int, v6: float, v7: v0) -> float:
v8 = self.get_beam_xy_from_det_dist(v4, v7)
return v8 * v5 / v6 | [] | [] | [] | 3 | from enum import Enum
from numpy import interp, loadtxt
class Axis(Enum):
Y_AXIS = 1
X_AXIS = 2
class DetectorDistanceToBeamXYConverter:
lookup_file: str
lookup_table_values: list
def __init__(self, lookup_file: str):
self.lookup_file = lookup_file
self.lookup_table_values = se... | [
"class v0(Enum):\n v1 = 1\n v2 = 2"
] |
v0 | [] | list | def v0(self) -> list:
v1 = loadtxt(self.lookup_file, delimiter=' ', comments=['#', 'Units'])
v2 = list(zip(*v1))
return v2 | [] | [
"numpy"
] | [
"from numpy import interp, loadtxt"
] | 4 | from enum import Enum
from numpy import interp, loadtxt
class Axis(Enum):
Y_AXIS = 1
X_AXIS = 2
class DetectorDistanceToBeamXYConverter:
lookup_file: str
lookup_table_values: list
def __init__(self, lookup_file: str):
self.lookup_file = lookup_file
self.lookup_table_values = se... | null |
v0 | [
"bytes"
] | Any | def v0(v1: bytes):
v2 = len(v1) % 4
v1 += b'=' * (4 - v2)
return v1 | [] | [] | [] | 4 | # -*- coding: utf-8 -*-
import base64
import hashlib
import json
import random
import string
import base58
from google.protobuf.json_format import MessageToDict
from tokenio.exceptions import CryptoKeyNotFoundException
from tokenio.proto.alias_pb2 import Alias
from tokenio.proto.member_pb2 import MemberAddKeyOperatio... | null |
v0 | [
"str"
] | str | def v0(self, v1: str) -> str:
v2 = []
v3 = v1.split('/')
for v4 in v3:
if v4 == '..':
if v2:
v2.pop()
elif v4 == '.' or v4 == '':
continue
else:
v2.append(v4)
return '/' + '/'.join(v2) | [] | [] | [] | 12 | """
71. Simplify Path
Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.
In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the directory up a level. For more information, see: Absolute path vs r... | null |
v0 | [
"Union[str, Path]"
] | Any | def v0(v1: Union[str, Path]):
v2 = subprocess.check_output(['git', 'status', '--short'], cwd=v1)
assert not v2 | [] | [
"subprocess"
] | [
"import subprocess"
] | 3 | # Copyright Contributors to the Packit project.
# SPDX-License-Identifier: MIT
import subprocess
from pathlib import Path
from typing import Union
import git
import pytest
from dist2src.constants import START_TAG_TEMPLATE
from tests.conftest import (
MOCK_BUILD,
TEST_PROJECTS_WITH_BRANCHES,
TEST_PROJECT... | null |
v0 | [
"Dict[str, torch.Tensor]"
] | torch.Tensor | def v0(self, v1: Dict[str, torch.Tensor]) -> torch.Tensor:
if isinstance(v1, torch.Tensor):
return v1
elif self.output_transformer is None:
v1 = v1['prediction']
else:
v1 = self.output_transformer(v1)
return v1 | [] | [
"torch"
] | [
"import torch",
"import torch.nn as nn",
"from torch.nn.utils import rnn",
"from torch.optim.lr_scheduler import LambdaLR, ReduceLROnPlateau",
"from torch.utils.data import DataLoader"
] | 8 | """
Timeseries models share a number of common characteristics. This module implements these in a common base class.
"""
from copy import deepcopy
import inspect
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union
import cloudpickle
import matplotlib.pyplot as plt
import numpy as np
import pandas as p... | null |
v0 | [
"Dict[str, torch.Tensor]",
"Dict[str, torch.Tensor]",
"int"
] | None | def v0(self, v1: Dict[str, torch.Tensor], v2: Dict[str, torch.Tensor], v3: int, **v4) -> None:
if (v3 % self.log_interval == 0 or self.log_interval < 1.0) and self.log_interval > 0:
if self.log_interval < 1.0:
v5 = torch.arange(0, len(v1['encoder_lengths']), max(1, round(self.log_interval * len(... | [] | [
"torch"
] | [
"import torch",
"import torch.nn as nn",
"from torch.nn.utils import rnn",
"from torch.optim.lr_scheduler import LambdaLR, ReduceLROnPlateau",
"from torch.utils.data import DataLoader"
] | 18 | """
Timeseries models share a number of common characteristics. This module implements these in a common base class.
"""
from collections import namedtuple
from copy import deepcopy
import inspect
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union
import matplotlib.pyplot as plt
import numpy as np
fr... | null |
v0 | [
"Dict[str, torch.Tensor]"
] | None | def v0(self, v1: Dict[str, torch.Tensor]) -> None:
v2 = []
v3 = []
for (v4, v5) in v1:
if v5.grad is not None and v5.requires_grad and ('bias' not in v4):
v3.append(v4)
v2.append(v5.grad.abs().cpu().mean())
self.logger.experiment.add_histogram(tag=v4, values=v5.gr... | [] | [
"matplotlib"
] | [
"import matplotlib.pyplot as plt"
] | 15 | """
Timeseries models share a number of common characteristics. This module implements these in a common base class.
"""
from collections import namedtuple
import copy
from copy import deepcopy
import inspect
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union
import warnings
import matplotl... | null |
v5 | [
"Any",
"List[int]",
"List[int]",
"List[int]",
"float"
] | Any | def v5(v6, v7: List[int], v8: List[int], v9: List[int]=(1, 1), v10: float=0):
(v11, v12) = v6.size()[-2:]
(v13, v14) = (v0(v11, v7[0], v8[0], v9[0]), v0(v12, v7[1], v8[1], v9[1]))
if v13 > 0 or v14 > 0:
v6 = F.pad(v6, [v14 // 2, v14 - v14 // 2, v13 // 2, v13 - v13 // 2], value=v10)
return v6 | [
{
"name": "v0",
"input_types": [
"int",
"int",
"int",
"int"
],
"output_type": "Any",
"code": "def v0(v1: int, v2: int, v3: int, v4: int):\n return max((math.ceil(v1 / v3) - 1) * v3 + (v2 - 1) * v4 + 1 - v1, 0)",
"dependencies": []
}
] | [
"math",
"torch"
] | [
"import math",
"import torch",
"import torch.nn as nn",
"import torch.nn.functional as F",
"from torch._six import container_abcs"
] | 6 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from typing import Tuple, Optional, List
from torch._six import container_abcs
from itertools import repeat
def _ntuple(n):
def parse(x):
if isinstance(x, container_abcs.Iterable):
return x
... | null |
v15 | [
"Any",
"torch.Tensor",
"Optional[torch.Tensor]",
"Tuple[int, int]",
"Tuple[int, int]",
"Tuple[int, int]",
"int"
] | Any | def v15(v16, v17: torch.Tensor, v18: Optional[torch.Tensor]=None, v19: Tuple[int, int]=(1, 1), v20: Tuple[int, int]=(0, 0), v21: Tuple[int, int]=(1, 1), v22: int=1):
v16 = v5(v16, v17.shape[-2:], v19, v21)
return F.conv2d(v16, v17, v18, v19, (0, 0), v21, v22) | [
{
"name": "v0",
"input_types": [
"int",
"int",
"int",
"int"
],
"output_type": "Any",
"code": "def v0(v1: int, v2: int, v3: int, v4: int):\n return max((math.ceil(v1 / v3) - 1) * v3 + (v2 - 1) * v4 + 1 - v1, 0)",
"dependencies": []
},
{
"name": "v5",
"in... | [
"math",
"torch"
] | [
"import math",
"import torch",
"import torch.nn as nn",
"import torch.nn.functional as F",
"from torch._six import container_abcs"
] | 3 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from typing import Tuple, Optional, List
from torch._six import container_abcs
from itertools import repeat
def _ntuple(n):
def parse(x):
if isinstance(x, container_abcs.Iterable):
return x
... | null |
v0 | [
"int",
"int",
"int"
] | int | def v0(v1: int, v2: int=1, v3: int=1, **v4) -> int:
v5 = (v2 - 1 + v3 * (v1 - 1)) // 2
return v5 | [] | [] | [] | 3 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from typing import Tuple, Optional, List
from torch._six import container_abcs
from itertools import repeat
def _ntuple(n):
def parse(x):
if isinstance(x, container_abcs.Iterable):
return x
... | null |
v11 | [
"Any",
"Any"
] | Tuple[Tuple, bool] | def v11(v12, v13, **v14) -> Tuple[Tuple, bool]:
v15 = False
if isinstance(v12, str):
v12 = v12.lower()
if v12 == 'same':
if v6(v13, **v14):
v12 = v0(v13, **v14)
else:
v12 = 0
v15 = True
elif v12 == 'valid':
... | [
{
"name": "v0",
"input_types": [
"int",
"int",
"int"
],
"output_type": "int",
"code": "def v0(v1: int, v2: int=1, v3: int=1, **v4) -> int:\n v5 = (v2 - 1 + v3 * (v1 - 1)) // 2\n return v5",
"dependencies": []
},
{
"name": "v6",
"input_types": [
"int"... | [] | [] | 15 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from typing import Tuple, Optional, List
from torch._six import container_abcs
from itertools import repeat
def _ntuple(n):
def parse(x):
if isinstance(x, container_abcs.Iterable):
return x
... | null |
v0 | [
"List[int]"
] | Any | def v0(self, v1: List[int]):
for v2 in v1:
self._live_vms.remove(v2) | [] | [] | [] | 3 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from typing import List, Set
from maro.backends.frame import NodeAttribute, NodeBase, node
from .enums import PmState
from .virtual_machine import VirtualMachine
@node("pms")
class PhysicalMachine(NodeBase):
"""Physical machine node defin... | null |
v0 | [
"Set[str]"
] | str | def v0(self, v1: Set[str]) -> str:
v2 = ''
for v3 in v1:
v4 = self.get_single(v3)
logging.info(f'Appending: \n{v4}')
v2 = v2 + v4 + '\n'
return v2 | [] | [
"logging"
] | [
"import logging"
] | 7 | import logging
import os
from typing import Set
from .file_handler import AuxHandler, BibHandler
from .reference import Reference
class Application:
"""Glues together all the functionality of this package.
This class is intended to be called by the `cmdline` module. Afterwards, it
uses the `reference` m... | null |
v0 | [
"int"
] | Any | def v0(self, v1: int):
assert isinstance(v1, int), f'{v1} is not a int.'
assert v1 >= 0, f'player: {v1}<0.'
assert v1 < self.get_game().num_players(), f'player: {v1} >= num_players: {self.get_game().num_players()}' | [] | [] | [] | 4 | # Copyright 2019 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
#
# Unless required by applicable law or agr... | null |
v0 | [] | List[float] | def v0(self) -> List[float]:
if not self._is_terminal:
v1 = [-self._time_step_length * self.current_time_step for v2 in self._vehicle_locations]
for v3 in self._vehicle_at_destination:
v1[v3] = -(self._vehicle_final_arrival_times[v3] * self._time_step_length)
return v1
v1 = [... | [] | [] | [] | 8 | # Copyright 2019 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
#
# Unless required by applicable law or agr... | null |
v0 | [] | None | def v0(self) -> None:
self.itotal = 0
self.ielement = 0 | [] | [] | [] | 3 | #pylint disable=C0301
from struct import Struct, pack
import warnings
from abc import abstractmethod
import inspect
from typing import List
import numpy as np
from numpy import zeros, searchsorted, allclose
from pyNastran.utils.numpy_utils import integer_types, float_types
from pyNastran.op2.result_objects.op2_object... | null |
v0 | [
"bool"
] | List[str] | def v0(self, v1: bool=False) -> List[str]:
if not self.is_built:
return ['<%s>\n' % self.__class__.__name__, f' ntimes: {self.ntimes:d}\n', f' ntotal: {self.ntotal:d}\n']
v2 = self.nelements
v3 = self.ntimes
try:
v4 = self.element_node.shape[0] // v2
except ZeroDivisionError:
... | [] | [
"numpy"
] | [
"import numpy as np",
"from numpy import zeros, where, searchsorted"
] | 27 | """
Defines the Solid Stress/Strain Result
- NX Nastran SOL 401 (contact) analysis for:
- 300-CHEXA
- 301-CPENTA
- 302-CTETRA
- 303-CPYRAM
"""
# pylint: disable=C0301,C0103,R0913,R0914,R0904,C0111,R0201,R0902
from itertools import count
from struct import Struct, pack
from typing import List
import n... | null |
v0 | [] | List[str] | def v0(self) -> List[str]:
v1 = [' F O R C E S I N B A R E L E M E N T S ( C B A R )\n', '0 ELEMENT BEND-MOMENT END-A BEND-MOMENT END-B - SHEAR - AXIAL\n', ' ID. PLANE 1 PLANE 2 PLANE 1 ... | [] | [] | [] | 3 | #pylint disable=C0301
from struct import Struct, pack
import warnings
from abc import abstractmethod
import inspect
from typing import List
import numpy as np
from numpy import zeros, searchsorted, allclose
from pyNastran.utils.numpy_utils import integer_types, float_types
from pyNastran.op2.result_objects.op2_object... | null |
v0 | [
"int"
] | List[str] | def v0(v1: int) -> List[str]:
v2 = ['', '']
v2[0] = 'performance_test_msgs/PerformanceHeader header\n'
v2[1] = 'byte[' + str(v1) + '] data'
return v2 | [] | [] | [] | 5 | from typing import List
import os
import shutil
def get_msg_name(size: int, unit: str) -> str:
return f"Stamped{size}{unit}.msg"
def get_msg_content(byte_size: int) -> List[str]:
content = ["", ""]
content[0] = "performance_test_msgs/PerformanceHeader header\n"
content[1] = "byte[" + str(byte_size) + ... | null |
v2 | [
"int",
"str"
] | Any | def v2(v3: int, v4: str):
if v4.upper() == 'MB':
v3 = v0(v3)
if v4.upper() == 'KB':
v3 = v0(v3)
return v3 | [
{
"name": "v0",
"input_types": [
"int"
],
"output_type": "int",
"code": "def v0(v1: int) -> int:\n return 1024 * v1",
"dependencies": []
}
] | [] | [] | 6 | from typing import List
import os
import shutil
def get_msg_name(size: int, unit: str) -> str:
return f"Stamped{size}{unit}.msg"
def get_msg_content(byte_size: int) -> List[str]:
content = ["", ""]
content[0] = "performance_test_msgs/PerformanceHeader header\n"
content[1] = "byte[" + str(byte_size) + ... | null |
v0 | [
"str",
"str",
"Any"
] | Any | def v0(v1: str, v2: str, v3=False):
v4 = Path(v1)
if v4.is_dir():
if v4.joinpath(v2).exists():
if not v3:
raise FileExistsError('The file %s already exists in chosen directory %s' % (v2, v1))
else:
v5 = 1
v6 = v2.split('.')[0] + '('... | [] | [
"pathlib"
] | [
"from pathlib import Path"
] | 21 | from pathlib import Path
def check_file_paths(file_path):
"""
check if specified input file exists, raises Exception if not
:param file_path: absolute or relative path
:return: path object if file exists
"""
if file_path is None:
return file_path
else:
my_path = Path(file_p... | null |
v0 | [
"str"
] | Path | def v0(self, v1: str) -> Path:
v2 = self.data_home / v1
v2.parent.mkdir(parents=True, exist_ok=True)
v2.touch(exist_ok=True)
return v2 | [] | [] | [] | 5 | """Module implementing XDG directory standard for astrality."""
import os
from pathlib import Path
class XDG:
"""
Class for handling the XDG directory standard.
:param application_name: Name of application to use XDG directory standard.
"""
def __init__(self, application_name: str = 'astrality'... | null |
v0 | [] | str | def v0(self) -> str:
try:
v1 = self.message.lower().split('gratss')[1].split(' ')[1].strip().capitalize()
except:
v1 = self.message
return v1 | [] | [] | [] | 6 | # pylint: disable=no-member,too-many-lines
from __future__ import annotations
import datetime
import math
import threading
import uuid as uuid_lib
import dateutil.parser
import wx
from ninjalooter import config
from ninjalooter import constants
from ninjalooter import extra_data
from ninjalooter import logger
# Thi... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.