code stringlengths 281 23.7M |
|---|
class HeaderChainSyncer(Service):
def __init__(self, chain: AsyncChainAPI, db: BaseAsyncChainDB, peer_pool: ETHPeerPool, enable_backfill: bool=True, checkpoint: Checkpoint=None) -> None:
self.logger = get_logger('trinity.sync.header.chain.HeaderChainSyncer')
self._db = db
self._checkpoint = ... |
class SimpleEditor(Editor):
scrollable = True
selection = Event()
selected = Any()
activated = Event()
click = Event()
dclick = Event()
veto = Event()
refresh = Event()
def init(self, parent):
factory = self.factory
self._editor = None
if factory.editable:
... |
class LeadGenLegalContentCheckbox(AbstractCrudObject):
def __init__(self, fbid=None, parent_id=None, api=None):
self._isLeadGenLegalContentCheckbox = True
super(LeadGenLegalContentCheckbox, self).__init__(fbid, parent_id, api)
class Field(AbstractObject.Field):
id = 'id'
is_check... |
class OptionPlotoptionsNetworkgraphEvents(Options):
def afterAnimate(self):
return self._config_get(None)
def afterAnimate(self, value: Any):
self._config(value, js_type=False)
def checkboxClick(self):
return self._config_get(None)
def checkboxClick(self, value: Any):
sel... |
class TransportT(abc.ABC):
Consumer: ClassVar[Type[ConsumerT]]
Producer: ClassVar[Type[ProducerT]]
TransactionManager: ClassVar[Type[TransactionManagerT]]
Conductor: ClassVar[Type[ConductorT]]
Fetcher: ClassVar[Type[ServiceT]]
app: _AppT
url: List[URL]
driver_version: str
loop: async... |
def _run_ragout(args):
if (not os.path.isdir(args.out_dir)):
os.mkdir(args.out_dir)
debug_root = os.path.join(args.out_dir, 'debug')
debugger.set_debugging(args.debug)
debugger.set_debug_dir(debug_root)
debugger.clear_debug_dir()
out_log = os.path.join(args.out_dir, 'ragout.log')
_en... |
class Rule_Line_Trailing_Whitesapce(Style_Rule_Line):
def __init__(self):
super().__init__('trailing_whitespace', True)
self.mandatory = True
def apply(self, mh, cfg, filename, line_no, line):
if line.endswith(' '):
if (len(line.strip()) == 0):
mh.style_issue(... |
def start_ddp_workers(main, argv, num_workers: tp.Optional[int]=None):
import torch as th
world_size = (num_workers or th.cuda.device_count())
if (not world_size):
fatal('DDP is only available on GPU. Make sure GPUs are properly configured with cuda.')
sys.exit(1)
xp = main.get_xp(argv)
... |
class Solution2():
def kthSmallest(self, root: TreeNode, k: int) -> int:
def inorder(node):
if (node is None):
return
(yield from inorder(node.left))
(yield node.val)
(yield from inorder(node.right))
for (i, val) in enumerate(inorder(ro... |
def get_value_from_field_indentifier(field: BadgeFieldForms, ticket_holder: TicketHolder):
snake_case_field_identifier = to_snake_case(field.field_identifier)
try:
field.sample_text = getattr(ticket_holder, snake_case_field_identifier)
except AttributeError:
try:
field.sample_tex... |
class flow_monitor_request(stats_request):
version = 6
type = 18
stats_type = 16
def __init__(self, xid=None, flags=None, entries=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (flags != None):
self.flags = flags
else:... |
def prepare_env(binary=None):
import os
base_path = (Path(__file__).parent / 'staticanalysis/libfunctors/')
def check_for_libfunctors():
libfunctors = (base_path / 'libfunctors.so')
compile_script = './compile_functors.sh'
if libfunctors.is_file():
return
print('l... |
class JsHtmlButtonChecks(JsHtml):
def val(self):
return ''
def content(self):
return ''
def disable(self):
return JsObjects.JsObjects.get('\n ')
def add(self, data: Union[(str, primitives.JsDataModel, float, dict, list)], is_unique: bool=True, css_style: Optional[dict]=None,... |
class FloatNeighborhoodOutputChecker(doctest.OutputChecker):
posnum = '(?:[0-9]+[.][0-9]*|[.][0-9]+|[0-9]+)(?:e[+-]?[0-9]+)?'
re_spread = re.compile('\\b((?:-?{posnum}|array[(][^()]*[)]){posnum})\\b'.format(posnum=posnum))
def check_output(self, want, got, optionflags):
if (want == got):
... |
def lazy_import():
from fastly.model.pagination import Pagination
from fastly.model.pagination_links import PaginationLinks
from fastly.model.pagination_meta import PaginationMeta
from fastly.model.service_authorization_response_data import ServiceAuthorizationResponseData
from fastly.model.service_... |
def extractElliPhantomhive(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ('WATTT' in item['tags']):
return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=frag, post... |
class GlyphCoordinates(object):
def __init__(self, iterable=[]):
self._a = array.array('d')
self.extend(iterable)
def array(self):
return self._a
def zeros(count):
g = GlyphCoordinates()
g._a.frombytes(bytes(((count * 2) * g._a.itemsize)))
return g
def cop... |
class ValidatePkpTestCase(TestCase):
def test__validate_pkp_positive(self):
private_key_paths = mock.Mock()
private_key_paths.read_all = mock.Mock(return_value=[])
_validate_pkp(private_key_paths)
private_key_paths.read_all.assert_called_once()
def test__validate_pkp_negative(sel... |
def interrupt_thread(thread, exctype=OSError):
if (not CPYTHON):
return False
if ((thread is None) or (not thread.is_alive())):
return True
import ctypes
tid = ctypes.c_long(thread.ident)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if (res == ... |
def verify_link(link):
global main_domain
global host_name
global url_scheme
global link_full_path
global emails
global debug
global verbose
global splitters
try:
if debug:
print('\t\t\t\t\t> Entering to verify_link function')
for i in splitters:
... |
def pql_fmt(s: T.string):
_s = cast_to_python_string(s)
tokens = re_split('\\$\\w+', _s)
string_parts = []
for (m, t) in tokens:
if m:
assert (t[0] == '$')
obj = get_var(t[1:])
inst = cast_to_instance(obj)
as_str = cast(inst, T.string)
... |
def extractRookietranslationsBlogspotCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, ... |
class Property():
def __init__(self, json):
self.name = json['name']
self.attributes_string = json['attributes_string']
self.attributes = json['attributes']
def prettyPrintString(self):
attrs = []
if ('N' in self.attributes):
attrs.append('nonatomic')
... |
def validate(schema: typing.Union[(dict, str, bytes)], format: str=None, encoding: str=None):
if (not isinstance(schema, (dict, str, bytes))):
raise ValueError(f'schema must be either str, bytes, or dict.')
if (format not in FORMAT_CHOICES):
raise ValueError(f'format must be one of {FORMAT_CHOIC... |
def group_ordered(list_in):
if (list_in is None):
return None
order_list = make_order_list(list_in)
current = 0
for item in order_list:
search = (current + 1)
while True:
try:
if (list_in[search] != item):
search += 1
... |
def test_histogram(elasticapm_client, prometheus):
metricset = PrometheusMetrics(MetricsRegistry(elasticapm_client))
histo = prometheus_client.Histogram('histo', 'test histogram', buckets=[1, 10, 100, float('inf')])
histo_with_labels = prometheus_client.Histogram('histowithlabel', 'test histogram with label... |
def logout_oauth_client(authorization: str=Security(oauth2_scheme), db: Session=Depends(get_db)) -> Optional[ClientDetail]:
if (authorization is None):
raise AuthenticationError(detail='Authentication Failure')
try:
token_data = json.loads(extract_payload(authorization, CONFIG.security.app_encry... |
('cuda.permute.gen_function')
def gen_function(func_attrs: Dict[(str, Any)]) -> str:
func_name = func_attrs['name']
x = func_attrs['inputs'][0]
rank = x._rank()
custom_libs = Target.current().get_custom_libs(os.path.dirname(__file__), 'permute.cuh')
dtype = x.dtype()
assert (dtype in ('float16',... |
def test():
assert Span.has_extension('to_html'), 'Hast du die Span-Erweiterung korrekt registriert?'
ext = Span.get_extension('to_html')
assert (ext[1] is not None), 'Hast du die Methode korrekt angegeben?'
assert ('method=to_html' in __solution__), 'Hast du die Funktion to_html als Methode angegeben?'... |
class Editor(QMainWindow):
finished_signal = Signal(list)
def __init__(self, filenames, search_text='', master_name='', parent=None):
QMainWindow.__init__(self, parent)
self.setObjectName(('Editor - %s' % utf8(filenames)))
self.setAttribute(Qt.WA_DeleteOnClose, True)
self.setWind... |
class Menus():
def __init__(self, ui):
self.page = ui.page
def top(self, data: List[dict]=None, color: str=None, width: Union[(tuple, int)]=(100, '%'), height: Union[(tuple, int)]=(30, 'px'), html_code: str=None, helper: str=None, options: dict=None, profile: Union[(bool, dict)]=None):
width = A... |
class Test_loopback_reply(unittest.TestCase):
def setUp(self):
self.md_lv = 1
self.version = 1
self.opcode = cfm.CFM_LOOPBACK_REPLY
self.flags = 0
self.first_tlv_offset = cfm.loopback_reply._TLV_OFFSET
self.transaction_id = 12345
self.tlvs = []
self.en... |
class Header():
parent_hash: Hash32
ommers_hash: Hash32
coinbase: Bytes20
state_root: Hash32
transactions_root: Hash32
receipt_root: Hash32
bloom: Bytes256
difficulty: Uint
number: Uint
gas_limit: Uint
gas_used: Uint
timestamp: U256
extra_data: Bytes
mix_digest: B... |
class UrlComponentCatalogConnector(ComponentCatalogConnector):
REQUEST_TIMEOUT = 30
def get_catalog_entries(self, catalog_metadata: Dict[(str, Any)]) -> List[Dict[(str, Any)]]:
return [{'url': url} for url in catalog_metadata.get('paths')]
def get_entry_data(self, catalog_entry_data: Dict[(str, Any)... |
def _mock_gcp_resource_iter(resource_type):
resource = Resource(cai_resource_name=resource_type.get('resource').get('cai_resource_name'), cai_resource_type=resource_type.get('resource').get('cai_resource_type'), full_name=resource_type.get('resource').get('full_name'), type_name=resource_type.get('resource').get('t... |
def test_staticfiles_config_check_occurs_only_once(tmpdir, test_client_factory):
app = StaticFiles(directory=tmpdir)
client = test_client_factory(app)
assert (not app.config_checked)
with pytest.raises(HTTPException):
client.get('/')
assert app.config_checked
with pytest.raises(HTTPExcep... |
class Solution():
def longestOnes(self, nums: List[int], K: int) -> int:
mmax = 0
start = 0
zeros = 0
for (i, n) in enumerate(nums):
if (n == 1):
mmax = max(mmax, ((i - start) + 1))
else:
zeros += 1
while (zeros ... |
def extractDeeyosarecommendationWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('demonssweetheart', "demon's sweetheart", 'translated'), ("demon's sweetheart", "dem... |
def collate_fn_mspecNquant(batch):
r = hparams.outputs_per_step
seq_len = 4
max_offsets = [(x[1].shape[0] - seq_len) for x in batch]
mel_lengths = [x[1].shape[0] for x in batch]
mel_offsets = [np.random.randint(0, offset) for offset in max_offsets]
sig_offsets = [int((((offset * hparams.frame_sh... |
def serve_udp(engine=None, port=9007, logto=sys.stdout):
from mayavi import mlab
e = (engine or mlab.get_engine())
proto = M2UDP()
proto.engine = e
proto.scene = e.current_scene.scene
proto.mlab = mlab
if (logto is not None):
log.startLogging(logto)
log.msg('Serving Mayavi2 UDP s... |
def get_one_column_drift(*, current_feature_data: SparkSeries, reference_feature_data: SparkSeries, datetime_column: Optional[str], column: ColumnName, options: DataDriftOptions, data_definition: DataDefinition, column_type: ColumnType) -> ColumnDataDriftMetrics:
if (column_type not in (ColumnType.Numerical, Column... |
def extractWuxiadreamCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Douluo Continent 2.5 - Legend of The Divine Realm', 'Douluo Continent 2.5 - Legend of The Divine Realm'... |
.parametrize('argument, expected_param_name, default_value, param_type, expected_param_type, description', [('--option', 'option', 'value', str, 'str', 'An option argument'), ('-option', 'option', 'value', str, 'str', 'An option argument'), ('--num-gpu', 'num_gpu', 1, int, 'int', 'Number of GPUS'), ('--num_gpu', 'num_g... |
class OptionPlotoptionsBoxplotSonificationTracksMappingHighpassFrequency(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):... |
.parametrize('app,expectation', [(app, pytest.raises(MultiPartException)), (Starlette(routes=[Mount('/', app=app)]), does_not_raise())])
def test_missing_boundary_parameter(app, expectation, test_client_factory) -> None:
client = test_client_factory(app)
with expectation:
res = client.post('/', data=b'C... |
def _setup_teb_x64(uc: Uc, process_info: ProcessController) -> None:
MSG_IA32_GS_BASE =
teb_addr =
peb_addr =
uc.mem_map(teb_addr, process_info.page_size, (UC_PROT_READ | UC_PROT_WRITE))
uc.mem_map(peb_addr, process_info.page_size, (UC_PROT_READ | UC_PROT_WRITE))
uc.mem_write((teb_addr + 48),... |
def lab_to_xyz(lab: Vector, white: VectorLike) -> Vector:
(l, a, b) = lab
fy = ((l + 16) / 116)
fx = ((a / 500) + fy)
fz = (fy - (b / 200))
xyz = [((fx ** 3) if (fx > EPSILON3) else (((116 * fx) - 16) / KAPPA)), ((fy ** 3) if (l > KE) else (l / KAPPA)), ((fz ** 3) if (fz > EPSILON3) else (((116 * fz... |
def test_Image(base):
with pytest.raises(EtypeCastError):
Etype.Image(base.id, ['/tmp/notafile.txt'])
with pytest.raises(EtypeCastError):
Etype.Image(base.id, ['/tmp/nonexistent_image.png'])
with pytest.raises(EtypeCastError):
Etype.Image(base.id, [base.im1, base.im2])
im1 = Etyp... |
.filterwarnings('ignore:Call to deprecated function compile_uri_template')
class TestUriTemplates():
.parametrize('value', (42, falcon.App))
def test_string_type_required(self, value):
with pytest.raises(TypeError):
routing.compile_uri_template(value)
.parametrize('value', ('this', 'this... |
def test_dt_evaluation(dummy_titanic_dt, dummy_titanic):
model = dummy_titanic_dt
(X_train, y_train, X_test, y_test) = dummy_titanic
pred_train = model.predict(X_train)
pred_train_binary = np.round(pred_train)
acc_train = accuracy_score(y_train, pred_train_binary)
auc_train = roc_auc_score(y_tra... |
class BasicErrorSelector(Selector):
out_etype = Etype.Any
def __init__(self, *args):
super().__init__(*args)
self.retryCount = 0
def index(self, config) -> LocalElementsIndex:
error = (config['error'] if ('error' in config) else '')
if (error == 'index'):
raise Se... |
class Person(HasTraits):
first_name = Str()
last_name = Str()
age = Range(0, 120)
misc = Instance(Spec)
gen_group = Group(Item(name='first_name'), Item(name='last_name'), Item(name='age'), label='General Info', show_border=True)
spec_group = Group(Group(Item(name='misc', style='custom'), show_la... |
class EnumValue(EditableValue):
values = List()
format = Callable(str, update_value_type=True)
colors = Callable(None, update_value_type=True)
images = Callable(None, update_value_type=True)
def is_valid(self, model, row, column, value):
return (value in self.values)
def has_text(self, m... |
def _get(namespace: Sequence[str]) -> Any:
global REGISTRY
if (not all((isinstance(name, str) for name in namespace))):
raise ValueError(f'Invalid namespace. Expected tuple of strings, but got: {namespace}')
namespace = tuple(namespace)
if (namespace not in REGISTRY):
raise RegistryError... |
class JsonDataset():
def __init__(self, args):
self.args = args
name = args.dataset
ds_im_dir = args.dataset_dir
ds_ann = args.dataset_ann
full_datasets = {}
if ((ds_im_dir is not None) and (ds_ann is not None)):
full_datasets[name] = {IM_DIR: ds_im_dir, A... |
def extractPrinceRevolution(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Romance RPG', 'Romance RPG', 'translated'), ('The Legend of Sun Knight', 'The Legend of Sun Knight',... |
def extractAllntrHomeBlog(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type) in tag... |
class Ui_OrganiserDialog(object):
def setupUi(self, OrganiserDialog):
OrganiserDialog.setObjectName('OrganiserDialog')
OrganiserDialog.resize(525, 536)
sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Policy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.se... |
class ClientHandlers():
async def Handler_SpeakOnWorldRequest(player_id, request):
logging.info(f'Handler_SpeakOnWorldRequest:{player_id}, request:{request} ')
GamePlayerMgr().player_speak_on_world(player_id, request.name, request.content)
async def Handler_PlayerMoveRequest(player_id, request):... |
class SimpleSliderEditor(BaseRangeEditor):
low = Any()
high = Any()
ui_changing = Bool(False)
def init(self, parent):
factory = self.factory
if (not factory.low_name):
self.low = factory.low
if (not factory.high_name):
self.high = factory.high
self... |
class LEDBackpack():
i2c = None
__HT16K33_REGISTER_DISPLAY_SETUP = 128
__HT16K33_REGISTER_SYSTEM_SETUP = 32
__HT16K33_REGISTER_DIMMING = 224
__HT16K33_ADDRESS_KEY_DATA = 64
__HT16K33_BLINKRATE_OFF = 0
__HT16K33_BLINKRATE_2HZ = 1
__HT16K33_BLINKRATE_1HZ = 2
__HT16K33_BLINKRATE_HALFHZ ... |
def _slice_between_surfaces(this, cube, sampling, other, other_position, zrange, ndiv, mask, attrlist, mthreshold, snapxy, showprogress=False, deadtraces=True):
npcollect = []
zincr = (zrange / float(ndiv))
zcenter = this.copy()
zcenter.slice_cube(cube, sampling=sampling, mask=mask, snapxy=snapxy, deadt... |
class TestGetSizes(unittest.TestCase):
def test_get_sizes_with_stepfactor(self):
beginSize = 32
endSize = 1024
stepFactor = 2
correct_list = [32, 64, 128, 256, 512, 1024]
result_list = comms_utils.getSizes(beginSize, endSize, stepFactor, stepBytes=0)
self.assertEqual(... |
def extractZazaTranslations(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ('WATTT' in item['tags']):
return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=frag, pos... |
def _import_irap_binary_purepy(mfile, values=True):
logger.info('Enter function %s', __name__)
if mfile.memstream:
mfile.file.seek(0)
buf = mfile.file.read()
else:
with open(mfile.file, 'rb') as fhandle:
buf = fhandle.read()
hed = unpack('>3i6f3i3f10i', buf[:100])
... |
('cuda.where.func_decl')
def gen_function_decl(func_attrs: Dict[(str, Any)]) -> str:
(_, input_tensor, other_tensor) = func_attrs['args']
backend_spec = CUDASpec()
return FUNC_DECL.render(func_name=func_attrs['name'], prefix=backend_spec.prefix, index_type=backend_spec.index_type, input_tensor_is_a_const_nu... |
def get_opennem_capacity_data(session: Session) -> dict[(str, Any)]:
r: Response = session.get(CAPACITY_URL)
data = r.json()
capacity_df = pd.json_normalize(data)
capacity_df = capacity_df.loc[(capacity_df['dispatch_type'] == 'GENERATOR')]
capacity_df = capacity_df.loc[(capacity_df['status.code'] ==... |
def SetLayer(kwargs: dict) -> OutgoingMessage:
compulsory_params = ['id', 'layer']
optional_params = []
utility.CheckKwargs(kwargs, compulsory_params)
msg = OutgoingMessage()
msg.write_int32(kwargs['id'])
msg.write_string('SetLayer')
msg.write_int32(kwargs['layer'])
return msg |
def print_adposition_stats(logfile):
print('surcface', 'left', 'poss', 'right', 'none', 'total', sep='\t', file=logfile)
for (lemma, comps) in adposition_complements.items():
totals = {'all': 0}
lefts = {'all': 0}
poss = 0
rights = {'all': 0}
nones = 0
for case in... |
class GridContainerExample(HasTraits):
plot = Instance(GridPlotContainer)
traits_view = View(Item('plot', editor=ComponentEditor(), show_label=False), width=1000, height=600, resizable=True)
def _plot_default(self):
container = GridPlotContainer(shape=(2, 3), spacing=(10, 5), valign='top', bgcolor='... |
def test_schema_migration_remove_field():
schema = {'type': 'record', 'name': 'test_schema_migration_remove_field', 'fields': [{'name': 'test', 'type': 'string'}]}
new_schema = {'type': 'record', 'name': 'test_schema_migration_remove_field', 'fields': []}
new_file = BytesIO()
records = [{'test': 'test'}... |
class Call(expr):
_fields = ('func', 'args', 'keywords', 'starargs', 'kwargs')
_attributes = ('lineno', 'col_offset')
def __init__(self, func, args=[], keywords=[], starargs=None, kwargs=None, lineno=0, col_offset=0, **ARGS):
expr.__init__(self, **ARGS)
self.func = func
self.args = l... |
class OptionSeriesLollipopZones(Options):
def className(self):
return self._config_get(None)
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get(None)
def color(self, text: str):
self._config(text, js_type=False)
... |
class GeoFieldWrapper(str):
_rule_parens = re.compile('^(\\(+)(?:.+)$')
_json_geom_map = {'POINT': 'Point', 'LINESTRING': 'LineString', 'POLYGON': 'Polygon', 'MULTIPOINT': 'MultiPoint', 'MULTILINESTRING': 'MultiLineString', 'MULTIPOLYGON': 'MultiPolygon'}
def __new__(cls, value, *args: Any, **kwargs: Any):
... |
def YlGn(range, **traits):
_data = dict(red=[(0.0, 1.0, 1.0), (0.125, 0., 0.), (0.25, 0., 0.), (0.375, 0., 0.), (0.5, 0., 0.), (0.625, 0., 0.), (0.75, 0., 0.), (0.875, 0.0, 0.0), (1.0, 0.0, 0.0)], green=[(0.0, 1.0, 1.0), (0.125, 0., 0.), (0.25, 0., 0.), (0.375, 0., 0.), (0.5, 0., 0.), (0.625, 0., 0.), (0.75, 0., 0.... |
def process_files(options):
mapping_dict = emaps.fastq_emoji_map
mapping_text = ''
mapping_default = ':heart_eyes:'
mapping_spacer = ' '
if options.custom:
with open(options.custom) as f:
mapping_dict = ast.literal_eval(f.read())
mapping_text = ' (custom)'
... |
def get_manifest_list(manifests_dir: str) -> List[str]:
yml_endings = ['yml', 'yaml']
if (isfile(manifests_dir) and (manifests_dir.split('.')[(- 1)] in yml_endings)):
return [manifests_dir]
manifest_list = []
for yml_ending in yml_endings:
manifest_list += glob.glob(f'{manifests_dir}/**/... |
def test_colors_whole_table_with_automatic_widths(data, header, footer, fg_colors, bg_colors):
result = table(data, header=header, footer=footer, divider=True, fg_colors=fg_colors, bg_colors=bg_colors)
if SUPPORTS_ANSI:
assert (result == '\n\x1b[48;5;2mCOL A \x1b[0m \x1b[38;5;3;48;5;23mCOL B\x... |
class ValveUnusedMeterTestCase(ValveTestBases.ValveTestNetwork):
CONFIG = ('\nmeters:\n unusedmeter:\n meter_id: 1\n entry:\n flags: "KBPS"\n bands:\n [\n {\n type: "DROP",\n rate: 1\n ... |
def test_cell_facet_subdomains(square, forms):
from operator import add
V = FunctionSpace(square, 'CG', 1)
v = TestFunction(V)
u = TrialFunction(V)
forms = list(map(eval, forms))
full = reduce(add, forms)
full_mat = assemble(full).M.values
part_mat = reduce(add, map((lambda x: assemble(x... |
def event_info_from_pr_comment(data, base_url):
if (data['msg']['pullrequest']['status'] != 'Open'):
log.info('Pull-request not open, discarding.')
return False
if (not data['msg']['pullrequest']['comments']):
log.info("This is most odd, we're not seeing comments.")
return False
... |
.django_db
def test_program_activity_fresh_load():
call_command('load_program_activity', 'usaspending_api/references/tests/data/program_activity.csv')
expected_results = {'count': 6, 'program_activity_name_lowercase_found': False}
actual_results = {'count': RefProgramActivity.objects.count(), 'program_activ... |
def process_rule(lines, rule):
doc = rule.__class__.__doc__.splitlines()
short_name = doc[0].strip()
assert (doc[1].strip() == '')
sections = [[]]
in_code = False
for l in doc[2:]:
if (l.strip() == '```'):
in_code = (not in_code)
if in_code:
sectio... |
def test_compound_pair_of_lists():
adapter = GenericInputAdapter(input_type='compound', input_shape='pair of lists')
inp_csv = os.path.abspath(os.path.join(inputs_path, 'compound_pair_of_lists.csv'))
inp_json = os.path.abspath(os.path.join(inputs_path, 'compound_pair_of_lists.json'))
inp_py = compound_p... |
def save_checkpoint(model, optimizer, step, checkpoint_dir, epoch, spk_flag=None, ema=None):
step = str(step).zfill(7)
checkpoint_path = join(checkpoint_dir, 'checkpoint_step{}.pth'.format(step))
torch.save({'state_dict': model.state_dict(), 'optimizer': optimizer.state_dict(), 'global_step': step, 'global_... |
class PrometheusAPI():
def __init__(self):
self.verify = False
self.session = None
self.prometheus_url = GlobalAttrs.env_prometheus_server
self.prometheus_url_query = (self.prometheus_url + '/api/v1/query')
def get_session(self):
try:
session = requests.Sessio... |
class TransformFactory(ReprMixIn):
_modules: Dict[(str, _TransformFactoryModule)] = {}
_instances: Dict[(str, Any)] = {}
def __init__(self) -> None:
raise InternalError('TransformFactory constructor called.')
def _import_modules(cls, config: Config, modules: ConfigList) -> None:
for (ind... |
def direct(twitch_id):
print(twitch_id)
channel = twitch_id.split('')[0]
video_id = twitch_id.split('')[1]
command = ['yt-dlp', '-f', 'best', '--no-warnings', ' '--get-url']
twitch_url = w.worker(['yt-dlp', '-f', 'best', '--no-warnings', ' '--get-url']).output()
if ('ERROR' in twitch_url):
... |
class AffiliationAddressModelTrainingDataGenerator(AbstractDocumentModelTrainingDataGenerator):
def get_main_model(self, document_context: TrainingDataDocumentContext) -> Model:
return document_context.fulltext_models.affiliation_address_model
def iter_model_layout_documents(self, layout_document: Layou... |
def template_hook(name, silent=True, is_markup=True, **kwargs):
try:
hook = getattr(current_app.pluggy.hook, name)
result = TemplateEventResult(hook(**kwargs))
except AttributeError:
if silent:
return ''
raise
if is_markup:
return Markup(result)
return... |
class OptLegend(Options):
def type(self):
return self._config_get()
def type(self, text):
self._config(text)
def direction(self):
return self._config_get()
def direction(self, text):
self._config(text)
def orient(self):
return self._config_get()
def orient... |
class CssToastTimePickerSelect(CssStyle.Style):
classname = 'tui-timepicker-select'
_focus = {'outline': 0}
def customize(self):
self.focus.css({'border-color': self.page.theme.notch()})
self.css({'height': ('%spx' % Defaults.LINE_HEIGHT), 'padding': '0 0 0px 9px'}, important=True) |
def test_assert_dataclassjsonmixin_type():
pt = SchemaArgsAssert
lt = TypeEngine.to_literal_type(pt)
gt = TypeEngine.guess_python_type(lt)
pv = SchemaArgsAssert(x=ArgsAssert(x=3, y='hello'))
DataclassTransformer().assert_type(gt, pv)
DataclassTransformer().assert_type(SchemaArgsAssert, pv)
c... |
class Entity(object):
def get_specification(cls):
entity_type = ((cls.__module__ + '/') + cls.__qualname__)
spec = cls.pre_make(entity_type, entity_type)
spec.initialize(cls)
return spec
def make(cls, *args: Any, **kwargs: Any):
pass
def info(cls, method: Optional[Uni... |
def test_call_with_context_kwargs():
provider = providers.Factory(Example, init_arg1=1)
instance1 = provider(init_arg2=22)
assert (instance1.init_arg1 == 1)
assert (instance1.init_arg2 == 22)
instance2 = provider(init_arg1=11, init_arg2=22)
assert (instance2.init_arg1 == 11)
assert (instance... |
class RevisionsMap(object):
def __init__(self, app, generator):
self.app = app
self._generator = generator
def _revision_map(self):
rmap = {}
heads = OrderedSet()
_real_heads = OrderedSet()
self.bases = ()
self._real_bases = ()
for revision in self... |
class TestGetMultiAddressCommandConnectionIdURIAgentOverridesPositive(AEATestCaseEmpty):
def test_run(self, *mocks):
self.add_item('connection', str(P2P_CONNECTION_PUBLIC_ID))
self.generate_private_key(FetchAICrypto.identifier)
self.add_private_key(FetchAICrypto.identifier, connection=True)
... |
def extractBeanylandCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('fight for love and peace', 'Fight for Peace and Love', 'translated'), ('im bearing my love rivals child'... |
class SysDescr(object):
name = (1, 3, 6, 1, 2, 1, 1, 1, 0)
def __eq__(self, other):
return (self.name == other)
def __ne__(self, other):
return (self.name != other)
def __lt__(self, other):
return (self.name < other)
def __le__(self, other):
return (self.name <= other... |
class AugInput():
def __init__(self, image: Union[(np.ndarray, torch.Tensor)], *, boxes: Optional[Union[(np.ndarray, torch.Tensor, Boxes)]]=None, sem_seg: Optional[Union[(np.ndarray, torch.Tensor)]]=None):
self.image = image
self.boxes = boxes
self.sem_seg = sem_seg
def transform(self, t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.