code stringlengths 281 23.7M |
|---|
class TestCLIRollover(CuratorTestCase):
def test_max_age_true(self):
value = '1s'
expected = {NEWINDEX: {'aliases': {ALIAS: {}}}}
self.client.indices.create(index=OLDINDEX, aliases={ALIAS: {}})
time.sleep(1)
args = self.get_runner_args()
args += ['--config', self.args... |
class TPWR702N():
MD5SIZE = 16
IMG0_OFFSET = 20
IMG0_HEADER_SIZE = 12
BOOTLOADER_OFFSET = 26820
OS_OFFSET = 262420
def __init__(self, filename):
self.img0 = None
self.md5_checksum = None
self.firmware_filepath = filename
self.firmware = open(filename, 'rb')
... |
class RDepOneComponent(Digraph.Node):
depends_on = ['RDepDependsOn', 'RDepSolvedBy']
def __init__(self, config):
Digraph.Node.__init__(self, 'RDepOneComponent')
self.config = config
def get_type_set():
return set([InputModuleTypes.reqdeps])
def rewrite(reqset):
tracer.deb... |
class OptionPlotoptionsWordcloudSonificationTracksMappingFrequency(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
def handle_dependency_not_found(e: DependencyNotFound) -> None:
sorted_expected = list(map(str, sorted(e.expected_dependencies)))
sorted_missing = list(map(str, sorted(e.missing_dependencies)))
print(('=' * 50))
print(f'Package {e.configuration_file}:')
print(f'Expected: {pprint.pformat(sorted_expec... |
class OptionSeriesScatter3dSonificationContexttracksMappingTremoloSpeed(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
def hexdump(src, length=32, indent=0):
trans_table = ''.join([(((len(repr(chr(x))) == 3) and chr(x)) or '.') for x in range(256)])
lines = []
for c in range(0, len(src), length):
chars = src[c:(c + length)]
hexed = ' '.join([('%02x' % ord(x)) for x in chars])
printable = ''.join([('%... |
class AppSettings():
def __init__(self, prefix):
self.prefix = prefix
def import_from_str(self, name):
from importlib import import_module
(path, prop) = name.rsplit('.', 1)
mod = import_module(path)
return getattr(mod, prop)
def _setting(self, name, dflt):
fr... |
class WhileLoopNodeSerializer(LoopNodeSerializer):
def serialize(self, node: WhileLoopNode) -> Dict:
return super().serialize(node)
def deserialize(self, data: dict) -> WhileLoopNode:
return WhileLoopNode(condition=LogicCondition.deserialize(data['condition'], self._group.new_context), reaching_... |
def get_test_array(shape, dtype, strides=None, offset=0, no_zeros=False, high=None):
shape = wrap_in_tuple(shape)
dtype = dtypes.normalize_type(dtype)
if (offset != 0):
raise NotImplementedError()
if (dtype.names is not None):
result = numpy.empty(shape, dtype)
for name in dtype.... |
def react_speed_in_loop(benchmark: BenchmarkControl, agents_num: int=1, skills_num: int=1, inbox_num: int=5000, agent_loop_timeout: float=0.01) -> None:
wrappers = []
envelope = AEATestWrapper.dummy_envelope()
for i in range(agents_num):
aea_test_wrapper = AEATestWrapper(**_make_custom_config(f'agen... |
class BC_Base():
def __init__(self, shape=None, name=None, b_or=None, b_i=0, nd=None):
self.Shape = shape
self.name = name
self.BC_type = 'None'
if (shape is not None):
self.nd = self.Shape.Domain.nd
elif (nd is not None):
self.nd = nd
else:
... |
def run(args):
opts_parser = argparse.ArgumentParser(description='A shell completion utility for nubia programs')
subparsers = opts_parser.add_subparsers(help='sub-command help', dest='mode')
opts_parser.add_argument('--loglevel', type=str, default='INFO', choices=['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'D... |
class ArrayWidget(_DefaultAttrsWidget, widgets.TextInput):
tag_choices = None
def __init__(self, *args, **kwargs):
self.tags = kwargs.pop('tags', False)
self.escape_space = kwargs.pop('escape_space', True)
self.escape_comma = kwargs.pop('escape_comma', True)
super(ArrayWidget, se... |
class InterComBackEndBinding():
def __init__(self, analysis_service=None, compare_service=None, unpacking_service=None, unpacking_locks=None, testing=False):
self.analysis_service = analysis_service
self.compare_service = compare_service
self.unpacking_service = unpacking_service
sel... |
class OptionTitle(Options):
def align(self):
return self._config_get('center')
def align(self, text: str):
self._config(text)
def display(self):
return self._config_get(False)
def display(self, flag: bool):
self._config(flag)
def fullSize(self):
return self._c... |
class TestAddProtocolFromRemoteRegistry(AEATestCaseEmptyFlaky):
IS_LOCAL = False
IS_EMPTY = True
.integration
.flaky(reruns=MAX_FLAKY_RERUNS)
def test_add_protocol_from_remote_registry_positive(self):
self.add_item('protocol', str(FipaMessage.protocol_id.to_latest()), local=self.IS_LOCAL)
... |
def main():
parser = argparse.ArgumentParser(description='jinja2 template rendering with shell environment variables')
parser.add_argument('input_file', nargs='?', help='Input filename. Defaults to stdin.')
parser.add_argument('-o', '--output-file', help=('Output filename. If none is given, and the input fi... |
def mock_request(data, loop):
payload = StreamReader(' loop=loop, limit=1024)
payload.feed_data(data.encode())
payload.feed_eof()
protocol = mock.Mock()
app = mock.Mock()
headers = CIMultiDict([('CONTENT-TYPE', 'application/json')])
req = make_mocked_request('POST', '/sensor-reading', header... |
def download_gh_asset(url: str, path: str, overwrite=False):
zipped = requests.get(url)
z = ZipFile(io.BytesIO(zipped.content))
Path(path).mkdir(exist_ok=True)
if overwrite:
shutil.rmtree(path, ignore_errors=True)
z.extractall(path)
click.echo(f'files saved to {path}')
z.close() |
.parametrize('value,expected', (('', False), ('a', False), (1, False), (True, False), ({'a': 1, 'b': 2}, False), (tuple(), False), (list(), False), (('a', 'b'), False), (['a', 'b'], False), (b'', False), (b'arst', False), (None, True), (TOPIC_A, True), (TOPIC_B, True)))
def test_is_topic(value, expected):
actual = ... |
class OptionPlotoptionsGaugeSonificationTracksMappingHighpass(Options):
def frequency(self) -> 'OptionPlotoptionsGaugeSonificationTracksMappingHighpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsGaugeSonificationTracksMappingHighpassFrequency)
def resonance(self) -> 'OptionPlo... |
class HttpResponseFormat(ModelNormal):
allowed_values = {}
validations = {}
_property
def additional_properties_type():
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def openapi_types():
return {'code': (int,), 'reason': (st... |
.slow
.skipif((not GPU_TESTS_ENABLED), reason='requires GPU')
def test_generate_sample(dolly_generator):
prompts = ['What is spaCy?', 'What is spaCy?']
torch.manual_seed(0)
assert (dolly_generator(prompts, config=SampleGeneratorConfig(top_k=10)) == ["SpaCy (short for spaCy Toolkit) is a Python library for N... |
class TGCustomYield():
def __init__(self):
self.main_bot = MegaDLBot
async def generate_file_properties(msg: Message):
error_message = "This message doesn't contain any downloadable media"
available_media = ('audio', 'document', 'photo', 'sticker', 'animation', 'video', 'voice', 'video_n... |
def CreateBmmSoftmaxBmmPermOperator(manifest, operation_kind=library.GemmKind.BatchGemmSoftmaxGemmPermute, xdl_op_type=gemm.XdlOpType.DeviceBatchedGemmSoftmaxGemmPermute_Xdl_CShuffle, causal_mask=None):
a_element_desc = library.TensorDesc(library.DataType.f16, library.LayoutType.RowMajor)
b_element_desc = libra... |
class ErrorTestCase(unittest.TestCase):
feature = {'geometry': {'type': 'Bizarro', 'coordinates': [[(1, 2), (3, 4)], [(7, 8), (9, 10)]]}, 'properties': {}}
def setUp(self):
logging.getLogger('svgis').setLevel(logging.CRITICAL)
def testDrawInvalidGeometry(self):
with self.assertRaises(errors.... |
(private_key_bytes=private_key_st)
def test_public_key_decompression_is_equal(private_key_bytes, native_key_api, coincurve_key_api):
public_key_template = coincurve_key_api.PrivateKey(private_key_bytes).public_key
compressed_public_key = public_key_template.to_compressed_bytes()
native_public_key = native_k... |
class Matching(object):
def __init__(self, core: Core):
self.core = core
def start(self, modes: Sequence[str]) -> None:
core = self.core
core.server.write(wire.msg.StartMatching(modes=list(modes)))
def stop(self) -> None:
core = self.core
core.server.write(wire.msg.St... |
.parametrize('model', [BinarySensorInfo, ButtonInfo, CoverInfo, FanInfo, LightInfo, NumberInfo, SelectInfo, SensorInfo, SirenInfo, SwitchInfo, TextSensorInfo, CameraInfo, ClimateInfo, LockInfo, MediaPlayerInfo, AlarmControlPanelInfo, TextInfo])
def test_build_unique_id(model):
obj = model(object_id='id')
assert... |
def install_npm_win(env_dir, src_dir, args):
logger.info((' * Install npm.js (%s) ... ' % args.npm), extra=dict(continued=True))
npm_url = (' % args.npm)
npm_contents = io.BytesIO(urlopen(npm_url).read())
bin_path = join(env_dir, 'Scripts')
node_modules_path = join(bin_path, 'node_modules', 'npm')
... |
class GenericDataloader():
def __init__(self, source_list: List[str], target_list: Union[(List[str], List[None])], tgt_lang_list: Optional[List[str]]=None) -> None:
self.source_list = source_list
self.target_list = target_list
self.tgt_lang_list = tgt_lang_list
assert (len(self.sourc... |
def cupy_pytorch_allocator(size_in_bytes: int):
device = get_torch_default_device()
size_in_bytes = max(1024, size_in_bytes)
torch_tensor = torch.zeros(((size_in_bytes // 4),), requires_grad=False, device=device)
address = torch_tensor.data_ptr()
memory = cupy.cuda.memory.UnownedMemory(address, size... |
def run_server(debug_gc=False):
service = None
if debug_gc:
from pprint import pformat
import gc
gc.enable()
gc.set_debug(gc.DEBUG_LEAK)
gc_timeout = 10
def gc_collect():
gc.collect()
if (len(gc.garbage) > 0):
print('\n\n')
... |
def test_ge_with_task():
task_object = GreatExpectationsTask(name='test6', datasource_name='data', inputs=kwtypes(dataset=str), expectation_suite_name='test.demo', data_connector_name='data_example_data_connector')
def my_task(csv_file: str) -> int:
df = pd.read_csv(os.path.join('data', csv_file))
... |
class SetActiveAttribute(Filter):
__version__ = 0
input_info = PipelineInfo(datasets=['any'], attribute_types=['any'], attributes=['any'])
output_info = PipelineInfo(datasets=['any'], attribute_types=['any'], attributes=['any'])
point_scalars_name = DEnum(values_name='_point_scalars_list', desc='scalar ... |
class PythonShellTask(Task):
id = 'pyface.tasks.contrib.python_shell'
name = 'Python Shell'
bindings = List(Dict)
commands = List(Str)
pane = Instance(PythonShellPane)
menu_bar = SMenuBar(SMenu(TaskAction(name='Open...', method='open', accelerator='Ctrl+O'), id='File', name='&File'), SMenu(id='V... |
('pyscf')
.parametrize('xyz_fn, coord_type, ref_rms', [('lib:hcn_bent.xyz', 'cart', 1.2e-06), ('lib:h2o2_rot2.xyz', 'redund', 0.000877)])
def test_numhess(xyz_fn, coord_type, ref_rms):
geom = geom_loader(xyz_fn, coord_type=coord_type)
calc = PySCF(basis='321g', pal=2, keep_chk=False)
geom.set_calculator(cal... |
class OptionSeriesXrangeSonificationDefaultinstrumentoptions(Options):
def activeWhen(self) -> 'OptionSeriesXrangeSonificationDefaultinstrumentoptionsActivewhen':
return self._config_sub_data('activeWhen', OptionSeriesXrangeSonificationDefaultinstrumentoptionsActivewhen)
def instrument(self):
re... |
def read_configuration_from_pyproject_toml(ctx: click.Context, _param: click.Parameter, value: Path) -> (Path | None):
try:
pyproject_data = load_pyproject_toml(value)
except FileNotFoundError:
logging.debug('No pyproject.toml file to read configuration from.')
return value
try:
... |
def _initialize_model_cache(system_app: SystemApp):
from dbgpt.storage.cache import initialize_cache
if (not CFG.MODEL_CACHE_ENABLE):
logger.info('Model cache is not enable')
return
storage_type = (CFG.MODEL_CACHE_STORAGE_TYPE or 'disk')
max_memory_mb = (CFG.MODEL_CACHE_MAX_MEMORY_MB or ... |
def user_record_to_row(user: UserRecord) -> Row:
row = {'uid': user.uid}
keys = ['email', 'uid', 'display_name', 'phone_number', 'photo_url', 'disabled', 'email_verified']
for key in keys:
value = getattr(user, key)
if (value is not None):
row[key] = value
if user.provider_da... |
def setup_dev_environment(dags: List[DAG], host: Optional[str]='0.0.0.0', port: Optional[int]=5555, logging_level: Optional[str]=None, logger_filename: Optional[str]=None) -> None:
import uvicorn
from fastapi import FastAPI
from dbgpt.component import SystemApp
from dbgpt.util.utils import setup_logging... |
class Pluginstests(DatabaseTestCase):
def test_load_all_plugins(self):
all_plugins = plugins.load_all_plugins(self.session)
backend_plugins = all_plugins['backends']
self.assertEqual(len(backend_plugins), len(EXPECTED_BACKENDS))
backend_names = sorted((plugin.name for plugin in backe... |
class OptionPlotoptionsBulletSonificationDefaultspeechoptionsPointgrouping(Options):
def algorithm(self):
return self._config_get('last')
def algorithm(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: boo... |
def sort_configuration_file(config: PackageConfiguration) -> None:
assert (config.directory is not None)
configuration_filepath = (config.directory / config.default_configuration_filename)
if (config.package_type == PackageType.AGENT):
json_data = config.ordered_json
component_configurations... |
(max_runs=3)
def test_miner_start(w3_empty, wait_for_miner_start):
w3 = w3_empty
assert w3.eth.mining
assert w3.eth.hashrate
w3.geth.miner.stop()
with Timeout(60) as timeout:
while (w3.eth.mining or w3.eth.hashrate):
timeout.sleep(random.random())
assert (not w3.eth.mining)
... |
class DataIteratorTest(absltest.TestCase):
def test_transition_iterator(self):
obs_size = 3
act_size = 4
replay = replay_lib.ReplayBuffer(int(1000.0), obs_shape=(obs_size,), action_shape=(act_size,))
for _ in range(10):
replay.add(np.zeros(obs_size), np.zeros(act_size), n... |
class RectangularSelectionTestCase(EnableTestAssistant, unittest.TestCase):
def test_selection_mask(self):
plot_data = ArrayPlotData()
plot = Plot(plot_data)
arr = np.array([(- 2), (- 1), 1, 2])
plot_data.set_data('x', arr)
plot_data.set_data('y', arr)
splot = plot.pl... |
class OFProtocol(namedtuple('OFProtocol', ['version', 'classes', 'enums'])):
def __init__(self, version, classes, enums):
assert ((version is None) or isinstance(version, OFVersion))
def class_by_name(self, name):
return find((lambda ofclass: (ofclass.name == name)), self.classes)
def enum_b... |
class OptionPlotoptionsSunburstSonificationTracksMappingLowpass(Options):
def frequency(self) -> 'OptionPlotoptionsSunburstSonificationTracksMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsSunburstSonificationTracksMappingLowpassFrequency)
def resonance(self) -> 'Opt... |
def validate_minimal_contract_factory_data(contract_data: Dict[(str, str)]) -> None:
if (not all(((key in contract_data.keys()) for key in ('abi', 'deploymentBytecode')))):
raise InsufficientAssetsError('Minimum required contract data to generate a deployable contract factory (abi & deploymentBytecode) not ... |
def read_union(decoder, writer_schema, named_schemas, reader_schema=None, options={}):
index = decoder.read_index()
idx_schema = writer_schema[index]
if reader_schema:
msg = f'schema mismatch: {writer_schema} not found in {reader_schema}'
if (not isinstance(reader_schema, list)):
... |
class OptionPlotoptionsFunnel3dLabelStyle(Options):
def fontSize(self):
return self._config_get('0.8em')
def fontSize(self, num: float):
self._config(num, js_type=False)
def fontWeight(self):
return self._config_get('bold')
def fontWeight(self, text: str):
self._config(te... |
def gaussian_highpass_kernel(fft_grid, wavelength):
dims = fft_grid.dims
freq_easting = fft_grid.coords[dims[1]]
freq_northing = fft_grid.coords[dims[0]]
k_easting = ((2 * np.pi) * freq_easting)
k_northing = ((2 * np.pi) * freq_northing)
da_filter = (1 - np.exp(((- ((k_easting ** 2) + (k_northin... |
def extractHarushyazinthengartenArtBlog(item):
if item['title'].startswith('Protected: '):
return None
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('a villain is a good ... |
def test_switch_test_no_default(task):
var_1 = Variable('var_1', Pointer(Integer(32, True), 32), None, False, Variable('var_28', Pointer(Integer(32, True), 32), 1, False, None))
switch_variable = Variable('var_0', Integer(32, True), None, True, Variable('var_10', Integer(32, True), 0, True, None))
task.grap... |
def change_sbref_palette(user_settings, temp_dir):
sbref_nii = os.path.join(temp_dir, '{}_SBRef.nii.gz'.format(user_settings.fmri_name))
func4D_nii = os.path.join(user_settings.work_dir, user_settings.subject, 'MNINonLinear', 'Results', user_settings.fmri_name, '{}.nii.gz'.format(user_settings.fmri_name))
r... |
class OptionSeriesVennData(Options):
def accessibility(self) -> 'OptionSeriesVennDataAccessibility':
return self._config_sub_data('accessibility', OptionSeriesVennDataAccessibility)
def className(self):
return self._config_get(None)
def className(self, text: str):
self._config(text, ... |
class OptionPlotoptionsTreemapSonificationContexttracksMappingRate(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
_pkg_resources
_mypy
class TestAnnotations(TestCase, MypyAssertions):
def test_all(self, filename_suffix=''):
examples_dir = Path(pkg_resources.resource_filename('traits.stubs_tests', 'examples'))
for file_path in examples_dir.glob('*{}.py'.format(filename_suffix)):
with self.subTest(fil... |
('cuda.gather.gen_function')
def gen_function(func_attrs):
inputs = func_attrs['inputs']
x = inputs[0]
index = inputs[1]
y = func_attrs['outputs'][0]
x_shape = x._attrs['shape']
input_type = cuda_common.dtype_to_cuda_type(x._attrs['dtype'])
index_type = cuda_common.dtype_to_cuda_type(index._... |
class OptionPlotoptionsVennSonificationContexttracksMappingLowpassResonance(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: st... |
class OptionSeriesPyramidDatalabels(Options):
def align(self):
return self._config_get('center')
def align(self, text: str):
self._config(text, js_type=False)
def alignTo(self):
return self._config_get(None)
def alignTo(self, text: str):
self._config(text, js_type=False)
... |
class TestFrozenFieldHook(unittest.TestCase):
def test_init_update_events_generic_hook(self) -> None:
dummy_obj = DummyInstance('01', 'Tupper01', '//fbsource', '//fbsource:output', 25)
self.assertEqual(dummy_obj.highest_pressure, 25)
dummy_obj.pressure = 70
self.assertEqual(dummy_obj... |
def send_email(user, email_content):
response = ses_client.send_email(Source='Haohaotiantian <>', Destination={'ToAddresses': [user.email_address]}, Message={'Subject': {'Charset': 'UTF-8', 'Data': ('Daily vocab word - ' + datetime.today().strftime('%b. %d, %Y'))}, 'Body': {'Html': {'Charset': 'UTF-8', 'Data': emai... |
def test_points_in_polygon(reekset):
(_poi, pol) = reekset
poi = _poi.copy()
assert (poi.nrow == 30)
poi.operation_polygons(pol, 0, opname='eli', version=2)
assert (poi.nrow == 19)
poi.operation_polygons(pol, 0, opname='eli', inside=False, version=1)
assert (poi.nrow == 0)
poi = _poi.cop... |
class WebhookBase():
_attr
def __tablename__(cls) -> str:
return cls.__name__.lower()
name = Column(String, unique=True, nullable=False)
key = Column(String, index=True, unique=True, nullable=False)
_attr
def policy_id(cls: 'WebhookBase') -> Column:
return Column(String, ForeignK... |
class ChooserButton():
def __init__(self, button, default_label=''):
self.button = button
self.default_label = default_label
self.label = None
self._menu = None
self._icon = None
children = self.button.get_children()
if ((len(children) == 1) and isinstance(chi... |
def extractLittlesleepysheepBlogspotCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [("transmigrated to another world where only men exist~bl isn't allowed!~", "Transmigrated ... |
class TestImportantGitExternalDataChecker(_TestWithInlineManifest):
_DUMMY_CHECKER_CLS = GitUpdateEverythingChecker
def setUp(self):
init_logging()
async def test_update_no_important_source_updated(self):
filename = 'importantsource.com.virustotal.Uploader.yml'
contents = "\nid: impo... |
def setup_to_fail():
shellexec('nft flush chain inet filter input')
shellexec('nft flush chain inet filter forward')
shellexec('nft flush chain inet filter output')
shellexec('nft delete chain inet filter input')
shellexec('nft delete chain inet filter forward')
shellexec('nft delete chain inet ... |
def get_installed_packages(project_path: Path) -> Tuple[(List, List)]:
packages_json = _load_packages_json(project_path)
installed: Set = set(packages_json['packages'])
modified: Set = set()
deleted: Set = set(packages_json['packages'])
for source_path in list(packages_json['sources']):
pack... |
def test_unslice_will_set_the_pixel_aspect_to_1(prepare_scene, create_pymel):
camera = prepare_scene
pm = create_pymel
dres = pm.PyNode('defaultResolution')
dres.width.set(1920)
dres.height.set(1080)
dres.pixelAspect.set(2.5)
rs = RenderSlicer(camera)
rs.slice(10, 10)
rs.unslice()
... |
def extractVoidTranslations(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
match = re.search('^Xian Ni Chapter \\d+ ?[\\-]? ?(.*)$', item['title'])
if match:
return buildRelea... |
def plot_figure(data, x, y, title=None, xlabel=None, ylabel=None, legend=None, x_axis_type='linear', y_axis_type='linear', width=800, height=400, line_width=2, colors=['red', 'green', 'blue', 'orange', 'black', 'purple', 'brown'], tools='pan,box_zoom,wheel_zoom,box_select,hover,reset,save', append_figure=None):
if ... |
def find_first(node: LN, target: int, recursive: bool=False) -> Optional[LN]:
queue: List[LN] = [node]
queue.extend(node.children)
while queue:
child = queue.pop(0)
if (child.type == target):
return child
if recursive:
queue = (child.children + queue)
retu... |
def chord_topology(m, r=1):
if ((not isinstance(m, int)) or (not isinstance(r, int))):
raise TypeError('m and r must be integers')
if (m < 2):
raise ValueError('m must be an integer >= 2')
if ((r < 1) or (r > ((2 ** m) - 1))):
raise ValueError('r must be an integer and 1 <= r <= 2^m'... |
class Dataset(Base, FidesBase):
__tablename__ = 'ctl_datasets'
meta = Column(JSON)
data_categories = Column(ARRAY(String))
collections = Column(JSON)
fides_meta = Column(JSON)
def create_from_dataset_dict(cls, db: Session, dataset: dict) -> 'Dataset':
validated_dataset: FideslangDataset ... |
class OptionPlotoptionsPolygonSonificationDefaultspeechoptions(Options):
def activeWhen(self) -> 'OptionPlotoptionsPolygonSonificationDefaultspeechoptionsActivewhen':
return self._config_sub_data('activeWhen', OptionPlotoptionsPolygonSonificationDefaultspeechoptionsActivewhen)
def language(self):
... |
class OptionLangAccessibilitySeries(Options):
def description(self):
return self._config_get('{description}')
def description(self, text: str):
self._config(text, js_type=False)
def nullPointValue(self):
return self._config_get('No value')
def nullPointValue(self, text: str):
... |
class ProcessNode(TestNode):
def make(cls, name: str, rate: float, process: Optional[int]=process.ENVIRONMENT, inputs: Optional[List[str]]=None, outputs: Optional[List[str]]=None, states: Optional[List[str]]=None, color: Optional[str]='white', test_arg: Optional[str]='test_argument'):
spec = cls.get_specifi... |
def login_user_exist(form, field):
result = FlicketUser.query.filter_by(username=form.username.data)
if (result.count() == 0):
field.errors.append('Invalid username.')
return False
result = result.first()
if (bcrypt.hashpw(form.password.data.encode('utf-8'), result.password) != result.pa... |
def create_logger():
loggr = logging.getLogger('nodeenv')
loggr.setLevel(logging.INFO)
def emit(self, record):
msg = self.format(record)
fs = ('%s' if getattr(record, 'continued', False) else '%s\n')
self.stream.write((fs % to_utf8(msg)))
self.flush()
logging.StreamHandle... |
class TestHtml5OnlySelectors(util.PluginTestCase):
def setup_fs(self):
template = self.dedent('\n <!DOCTYPE html>\n <html>\n <head>\n <meta content="text/html; charset=UTF-8">\n </head>\n <body>\n <div>\n <p>aaaa<... |
def test_flyte_system_exception():
try:
raise system.FlyteSystemException('bad')
except Exception as e:
assert (str(e) == 'bad')
assert isinstance(type(e), base._FlyteCodedExceptionMetaclass)
assert (type(e).error_code == 'SYSTEM:Unknown')
assert isinstance(e, base.FlyteE... |
def test_ref_task_more():
_task(project='flytesnacks', domain='development', name='recipes.aaa.simple.join_strings', version='553018f39e519bdb2597b652639c30ce16b99c79')
def ref_t1(a: typing.List[str]) -> str:
...
def wf1(in1: typing.List[str]) -> str:
return ref_t1(a=in1)
with pytest.rai... |
class OptionSeriesColumnSonificationContexttracksMappingTime(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
sel... |
class OptionSeriesErrorbarSonificationTracksMappingTremoloSpeed(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
class OptionSeriesPyramidSonificationTracksMappingTremolo(Options):
def depth(self) -> 'OptionSeriesPyramidSonificationTracksMappingTremoloDepth':
return self._config_sub_data('depth', OptionSeriesPyramidSonificationTracksMappingTremoloDepth)
def speed(self) -> 'OptionSeriesPyramidSonificationTracksMapp... |
def test_get_state_serialization():
kwargs_arg = ContractApiMessage.Kwargs({'key_1': 1, 'key_2': 2})
msg = ContractApiMessage(message_id=1, dialogue_reference=(str(0), ''), target=0, performative=ContractApiMessage.Performative.GET_STATE, ledger_id='some_ledger_id', contract_id='some_contract_id', contract_addr... |
class EditorWidget(QtGui.QDockWidget):
def __init__(self, editor, parent=None):
super().__init__(parent)
self.editor = editor
self.editor.create(self)
self.setAllowedAreas(QtCore.Qt.DockWidgetArea.LeftDockWidgetArea)
self.setFeatures((QtGui.QDockWidget.DockWidgetFeature.DockW... |
def test_env_variable_interpolation(config, yaml_config_file_3):
config.from_yaml(yaml_config_file_3)
assert (config() == {'section1': {'value1': 'test-value', 'value2': 'test-path/path'}})
assert (config.section1() == {'value1': 'test-value', 'value2': 'test-path/path'})
assert (config.section1.value1(... |
def get_tensor_accessor_alignments(func_attrs):
input_accessors = func_attrs['input_accessors']
a_alignment = tensor_accessor_codegen.find_max_alignment_for_accessor(input_accessors[0])
b_alignment = tensor_accessor_codegen.find_max_alignment_for_accessor(input_accessors[1])
output_accessor = func_attrs... |
('config_name,overrides,expected', [param('override_hydra2', [], DefaultsTreeNode(node=VirtualRoot(), children=[DefaultsTreeNode(node=ConfigDefault(path='hydra/config'), children=[GroupDefault(group='help', value='custom1'), GroupDefault(group='output', value='default'), ConfigDefault(path='_self_')]), ConfigDefault(pa... |
class Job():
def __repr__(self):
return ('Job (%s, %s)' % (self.jobname, self.jobid[:6]))
def __init__(self, bin, args, jobname=None, parent_ids=None):
self.status = None
self.bin = bin
self.args = args
self.cores = 1
self.exec_type = 'insitu'
self.jobname... |
class squeeze(_view):
def __init__(self, dim: Optional[int]) -> None:
super().__init__()
self._attrs['op'] = 'squeeze'
self._attrs['dim'] = dim
self.shape_eval_template = SQUEEZE_FUNC_TEMPLATE
def _infer_shapes(self, x: Tensor) -> IntVar:
dim = self._attrs['dim']
... |
class TriggerThread(threading.Thread):
def __init__(self, redischannel, trigger):
threading.Thread.__init__(self)
self.redischannel = redischannel
self.name = trigger
self.running = True
def stop(self):
self.running = False
def run(self):
global r, lsl_format,... |
class StepStateCriticComposer(BaseStateCriticComposer):
def __init__(self, observation_spaces_dict: Dict[(Union[(str, int)], spaces.Dict)], agent_counts_dict: Dict[(StepKeyType, int)], networks: CollectionOfConfigType):
super().__init__(observation_spaces_dict, agent_counts_dict)
networks = list_to_... |
def main():
argv = sys.argv
logging.basicConfig(format='[%(asctime)s][%(name)s][%(levelname)s] - %(message)s', handlers=[logging.StreamHandler()], level=logging.INFO)
if ((len(argv) < 2) or (argv[1] not in all_cli_commands)):
cmd_names = sorted(all_cli_commands.keys())
print(f'Usage: {argv[0... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.