text stringlengths 1 927k |
|---|
def process_transaction_type(state: BeaconState,
transactions: List[Any],
max_transactions: int,
tx_fn: Callable[[BeaconState, Any], None]) -> None:
assert len(transactions) <= max_transactions
for transaction in transactions... |
from django.contrib import admin
from .models import Page
# Register your models here.
class PageAdmin(admin.ModelAdmin):
list_display = ('title', 'update_date')
ordering = ('title',)
search_fields = ('title',)
admin.site.register(Page, PageAdmin) |
from typing import List
from prime_numbers.int import Int
class PrimeNumbers:
def __init__(self, numbers: List[int]):
self._numbers = numbers
def __iter__(self):
for number in self._numbers:
if Int(number).prime():
yield number |
# Copyright (c) 2015-2018 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge... |
import os
import glob
import random
import numpy as np
import cv2
from tqdm.auto import tqdm
def cropimage(img_name):
row_list_top = []
row_list_top_idx = []
row_list_bottom = []
row_list_bottom_idx = []
img_original = cv2.imread(img_name, 0)
H_original, W_original = img_original.shape[:2]
... |
"""
METAR Report Tests
"""
# pylint: disable=invalid-name
# stdlib
from dataclasses import asdict
from datetime import datetime
# module
from avwx import static, structs
from avwx.current import metar
# tests
from tests.util import BaseTest, get_data
class TestMetar(BaseTest):
"""
Tests Metar class and pa... |
from pcassandra import connection
class CassandraConnectionSetupWsgiMiddleware:
"""WSGI middleware, setup the Cassandra connection when receiving the first request
To use it, create a 'development version' of the 'WSGI application':
* Add to `wsgi.py`:
from pcassandra.dj18 import wsgi
a... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/components/shield_generator/shared_shd_sfs_imperial_heavy.iff"
... |
# coding=utf-8
from bluebottle.test.factory_models.slides import SlideFactory
from tenant_schemas.urlresolvers import reverse
from bluebottle.test.utils import BluebottleAdminTestCase
class SlideAdminTest(BluebottleAdminTestCase):
def setUp(self):
super(SlideAdminTest, self).setUp()
self.news = S... |
from collections import deque
import time
import gym
import numpy as np
from gym import spaces, logger
from gym.utils import seeding
from gym.envs.classic_control import rendering
class SnakeEnv(gym.Env):
metadata = {
"render.modes": ["human", "rgb_array"],
"video.frames_per_second": "35"
}
... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
# <summary>
# 虚拟按键代码
# 参考于 http://msdn.microsoft.com/zh-cn/library/dd375731(v=vs.85).aspx
# </summary>
# public enum VirtualKeyCode
class VirtualKeyCode:
# <summary>
# Left mouse button
# </summary>
Left_mouse_button = 0x01
# <summary>
# Right mouse button
# </summary>
Right_... |
import googletrans as gt
gt = gt.Translator()
class tr():
@staticmethod
def fr(text):
res = gt.translate(text, dest='fr')
return res.text
@staticmethod
def ar(text):
res = gt.translate(text, dest='ar')
return res.text
@staticmethod
def en(text):
res = gt.translate(text, d... |
import math
from logging import getLogger
from typing import Optional
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils import weight_norm
from libcity.model import loss
from libcity.model.abstract_traffic_state_model import AbstractTrafficStateModel
def remov... |
# -*- coding: utf-8 -*-
"""Unit test package for toy_robot_challenge.""" |
import numpy as np
from cobras_ts.superinstance import SuperInstance
def get_prototype(A,indices):
max_affinity_to_others = -np.inf
prototype_idx = None
for idx in indices:
affinity_to_others = 0.0
for j in indices:
if j == idx:
continue
affinity_t... |
class Node:
# Constructor untuk buat node sebagai objek
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Fungsi untuk inisialisasi kepala
def __init__(self):
self.head = None
# Fungsi untuk memasukkan Node baru di awal
def push(self, ne... |
import random
import statistics
import time
class Chromosome:
Genes = None
Fitness = None
def __init__(self,genes,fitness):
self.Genes = genes
self.Fitness = fitness
def _generate_gene(length,geneset,get_fitness):
genes = []
while len(genes) < length:
#samples = min(length - len(genes), len(geneset))
a ... |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'includes': [
'../../../../../native_client/build/untrusted.gypi',
],
'targets': [
{
# The full library, which PNaCl uses for offli... |
#!/usr/bin/python
# -*- encoding: utf-8 -*-
#
# Swift dispersion monitoring script for Nagios
#
# Copyright © 2012 eNovance <licensing@enovance.com>
#
# Author: Julien Danjou <julien@danjou.info>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Lice... |
import numpy as np
from netCDF4 import Dataset
import matplotlib.pyplot as plt
from plotly.graph_objs import Scattergeo, Layout
from plotly import offline
from cartopy import config
import matplotlib as matplot
from matplotlib.image import imread
import cartopy.crs as crs
import os
import shapely.geometry as sgeom
from... |
import sys
max_am = int(sys.argv[1])
prefix = str(sys.argv[2])
file = open(prefix + "/qlist.txt", "w")
file.write(prefix + "/generated/ecpint_gen.cpp\n")
for j in range(max_am+1):
for i in range(j+1):
for k in range(max_am+1):
if j == i == k == max_am:
file.write(prefix + "/gene... |
import os
from ast import literal_eval
from datetime import datetime
from django.conf import settings
from django.contrib import auth, messages
from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.models import Site
from django.http import... |
# Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""
Remove gGRC Admin hardcoded permissions
Create Date: 2016-06-10 07:10:22.781593
"""
# disable Invalid constant name pylint warning for mandatory Alembic variables.
# pylint: disable=invalid-name
from ... |
import math
import logging
from pprint import pprint, pformat # noqa
from aleph.core import url_external
from aleph.index.util import unpack_result
from aleph.search.parser import QueryParser
from aleph.search.facet import CategoryFacet, CollectionFacet, CountryFacet
from aleph.search.facet import LanguageFacet, Sche... |
import os
from glob import glob
from typing import Optional
import cv2
import numpy as np
import torch
import yaml
from fire import Fire
from tqdm import tqdm
from aug import get_normalize
from models.networks import get_generator
class Predictor:
def __init__(self, weights_path: str, model_name: str = ''):
... |
import logging
import random
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import urllib.request
import json
import imdb
import os
BOT_TOKEN = os.environ.get("BOT_TOKEN")
OMDB_API_KEY = '558c75c8'
ia = imdb.IMDb()
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(mess... |
"""Progress Bar Simulation, by Al Sweigart al@inventwithpython.com
A sample progress bar animation that can be used in other programs.
This and other games are available at https://nostarch.com/XX
Tags: tiny, module"""
__version__ = 0
import random, time
BAR = chr(9608) # Character 9608 is '█'
def main():
# Simul... |
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow.keras as keras
import tensorflow.keras.layers as layers
from PIL import Image
from io import BytesIO
import matplotlib.pyplot as plt
import numpy as np
import requests
import os
import platform
import pathlib
import random
import math
base_path =... |
from setuptools import setup
setup(
name='relnet',
version='',
packages=['relnet'],
url='',
license='',
author='Roger Paredes',
author_email='',
description=''
)
from setuptools import setup, find_packages
from codecs import open
from os import path
__version__ = '0.0.1'
here = path.a... |
# Copyright 2020 The T5 Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... |
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2013 ecdsa@github
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without li... |
import json
def add_to_map(data_map, key):
if key in data_map:
data_map[key] += 1
elif key not in data_map:
data_map[key] = 1
return data_map
def get_json(line, headers):
sample_data = {}
for i, val in enumerate(line):
sample_data[headers[i]] = val
return sample_data... |
#!/usr/bin/python
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License")... |
import weasyprint
from django.conf import settings
from django.template.response import TemplateResponse
from django.views.generic.base import ContextMixin, TemplateResponseMixin, View
from django_weasyprint.utils import django_url_fetcher
class WeasyTemplateResponse(TemplateResponse):
def __init__(self, filenam... |
#!python
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribut... |
from enum import auto
from os.path import abspath, expanduser, sep
from pathlib import Path
import pytest
from napari.utils.misc import (
StringEnum,
abspath_or_url,
ensure_iterable,
ensure_sequence_of_iterables,
)
ITERABLE = (0, 1, 2)
NESTED_ITERABLE = [ITERABLE, ITERABLE, ITERABLE]
DICT = {'a': 1, ... |
from unittest.mock import patch
import pytest
from model.agents.student.activities import IdleActivity, StudySessionActivity
__author__ = 'e.kolpakov'
class TestIdleActivity:
@pytest.mark.parametrize("length", [10, 15, 20, 3, 7, 11])
def test_activate_sends(self, student, env, length):
activity = ... |
"""Support for mill wifi-enabled home heaters."""
import mill
import voluptuous as vol
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
CURRENT_HVAC_HEAT,
CURRENT_HVAC_IDLE,
FAN_ON,
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
SUPPORT_FAN_MODE,
... |
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
import importlib
import logging
from typing import (
Any, Iterator, Union,
)
import neo4j
from neo4j import GraphDatabase
from pyhocon import ConfigFactory, ConfigTree
from databuilder.extractor.base_extractor import Extracto... |
# -------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
# ----------------------------------------------------------------------... |
#!/usr/local/bin/python
import functools, httplib, os, sys
import MySQLdb
import useful
# --- Web Pages ---------------------------------------------------------
def get_page_info(page_id, form_key='', defval='', args='', dbedit=None):
import pifile
pif = pifile.PageInfoFile(page_id, form_key, defval, args... |
import ldap3
# server info
server = ldap3.Server('10.10.10.175', get_info=ldap3.ALL, port=389)
connection = ldap3.Connection(server)
print('Bind connection: ', connection.bind())
print(server.info)
# search on each name context
name_contexts = ['DC=EGOTISTICAL-BANK,DC=LOCAL',
'CN=Configuration,DC=EG... |
"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W... |
n1=int(input("n1:"))
n2=int(input("n2:"))
n3=int(input("n3:"))
lista=[n1,n2,n3]
print("lista original:", lista)
if n1<n2 and n2<n3:
print("ordenado:{}".format(lista))
else:
if n1>n2:
lista[0]=n2
lista[1]=n1
if n1>n3:
lista[1]=n3
lista[2]=n1
else:
if n3... |
"""
this python file is written orientated by the TUIO spezification
https://www.tuio.org/?specification
It supports only 2D Object|Blob|Cursor
Profile
|
---------------------
| | |
Object Cursor Blob
"""
from pythonosc.osc_message_builder import OscMessa... |
import asyncio
import logging
import pytest
from p2p.peer import PeerSubscriber
from p2p.protocol import Command
from trinity.protocol.eth.peer import ETHPeer
from trinity.protocol.eth.commands import GetBlockHeaders
from trinity.protocol.eth.requests import (
HeaderRequest,
NodeDataRequest,
)
from tests.tr... |
# coding: utf-8
"""
Control-M Services
Provides access to BMC Control-M Services # noqa: E501
OpenAPI spec version: 9.20.215
Contact: customer_support@bmc.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from ctm_api_cl... |
def coding_problem_10():
"""
Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds.
Example:
>>> coding_problem_10()
Before
Hello from thread
After
"""
from threading import Thread
import time
def delayed_execution(f, ms):
... |
#!/usr/bin/env python
from __future__ import print_function
from collections import OrderedDict
import re
# TODO nf-core: Add additional regexes for new tools in process get_software_versions
regexes = {
'nf-core/qtlquant': ['v_pipeline.txt', r"(\S+)"],
'Nextflow': ['v_nextflow.txt', r"(\S+)"],
'FastQC': [... |
# -*- coding: utf-8 -*-
"""
weatherapi
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
import weatherapi.models.forecastday
class Forecast(object):
"""Implementation of the 'Forecast' model.
TODO: type model description here.
Attributes:
forecastday... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://babel.edgewall.org/wiki/License.
#
# This software consists of v... |
"""
Insert datetime
"""
import sublime_plugin
import time
"""
date_format_en = '%Y-%m-%d' # 2016-01-01
date_format_fr = '%d/%m/%Y' # 01/01/2016
datetime_format_long_en = '%Y-%m-%d_%H-%M' # 2016-01-01_00-00
datetime_format_long_fr = '%H:%M %d/%m/%Y' # 00:00 01/01/2016
time_format_long ... |
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license... |
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
from django import forms
from django.utils.html import mark_safe, escape
class SimpleMarkdownEditor(forms.Widget):
"""
Code Editor built upon SimpleMDE
"""
def render(self, name, value, attrs=None, renderer=None):
template = '''
<textarea name="%(name)s" id="id_%(name)s"
... |
# encoding=utf-8
# python3.6
# bear_export_sync.py
# Developed with Visual Studio Code with MS Python Extension.
'''
# Markdown export from Bear sqlite database
Version 1.3.13, 2018-03-06 at 15:32 EST
github/rovest, rorves@twitter
See also: bear_import.py for auto import to bear script.
## Sync external updates:
Fi... |
from pathlib import Path
import os
import shutil
import numpy as np
import pandas as pd
from spikeinterface.core import load_extractor
from spikeinterface.extractors import NpzSortingExtractor
from spikeinterface.sorters import sorter_dict, run_sorters
from spikeinterface import WaveformExtractor
from spikeinterface.... |
import torch
import data as Data
import model as Model
import argparse
import logging
import core.logger as Logger
import core.metrics as Metrics
from tensorboardX import SummaryWriter
import os
import numpy as np
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config... |
import pytest
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
from django_scopes import scope
from pretalx.common.exceptions import SubmissionError
from pretalx.submission.models import Answer, Submission, SubmissionStates
from pretalx.submission.models.submission import ... |
##############################################################################
#
# Copyright (c) 2009 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... |
from unittest import TestCase
from flask import Flask
import cvapi
class TestFlaskApp(TestCase):
def test_create_app_deve_existir(self):
self.assertEqual(
hasattr(cvapi, 'create_app'),
True,
'app factory não existe'
)
def test_create_app_deve_ser_invocavel(... |
from conans import ConanFile, CMake, tools
from os import path
class RoseArrayTestConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
generators = "cmake"
def build(self):
cmake = CMake(self)
cmake.configure()
cmake.build()
def test(self):
self.run(path... |
import numpy as np
import pylab as plt
import mahotas as mh
class GaussianFilter:
def __init__(self,img,sigma = 1,windsize = 3):
self.img = mh.imread(img)
self.M,self.N = self.img.shape
self.windsize = windsize
self.sigma = sigma
self.gaussian_kernel = self.kernel()
... |
import conftest
import pytest
from msl.network import LinkedClient
from msl.examples.network import Echo
def test_linked_echo():
manager = conftest.Manager(Echo)
manager.kwargs['name'] = 'foobar'
link = LinkedClient('Echo', **manager.kwargs)
args, kwargs = link.echo(1, 2, 3)
assert len(args) ... |
from lib_classes.modules.utils_basic import *
from lib_classes.modules import utils_improc
import constants as const
import ipdb
st = ipdb.set_trace
from sklearn.decomposition import PCA
class SimpleNetBlock(tf.keras.Model):
def __init__(self,out_chans, blk_num,istrain):
super(SimpleNetBlock, self).__init... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
from util.config import config
from util.log import getLogger
from pubsub import Publisher
from slackclient import SlackClient
import time
from Queue import Queue
from Queue import Empty as QueueEmpty
from threading import Thread, Event
import re
import json
_log = getLogger('slack_reader')
class Reader(Thread):
def... |
# -*- coding: utf-8 -*-
# Copyright 2018 IBM.
#
# 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 agre... |
"""Support for Amcrest IP cameras."""
from datetime import timedelta
import logging
import threading
import aiohttp
from amcrest import AmcrestError, Http, LoginError
import voluptuous as vol
from homeassistant.auth.permissions.const import POLICY_CONTROL
from homeassistant.components.binary_sensor import DOMAIN as B... |
# File: Roman_to_decimal_number_system.py
# Description: Conversion Roman number to decimal number system
# Environment: PyCharm and Anaconda environment
#
# MIT License
# Copyright (c) 2018 Valentyn N Sichkar
# github.com/sichkar-valentyn
#
# Reference to:
# [1] Valentyn N Sichkar. Conversion Roman number to decimal n... |
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers as tfkl
from tensorflow_probability import distributions as tfd
from tensorflow.keras.mixed_precision import experimental as prec
import tools
from trxls import TrXL
class RSSM(tools.Module):
def __init__(self, stoch=30, deter=200, hid... |
class Solution:
def isMatch(self, s: str, p: str) -> bool:
ns, np = len(s), len(p)
dp = [[False] * (np + 1) for _ in range(ns + 1)]
dp[0][0] = True
for j in range(2, np + 1, 2):
if p[j - 1] == '*' and dp[0][j - 2]:
dp[0][j] = True
for i in range(1,... |
# Generated by Django 3.1.6 on 2021-04-26 23:37
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('emails', '0042_auto_20210423_0844'),
]
operations = [
migrations.RenameField(
model_name='emailstats',
old_name='deleted_att... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.async.base.exchange import Exchange
import hashlib
from ccxt.base.errors import ExchangeError
class ccex (Exchange):
def d... |
"""
GUI progressbar decorator for iterators.
Includes a default `range` iterator printing to `stderr`.
Usage:
>>> from tqdm.gui import trange, tqdm
>>> for i in trange(10):
... ...
"""
# future division is important to divide integers and get as
# a result precise floating numbers (instead of truncated int)
from _... |
from fv3gfs.util.buffer import BUFFER_CACHE
import pytest
import fv3gfs.util
import copy
@pytest.fixture
def dtype(numpy):
return numpy.float64
@pytest.fixture(params=[(1, 1), (3, 3)])
def layout(request, fast):
if fast and request.param == (1, 1):
pytest.skip("running in fast mode")
else:
... |
import functools
import typing
import h2.connection
import h2.events
from ..config import DEFAULT_TIMEOUT_CONFIG, TimeoutConfig, TimeoutTypes
from ..exceptions import ConnectTimeout, ReadTimeout
from ..interfaces import BaseReader, BaseWriter
from ..models import AsyncRequest, AsyncResponse
class HTTP2Connection:
... |
#!/usr/bin/env python
# Copyright (c) 2016 Orange and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
"""Define t... |
#
# author: Jungtaek Kim (jtkim@postech.ac.kr)
# last updated: February 8, 2021
#
import numpy as np
import pytest
from bayeso_benchmarks.inf_dim_ackley import *
class_fun = Ackley
TEST_EPSILON = 1e-5
def test_init():
obj_fun = class_fun(2)
with pytest.raises(TypeError) as error:
class_fun()
... |
# coding: utf-8
"""
Scubawhere API Documentation
This is the documentation for scubawhere's RMS API. This API is only to be used by authorized parties with valid auth tokens. [Learn about scubawhere](http://www.scubawhere.com) to become an authorized consumer of our API
OpenAPI spec version: 1.0.0
... |
import moai.utils.engine as mieng
import torch
import omegaconf.omegaconf
import typing
import logging
import inspect
import itertools
log = logging.getLogger(__name__)
__all__ = ['Metric']
class Metric(mieng.Single):
def __init__(self,
metrics: omegaconf.DictConfig,
**kwargs: typing.Mapping[str... |
from behave import *
from behave.log_capture import capture
import tempfile
import shutil
@capture()
def before_scenario(context, scenario):
context.working_directory = tempfile.mkdtemp()
# prepare some lists to store mentioned entities during steps
context.cells = []
context.files = []
context.f... |
import shutil
import pytest
from pathlib import Path
from atri.core.index.index import MIndex
from atri.core.primitives import MDoc, MCol
from atri.core.ranking.search import MSearcher
from atri.error import MupError
TEMPORARY_FOLDER = "./_temporary"
def create_temp_path():
p = Path(TEMPORARY_FOLDER)
if p.e... |
from itertools import accumulate
from kivy.uix.recyclelayout import RecycleLayout
from kivyx.uix.boxlayout import KXBoxLayout
__all__ = ('KXRecycleBoxLayout', )
class KXRecycleBoxLayout(RecycleLayout, KXBoxLayout):
_rv_positions = None
def __init__(self, **kwargs):
super().__init__(**kwargs)
... |
import pexpect
class Ser2NetConnection():
def __init__(self, device=None, conn_cmd=None, **kwargs):
self.device = device
self.conn_cmd = conn_cmd
def connect(self):
pexpect.spawn.__init__(self.device,
command='/bin/bash',
ar... |
import heapq
class Solution:
def tilingRectangle(self, n: int, m: int) -> int:
total_area = n * m
dp = [0] * (total_area + 1)
for i in range(1, total_area):
dp[i] = 1 + min(dp[i - k * k] for k in range(1, int(i ** 0.5) + 1))
height = [0] * m
pq = []
for i... |
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
def window():
app = QApplication(sys.argv)
win = QWidget()
button1 = QPushButton(win)
button1.setText("Show dialog!")
button1.move(50, 50)
butt... |
# The tests for the CI server - ci.sagrid.ac.za
# Run with testinfra --host=ansible@ci.sagrid.ac.za
# - make sure you have ssh credentials.
# - make sure the test starts with "test"
# Most tests require access to sensitive information, so use the
# --sudo option
def test_ssh_protocol(host):
file = host.file('/et... |
from werkzeug.exceptions import Unauthorized
from base64 import standard_b64decode
from .base import BaseAuth
class BasicAuth(BaseAuth):
class Unauthorized(Unauthorized):
def __init__(self, *args, **kwargs):
self.realm = kwargs.get('realm') or 'Authorization required'
super(Unauth... |
import copy
import json
import jsonpatch
from collections import deque
from enum import Enum
from .gu_common import OperationWrapper, OperationType, GenericConfigUpdaterError, JsonChange, PathAddressing
class Diff:
"""
A class that contains the diff info between current and target configs.
"""
def __i... |
"""
Incompressible Navier-Stokes flow around a cylinder in 2D.
"""
from __future__ import absolute_import
from builtins import object
from proteus import *
from proteus.default_p import *
import sys
try:
from . import step2d
except:
import step2d
reload(step2d)
try:
from .step2d import *
except:
from st... |
"""
The Salt loader is the core to Salt's plugin system, the loader scans
directories for python loadable code and organizes the code into the
plugin interfaces used by Salt.
"""
import contextlib
import logging
import os
import re
import time
import types
import salt.config
import salt.defaults.events
import salt.de... |
import calendar
import logging
from flask import render_template
from app.libs.utils import ObjectFromDict
from app.schema.widget import Widget
logger = logging.getLogger(__name__)
class DateWidget(Widget):
def render(self, answer_state):
if answer_state.input:
parts = answer_state.input.s... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
class CriterionIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?criterion\.com/films/(?P<id>[0-9]+)-.+'
_TEST = {
'url': 'http://www.criterion.com/films/184-le-samourai',
'md5': 'bc51beba55685509883a... |
import os
import pytest
from leapp.snactor.fixture import current_actor_context
from leapp.models import SELinuxModule, SELinuxModules, SELinuxCustom, SELinuxFacts, SELinuxRequestRPMs
from leapp.libraries.stdlib import api, run, CalledProcessError
from leapp.reporting import Report
TEST_MODULES = [
["400", "mock... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
#!/usr/bin/env python3
# Copyright (c) 2014-2019 The Btcavenue Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test node disconnect and ban behavior"""
import time
from test_framework.test_framework import Btcav... |
"""
A test suite for local matrices.
"""
import unittest
import NTPolySwig as nt
from scipy.io import mmwrite, mmread
class TestParameters:
'''An internal class for holding test parameters.'''
def __init__(self, rows, columns, sparsity):
'''Default constructor
@param[in] rows matrix rows.
... |
"""Importer decorators."""
import logging
from functools import wraps
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
class ImporterHook:
"""Interface for an importer hook."""
def __call__(self, importer, file, imported_entries, existing_entries):
"""Apply the hook and modify th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.