content stringlengths 5 1.05M |
|---|
from numpy import random as r
class Dice(object):
"""
Simulate the rolling of a dice
Parameters
----------
NONE
Attributes
----------
n_rolls_ : int
Number of rolls for the dice
result_ : array, shape = [2]
Most recent outcome of the roll of two di... |
# -*- coding: UTF-8 -*-
# =========================================================================
# Copyright (C) 2017 Yunify, Inc.
# -------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this work except in compli... |
from abc import ABC, abstractmethod
from pydantic import BaseModel, create_model
from typing_extensions import Literal
from rastervision.v2.core import _registry
def register_config(type_hint, version=0, upgraders=None):
def _register_config(cls):
if version > 0:
cls = create_model(
... |
import setuptools
import milli_piyango
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name=milli_piyango.__name__,
version=milli_piyango.__version__,
author="M. Olcay TERCANLI",
author_email="molcaytercanli@gmail.com",
description="A package for getting lotte... |
import Bio, pandas
lengths = map(len, Bio.SeqIO.parse('/home/jit/Downloads/setu/see_long/mapped.long.fasta', 'fasta'))
pandas.Series(lengths).hist(color='gray', bins=1000)
|
# BEGIN-SCRIPT-BLOCK
#
# Script-Filter:
# $vendor eq "Cisco" and $model like /ASA/
#
# END-SCRIPT-BLOCK
from infoblox_netmri.easy import NetMRIEasy
# This values will be provided by NetMRI before execution
defaults = {
"api_url": api_url,
"http_username": http_username,
"http_password": http_password,... |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any... |
class Solution:
def firstMissingPositive(self, nums):
for i in range(len(nums)):
while 0 <= nums[i] < len(nums) and nums[nums[i] - 1] != nums[i]:
tmp = nums[i] - 1
nums[i], nums[tmp] = nums[tmp], nums[i]
for i, v in enumerate(nums):
if v != i +... |
import Pyro4
import os
import json
import base64
class Client:
def __init__(self, host, port, identifier = "main-"):
self.host = host
self.port = port
self.identifier = identifier
self.objects = dict()
def Start(self, remoteObjects):
for obj in remoteObjects:
... |
import json
import os
import random
import scipy.io
import codecs
from collections import defaultdict
class BasicDataProvider:
def __init__(self, dataset):
print ('Initializing data provider for dataset %s...' % (dataset, ))
# !assumptions on folder structure
self.dataset_root = os.path.join('data', dat... |
import torch
from torch import nn
from torch.nn import functional as F
class IDRLoss(nn.Module):
def __init__(self, idr_rgb_weight, sg_rgb_weight, eikonal_weight, mask_weight, alpha,
r_patch=-1, normalsmooth_weight=0., loss_type='L1'):
super().__init__()
self.idr_rgb_weight = idr_... |
from . import id_request
|
# !/user/bin/python
# -*- coding: utf-8 -*-
#- Author : (DEK) Devendra Kavthekar
# Write a program which can filter() to make a list whose elements are
# even number between 1 and 20 (both included).
# Hints:
# Use filter() to filter elements of a list.
# Use lambda to define anonymous functions.
def do(start_numbe... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
___ ___ __ ___ __ __ __
/' __` __`\ /'__`\ / __`\/\ \/\ \/\ \\
/\ \/\ \/\ \/\ __//\ \L\ \ \ \_/ \_/ \\
\ \_\ \_\ \_\ \____\ \____/\ \___x___/'
\/_/\/_/\/_/\/____/\/___/ \/__//__/
Editor-agnostic markdown live preview server.
Usage: meow ... |
#!/usr/bin/env python
import numpy
import pandas
from copy import copy, deepcopy
import rpy2.robjects as ro
from rpy2.robjects import r, pandas2ri, numpy2ri
from rpy2.robjects.conversion import localconverter
pandas2ri.activate()
numpy2ri.activate()
r.library("lme4")
class lmer(object):
"""
Mixed effect regre... |
def benchmark(func_to_decorate):
import time
def wrapper():
start = time.time()
func_to_decorate()
end = time.time()
print(f"Time: {end - start}")
return wrapper
@benchmark
def fetch_web_page():
import requests
webpage = requests.get("https://google.com")
pr... |
import urllib3
from appwrite.client import Client
from appwrite.services.users import Users
from appwrite.services.database import Database
from appwrite.services.storage import Storage
import datetime
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# Helper method to print green colored output.... |
# __init__.py
# ALS 2017/05/11
__all__ = ['sdssobj']
from . import sdssobj
import imp
imp.reload(sdssobj)
from .sdssobj import sdssObj
|
# Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""
Add url and reference_url columns
Create Date: 2016-05-13 13:51:06.534663
"""
# disable Invalid constant name pylint warning for mandatory Alembic variables.
# pylint: disable=invalid-name
import sqlal... |
# -*- coding:utf-8 -*-
import sys
import os
import argparse
import numpy as np
from PIL import Image, ImageEnhance, ImageOps, ImageFile
# C:\Users\14542\Desktop\t
def main(args):
images_inputpath = os.path.join(args.input_dir, 'val_img')
gtpath_inputpath = os.path.join(args.input_dir, 'val_gt')
... |
###
# Copyright (c) SpiderDave
# Copyright (c) 2020, oddluck <oddluck@riseup.net>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyr... |
import os, sys, time
path = os.path.join(os.path.dirname(__file__), '../lib/')
sys.path.insert(0, path)
from thrift.transport import THttpClient
from thrift.protocol import TCompactProtocol
from curve import LineService
from curve.ttypes import *
class Poll:
client = None
auth_query_path = "/api/v4/TalkService... |
from setuptools import setup
setup(
name = "Catnap",
version = "0.4.5",
description = "A script for running integration tests against RESTful/HTTP-based interfaces",
author = "Yusuf Simonson",
url = "http://github.com/dailymuse/catnap",
packages = [
"catnap",
],
script... |
from .models import MemberData
from ..enums import Permission
class IMemberDataProvider:
def get_basic_data_by_id(self, server_id: str, user_id: str) -> MemberData:
raise NotImplementedError
def get_basic_data_by_name(self, server_id: str, name: str) -> MemberData:
raise NotImplementedError
... |
# terrascript/data/kvrhdn/honeycombio.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:18:50 UTC)
import terrascript
class honeycombio_datasets(terrascript.Data):
pass
class honeycombio_query(terrascript.Data):
pass
class honeycombio_trigger_recipient(terrascript.Data):
pass
__all__... |
# Signals here
|
from Node import Node
from collections import deque
def search(state, goal_state, yield_after):
cur_node = Node(state)
explored = set()
queue = deque([cur_node])
counter = 0
while len(queue) != 0:
cur_node = queue.popleft()
explored.add(cur_node.map)
if cur_node.is_goal(goa... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
### This file is a part of the Syncpy library.
### Copyright 2015, ISIR / Universite Pierre et Marie Curie (UPMC)
### Main contributor(s): Giovanna Varni, Marie Avril,
### syncpy@isir.upmc.fr
###
### This software is a computer program whose for investigating
### synchrony in a fast and exhaustive way.
###
### This ... |
# coding=utf-8
# Copyright 2020 The TensorFlow Datasets 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 appl... |
from regression_tests import *
class Test1(Test):
settings=TestSettings(
tool='fileinfo',
input='8b280f2b7788520de214fa8d6ea32a30ebb2a51038381448939530fd0f7dfc16',
args='--json --verbose'
)
def test_certificates(self):
assert self.fileinfo.succeeded
self.assertEqual(self.fileinfo.output["certificateTable... |
#! /usr/bin/env python3
import sys
import math
import glob
from sweet.postprocessing.pickle_SphereDataPhysicalDiff import *
from mule.exec_program import *
p = pickle_SphereDataPhysicalDiff()
|
from server.server import Server
from common.command import Command
from sys import argv
from server.handlers import handler_map, check_state
from server.handlers import unknown_handler, invalid_handler
def handle_message(serv, usr, data):
try:
msg = Command(data)
(state, handler) = handler_map[msg.command]
if... |
from flask_restful import Resource, reqparse
from flask_jwt_extended import get_jwt_identity, jwt_required
from constants import userConstants as UserConstants
import service.userCreateUpdateService as UserCreateUpdateService
class UserEmailUpdateResource(Resource):
parser = reqparse.RequestParser()
for field... |
import plotoptix, os, zipfile
from plotoptix._load_lib import BIN_PATH, PLATFORM
from plotoptix.install import download_file_from_google_drive
def install_denoiser():
"""Install denoiser binaries.
"""
print("Downloading denoiser binaries...")
if PLATFORM == "Windows":
id = "1qLyR7c_upFJKxZDKQC... |
class Solution:
def candy(self, ratings):
"""
:type ratings: List[int]
:rtype: int
"""
ret = [1 for _ in range(len(ratings))]
for i in range(len(ratings) - 1):
if ratings[i] < ratings[i + 1] and ret[i] >= ret[i + 1]:
ret[i + 1] = ret[i] + 1... |
# -*- coding: utf-8 -*-
from .specialized import (
BRAINSCut,
BRAINSROIAuto,
BRAINSConstellationDetector,
BRAINSCreateLabelMapFromProbabilityMaps,
BinaryMaskEditorBasedOnLandmarks,
BRAINSMultiSTAPLE,
BRAINSABC,
ESLR,
)
|
from uribuilder.uri import HIER_PART, URI, SCHEME, QUERY
def test_scheme():
assert SCHEME.match("http")
def test_query():
assert QUERY.match("a=1&b=1")
def test_hier_part_regex():
assert HIER_PART.match("//www.google.it/")
assert HIER_PART.match("//foo.com/blah_blah")
def test_valid_uri():
a... |
from django.contrib import admin
from . import models
# Register your models here.
admin.site.register(models.CfgApprovingOfficers)
admin.site.register(models.CfgAttestingOfficers)
admin.site.register(models.CfgCertifyingOfficers)
admin.site.register(models.CfgGlobal)
admin.site.register(models.CfgOfficials)
admin.s... |
#from cqc.pythonLib import CQCConnection, qubit
#from lib import *
import json
def generate_python_file_from_node(folder_prefix, my_name, targets, n_receive):
with open(folder_prefix+my_name+".py", 'w') as f:
f.write("from cqc.pythonLib import CQCConnection, qubit\n\from lib import *\n\with CQCConnection('"+my_nam... |
import random
import numpy as np
from blocklm_utils import ConstructBlockStrategy
from argparse import Namespace
# rng = random.Random()
# span_lengths = [2, 3, 4, 2, 3, 4]
# length = 100
#
# counts = np.array([0] * length)
# for _ in range(10000):
# rng.shuffle(span_lengths)
# spans = ConstructBlockStrategy.... |
'''
Docs string
syntax if-else-elseif
if condition:
[code]
elif condition2:
[code]
else:
[code]
'''
# input --> str
# x = input('Enter a number: ')
# x = int(x)
x = int(input('Enter a number: '))
if x%2 == 0:
print(x, 'is an even.')
elif x%2 == 1:
print('Reminder is 1')
else:
print(x, 'is an ... |
# coding=utf-8
"""Command line processing"""
import argparse
from glenoidplanefitting import __version__
from glenoidplanefitting.ui.glenoidplanefitting_demo import run_demo
def main(args=None):
"""Entry point for glenoidplanefitting application"""
parser = argparse.ArgumentParser(description='glenoidplan... |
# (c) 2012-2018, Ansible by Red Hat
#
# This file is part of Ansible Galaxy
#
# Ansible Galaxy is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by
# the Apache Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
... |
# --------------
# Code starts here
import numpy as np
# Code starts here
# Adjacency matrix
adj_mat = np.array([[0,0,0,0,0,0,1/3,0],
[1/2,0,1/2,1/3,0,0,0,0],
[1/2,0,0,0,0,0,0,0],
[0,1,0,0,0,0,0,0],
[0,0,1/2,1/3,0,0,1/3,0],
... |
#!/usr/bin/python2
# SPDX-License-Identifier: MIT
import os, sys, subprocess
d = sys.argv[1]
o = sys.argv[2]
l = os.listdir(d)
t = 0
for fn in l:
print str(t)
p = subprocess.check_output(['./f2fs_standalone', 'repro', 'f2fs.img', os.path.join(o, str(t) + '.img'), os.path.join(d, fn)])
t += 1
|
import shutil
def progressbar(
current_index, total_index, left_description=None, right_description=None
):
"""Simple progressbar function that prints an ASCII-based progressbar
in the terminal with the additional textual description on the left and
right-hand side. In programs where there is a long l... |
class Solution:
def shortestSuperstring(self, words: List[str]) -> str:
good_words = []
for word in words:
dominated = False
for word2 in words:
if word in word2 and word != word2:
dominated = True
if not dominated:
... |
import json
import xlrd
coordinates = open("coordinates.json", "r")
cDict = json.loads(coordinates.read())
coordinates.close()
# print(cDict["FP1"])
# Archvio de salida
jDict = {}
data = xlrd.open_workbook("Matrices-Grafos3D.xlsx")
sheet = data.sheet_by_index(0)
# cellData = sheet.cell_value(16,1)
# print(cel... |
from cmd import Cmd
import os
import json
from dbestclient.executor.executor import SqlExecutor
config = {
'warehousedir': 'dbestwarehouse',
'verbose': 'True',
'b_show_latency': 'True',
'backend_server': 'None',
'epsabs': 10.0,
'epsrel': 0.1,
'mesh_grid_num': 20,
'limit': 30,
'csv_... |
from flask_restful import abort, Resource, reqparse
from flask import jsonify
from resources.models.User import User
from resources.models.UserArtist import UserArtist
from sqlalchemy.sql import func
class UserArtistListApi(Resource):
user = None
def __init__(self, **kwargs):
self.dbConn = kwargs['d... |
import pytest
from django.utils import timezone
pytestmark = [pytest.mark.django_db]
def test_order_is_shipped_even_if_it_is_not_paid(order, ship, course, user):
result = order.ship_without_payment()
assert result is True
ship.assert_called_once_with(course, to=user, order=order)
def test_order_is_mar... |
from .context import solvers
from solvers import Alphametic
import unittest
class AlphameticTest(unittest.TestCase):
"""Tests for the Alphametic solver"""
def testDivision(self):
a = Alphametic()
a.AddDivision(dividend="FHPOHSKF", divisor="ITSSKR", quotient="HIF")
a.AddDivision(dividen... |
def getUserName(chat):
username = ""
if chat.first_name:
username += chat.first_name
if chat.last_name:
username += chat.last_name
return username |
x = """
AA_Page1_AB.html
A_Final_AB.css
All_Images_lab_3
All_Images_lab4_AB
All_Index_AB.html
A_MyTemplate_AB.html
A_page2_AB.html
A_page3_AB.html
bdog.jpg
blcat.jpg
business.jpg
cat.jpg
cocky.jpg
coliseum.jpg
<!DOCTYPE html>.html
elephant.jpg
family.jpg
geyser1.jpg
geyser1.jpg
geyser2.jpg
geyser2.jpg
grand2.jpg
grand.... |
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... |
# coding=utf-8
import schedule
import os
import logging
import local_settings
from jobs import GenApi
logging.basicConfig(format='%(levelname)5s %(asctime)-15s #%(filename)-20s@%(funcName)-20s: %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
... |
from ftpack.correlation import corr_fft, conv_fft, conv, corr
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.backends.backend_pdf as pdf
N = 16
n_cont = 100
def y(x):
return np.sin(2 * x)
def z(x):
return np.cos(7 * x)
y_val = [y(2 * np.pi * i / N) for i in xrange(N)]
z_val = [z(2 ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 5 11:05:03 2018
@author: ckwha
"""
import numpy as np
import matplotlib.pyplot as plt
def plot_image(i, predictions_array, true_label, img,class_names):
predictions_array, true_label, img = predictions_array[i], true_label[i], img[i]
plt.grid(False)
plt.xticks([]... |
# with pytest.warns((预期警告类1,预期警告类2,...)) as record:
# 被测试代码
# record 类似于数组,数组中的元素是捕获的警告对象
import warnings
import pytest
def warn_message():
warnings.warn("user", UserWarning)
warnings.warn("runtime", RuntimeWarning)
def test_warns():
with pytest.warns((UserWarning, RuntimeWarning)) as records:
... |
# -*- coding: utf-8 -*-
# @Time : 2020/8/16 17:50
from __init__ import *
import close_flag
from ui2py.Manage import Ui_Manage
class ManageUI(QWidget):
def __init__(self,Userinfo,selfMerchant=0):
super().__init__()
self.ui = Ui_Manage()
self.ui.setupUi(self)
self.closeMerchant ... |
# -*- coding: UTF-8 -*-
import os
import shutil
from ..action import Action
from ..decorators import side_effecting
from ..mixins import WalkAppierMixin
from .strategies import match_strategy
class Cleaner(Action, WalkAppierMixin):
"""Класс действия для удаления файлов.
Attributes:
Внешние:
... |
# Here we'll just set up some basic strings
# Strings go in quotes, but be careful about quotes in strings!
## You can see that you can create problems when you use a quote character in the
## string. There are a couple ways around this, including putting a backslash
## before the problematic quote, or using a differe... |
import numpy as np
import scipy as sp
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import pd
import pickle as pkl
def read_file(file_path):
with open(file_path, 'rb') as f:
data = pkl.load(f)
return data
|
import os
import numpy as np
import itk
import typer
import json
from pathlib import Path
import segmantic
from segmantic.prepro.labels import (
load_tissue_list,
save_tissue_list,
build_tissue_mapping,
)
drcmr_labels_16 = [
"Background",
"Air_internal",
"Artery",
"Bone_cancellous",
"... |
import datetime
import pytz
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.core import mail
from circles.models import Event, MailTemplate
User = get_user_model()
class EventTestCase(TestCase):
def setUp(self):
self.host = User(email="host@example.com", user... |
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from protests.models import Protest
from participant.models import Participant
# noinspection PyMethodMayBeStatic
class ParticipantCreateAPIView(APIView):
def post(self, request, ... |
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import logging
import sys
from marshmallow import ValidationError
from pathlib import Path
from copy import deepcopy
from asyncio import get_running_loop, all_tasks, current_task, ... |
'''3. 输入一个三位整型数,判断它是否是一个水仙花数(比如153 = 1*1*1 + 5*5*5 + 3*3*3)
计算出有多少个水仙花数
'''
num = int(input("请输入一个三位整型数字:"))
n3 = num % 10
n2 = num /10 % 10
n1 = num /100 % 10
if num ==n1*n1*n1+ n2*n2*n2 + n3*n3*n3 :
print ("它是一个水仙花数")
else:
print("它不是一个水仙花数")
con = 0
for i in range(100,1000):
i3 = i % 10
i2 = i//10 % 10
... |
from .qart import QArtist
|
# Copyright (C) 2017 Beijing Didi Infinity Technology and Development Co.,Ltd.
# 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.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LI... |
import shutil
import os
path = "/data/data/com.termux/files/home/TermuxOutput"
shutil.rmtree(path)
print("Thank you for using TermuxOutput It shall now be deleted")
print("please run <cd> to properly exit")
|
# package.module
# module description
#
# Author: Allen Leis <allen.leis@gmail.com>
# Created: timestamp
#
# Copyright (C) 2017 Allen Leis
# For license information, see LICENSE
#
# ID: filename.py [] allen.leis@gmail.com $
"""
module description
"""
################################################################... |
from forest.dsl import Node
from .post_order import PostOrderInterpreter
class NodeCounter(PostOrderInterpreter):
# */+/? concat |
# {"kleene":3, "copies":3, "posit":3, "option":3, "concat":2, "union":1}
def __init__(self):
super().__init__()
def eval_Input(self, v):
return 0
def... |
# coding=utf-8
"""
Pytest config
"""
import os
import sys
import pytest
from click.testing import CliRunner
from mockito import unstub
@pytest.fixture(scope='session')
def miktex_path():
yield os.path.abspath(
os.path.join(
os.path.dirname(
os.path.dirname(__file__)
... |
# Generated with SMOP 0.41
from libsmop import *
# main.m
# This code is a basic example of one-class Matrix Factorization
# using AUC as a ranking metric and Bayesian Personalized Ranking
# as an optimization procedure (https://arxiv.org/abs/1205.2618).
#clear;
# TODO
# * Cross validation
set(... |
'''Unit test module for User class'''
import unittest
from user_data import User
class TestUser(unittest.TestCase):
'''
Test class that defines test cases for the user class behaviours.
Args:
unittest.TestCase: TestCase class that helps in creating test cases
'''
def setUp(self):
... |
'''
实验名称:网络时钟
版本:v1.0
日期:2020.7
作者:01Studio
'''
# 导入相关模块
from machine import Pin, I2C, RTC,Timer
from ssd1306 import SSD1306_I2C
import ntptime,network,time
# 定义星期和时间(时分秒)显示字符列表
week = ['Mon', 'Tues', 'Wed', 'Thur', 'Fri', 'Sat', 'Sun']
time_list = ['', '', '']
# 初始化所有相关对象
i2c = I2C(sda=Pin(13), scl=Pin(14)) #I2C初始化... |
calling <function report at 0x7fd128ff1bf8> 22.5
# A function call always needs parenthesis, otherwise you get memory address of
# the function object. So, if we wanted to call the function named report, and
# give it the value 22.5 to report on, we could have our function call as
# follows:
print("calling")
repor... |
# 利用pip来安装selenium
"""
命令:pip install -U selenium
网站:https://pypi.org/project/selenium/
""" |
"""Player apps"""
#Django
from django.apps import AppConfig
class PlayerAppConfig(AppConfig):
"""Player app config
The player contains the reference to the objects models like artists, songs
and albums.
"""
name = 'ceol.player'
verbose_name = 'Player'
|
from nsl.passes.ValidateSwizzle import ValidateSwizzleMask
import pytest
class TestValidateSwizzlePass:
def testMixFail(self):
with pytest.raises(Exception):
ValidateSwizzleMask('xyrg')
def testRepeatedWorks(self):
ValidateSwizzleMask('rrrr') |
import unittest
from unittest import TestCase
from unittest.mock import patch
from featurehub_sdk.client_context import ClientContext
from featurehub_sdk.fh_state_base_holder import FeatureStateBaseHolder
class ClientContextTest(TestCase):
@patch('featurehub_repository.FeatureHubRepository')
@patch('edge_se... |
"""
link: https://leetcode-cn.com/problems/robot-room-cleaner
problem: 模拟扫地机器人的行为,只通过四个 API 接口情况下遍历整个房间
solution: DFS。首先抛开题目,遍历01矩阵只需要做dfs。本质上这道题是一致的,不过遍历矩阵可以通过栈直接回溯变量,本题多了一个全局的robot,
在回溯时令robot也回到上一状态即可。
"""
# """
# This is the robot's control interface.
# You should not implement it, or speculate about ... |
"""
ConfigureCommand class for SubarrayNodeLow.
"""
# Standard Python imports
import json
# Third party imports
# Tango imports
import tango
from tango import DevFailed
# Additional import
from ska.base.commands import ResultCode
from ska.base import SKASubarray
from tmc.common.tango_client import TangoClient
from ... |
from arima.arima_model import fit_arma
from arima.process import generate_process, get_forecast
from arima.model_selection import choose_arma_model, choose_arima_model
from arima.stat_test import augmented_dickey_fuller_fit, ADFBootstrap, wald_stat |
#! /usr/bin/env python2.5
#
# orange4.py -- an interpreter for a simple lisp-like language
# [under same license as Python]
# (inspired by Peter Norvig's JScheme)
#
# =================================================================
# + Notes +
# =================================================================
#
# -... |
from mayan.apps.appearance.classes import Icon
icon_task_manager = Icon(driver_name='fontawesome', symbol='braille')
|
from django.apps import AppConfig
class SeedConfig(AppConfig):
name = 'seed'
|
from abc import ABCMeta, abstractmethod
from ml_keeker.common import RegexRepository
class Handler(metaclass=ABCMeta):
@abstractmethod
def handle(self):
pass
@abstractmethod
def close(self):
pass
class EventHandler(Handler):
def __init__(self, _filter: dict, logger=None):
... |
from unittest import mock
from django.test import TestCase
from two_factor import webauthn_utils
from two_factor.models import WebauthnDevice
from webauthn.webauthn import COSE_ALG_ES256, COSE_ALG_PS256, COSE_ALG_RS256
from .utils import UserMixin
class WebAuthnUtilsTest(UserMixin, TestCase):
def setUp(self... |
"""
from gcn.etc.dbconfig import DBCONFIG
clinvardb clinvitae clnphesnpdb cosmic dbsnp esp exac geneontology hgmd kgdb mimdb mirna nsfpdb refgene refmrna regulomedb splicedb utrdb
"""
from collections import namedtuple
from gcn.lib.utils import lib_utils
def get_vkey(chrom,pos,ref,alt):
#assembly = ... |
# -*- coding: utf-8 -*-
# Copyright (c) 2017 - for information on the respective copyright owner
# see the NOTICE file and/or the repository https://github.com/boschresearch/statestream
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.... |
"""Helper functions to read from library."""
import os
from dotenv import dotenv_values
def load_dotenv_config(dotenv_path=None, verbose=False, **kwargs):
"""Load config file at either `dotenv_path`, env var `PF_CONFIG_DOTENV_PATH`."""
return dotenv_values(dotenv_path=dotenv_path, verbose=verbose, **kwargs)... |
import keras.layers
from .utils import ensure_tf_type
def convert_relu(node, params, layers, node_name, keras_name):
"""
Convert ReLU activation layer
:param node: current operation node
:param params: operation attributes
:param layers: available keras layers
:param node_name: internal conver... |
from Attack.ParameterTypes.String import String
class SpecificString(String):
def __init__(self, args: list):
super(SpecificString, self).__init__(*args)
self.name = "String"
def validate(self, value) -> (bool, str):
is_valid = String.validate(self, value)
args = []
i... |
import pytest
from pynextion.events import (
Event,
MsgEvent,
TouchEvent,
CurrentPageIDHeadEvent,
PositionHeadEvent,
SleepPositionHeadEvent,
StringHeadEvent,
NumberHeadEvent,
CommandSucceeded,
EmptyMessage,
EventLaunched
)
from pynextion.exceptions import NexMessageException
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from downward import suites
from lab.reports import Attribute, gm
from common_setup import IssueConfig, IssueExperiment
SUITE_MCO14 = [
'barman-mco14-strips',
'cavediving-mco14-adl',
'childsnack-mco14-strips',
'citycar-mco14-adl',
'floortile-mco14-st... |
# Copyright 2016 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.
"""API that build and execute recipes wrapped into a task dependency graph.
A Task consists of a 'recipe' (a closure to be executed) and a list of refs to
t... |
import os
def data_filename(filename: str) -> str:
"""Returns the absolute path of a file in the testdata directory.
Parameters
----------
filename : str
Relative filename
Returns
-------
str
Absolute filename
"""
return os.path.join(os.path.dirname(__file__), fil... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.