content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
import os
from os import environ
from os.path import dirname, join, isdir
from uuid import uuid4 as random_uuid
from netmiko import utilities
from netmiko._textfsm import _clitable as clitable
RESOURCE_FOLDER = join(dirname(dirname(__file__)), "etc")
CONFIG_FILENAME = join(RESOURCE_FOLDER, ".ne... |
#!/usr/bin/env python3
# ------------------------------------------------------------------------------
# stress test scopez_server
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# Imports
# --------------... |
"""
Created on 13 Jul 2019
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
"""
import optparse
# --------------------------------------------------------------------------------------------------------------------
class CmdDisplay(object):
"""unix command line handler"""
def __init__(self):
... |
from typing import Tuple, Optional, List
import warnings
import ctypes
import operator
from functools import reduce
import torch
import numpy as np
from dqc.hamilton.intor.lcintwrap import LibcintWrapper
from dqc.hamilton.intor.utils import np2ctypes, int2ctypes, CGTO, CPBC, \
c_nul... |
import olympe
import os
from olympe.messages.ardrone3.Piloting import TakeOff, moveBy, Landing
from olympe.messages.ardrone3.PilotingState import FlyingStateChanged
DRONE_IP = os.environ.get("DRONE_IP", "10.202.0.1")
def test_moveby2():
drone = olympe.Drone(DRONE_IP)
drone.connect()
assert drone(
... |
# -*- coding: utf-8 -*-
"""
This module defines the parser of the QL language. It uses the PLY library to
take a string and return instead a stream of tokens. PLY is often used as a
single script but in this case we use a class for better encapsulation and code
organisation.
"""
from ply import lex
from ply.lex import ... |
from datetime import datetime
import pytest
from sqlalchemy.orm import Session
from itunesdb.web import crud
from itunesdb.web import models
from itunesdb.web import schemas
@pytest.fixture
def track_1_ambient_1(db: Session, album_ambient_1: models.Album) -> models.Track:
return crud.create_track(
schem... |
import os
import flask
import pytest
import uuid
from kaos_backend.controllers.tests import create_job_service, t_any, create_train_zip
from kaos_backend.controllers.train import TrainController
from kaos_backend.exceptions.exceptions import InvalidBundleError
from kaos_backend.util.tests import create_zip
from kaos... |
import supybot.utils as utils
from supybot.commands import *
import supybot.plugins as plugins
import supybot.ircutils as ircutils
import supybot.callbacks as callbacks
import json
import requests
class Segwit(callbacks.Plugin):
threaded = True
def segwit(self, irc, msg, args):
timeout = False
... |
# Generated by Django 2.2.5 on 2019-09-04 00:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('announcement', '0004_comment'),
]
operations = [
migrations.AlterField(
model_name='announcemen... |
import copy
import random
# Consider using the modules imported above.
class Hat:
def __init__(self, **kwargs):
self.contents = []
for k, v in kwargs.items():
for _ in range(v):
self.contents.append(k)
def draw(self, num):
if num > len(self.contents):
drawn_balls = [i for i in sel... |
import os
import sys
import copy
import torch
import platform
import numpy as np
import pandas as pd
from ray import tune
from tqdm import tqdm
from pathlib import Path
from torchvision import transforms
from torch.utils.data import DataLoader
from sklearn.utils.class_weight import compute_sample_weight
if platform.s... |
from enum import Enum
import os
class Mode(Enum):
NONE = 0
DEBUG = 1
LOG = 2
class Level(Enum):
ERROR = 0
INFO = 1
TRACE = 2
class Config:
def __new__(cls):
if not hasattr(cls, 'instance') or not cls.instance:
cls.instance = super().__new__(cls)
cls.instanc... |
import sys
import os
sys.path.insert(1, os.getcwd())
|
import cv2
import numpy as np
from aip import AipOcr
from PIL import Image, ImageDraw, ImageFont
import os, math
def crop_image(src_img, x_start, x_end, y_start, y_end):
"""
图片裁剪
:param src_img: 原始图片
:param x_start: x 起始坐标
:param x_end: x 结束坐标
:param y_start: y 开始坐标
:param y_end: y 结束坐标
... |
# Copyright 2018 The TensorFlow Probability 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 o... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable-msg=no-member
"""
elmo_config.py is a module for elmo model config
"""
import torch
__author__ = "Ehsan Tavan"
__project__ = "Persian Emoji Prediction"
__credits__ = ["Ehsan Tavan"]
__license__ = "Public Domain"
__version__ = "1.0.0"
__maintainer__ = "... |
class Solution:
def dfs(self, root):
if not root:
return 0
return max(self.dfs(root.left),self.dfs(root.right)) + 1
def XXX(self, root: TreeNode) -> bool:
if not root:
return True
if abs(self.dfs(root.left) - self.dfs(root.right)) <= 1:
return ... |
import altair as alt
from vega_datasets import data
from rpcjs import Dashboard, Page, set_attribute
import rpcjs.elements as html
import rpcjs.binded as forms
source = data.cars()
columns = list(source.columns)
class MyDynamicPage(Page):
def routes(self):
return '/'
def __init__(self):
se... |
from django.urls import path, include
from .views import dashboard, register_user, edit_user_details, ProfileList, ProfileDetail, start_following
from django.contrib.auth import views as auth_views
from django.contrib.auth.decorators import login_required
urlpatterns = [
## USER MANAGED LOGIN.
# path("login/",... |
import mock
import mopidy_funkwhale
from mopidy_funkwhale import models
from mopidy_funkwhale.client import (convert_uri,
favorites_playlist)
from tests import factories
@mock.patch('mopidy_funkwhale.client.translator')
def test_client_convert_uri_uri(translator):
@convert_u... |
"""Asyncio S3 file operations."""
|
from model.group import Group
from random import randrange
from model.contact import Contact
def test_add_contact_in_group(app, db):
if len(db.get_group_list()) == 0:
app.group.create(Group(name="test"))
if len(db.get_contact_list()) == 0:
app.contact.add_new(Contact(firstname="random", home_n... |
import torch
from typing import Union, Sequence, List, Tuple
import builtins
# Convenience aliases for common composite types that we need
# to talk about in PyTorch
_TensorOrTensors = Union[torch.Tensor, Sequence[torch.Tensor]]
# In some cases, these basic types are shadowed by corresponding
# top-level values. T... |
import threading
import time
import logging
from Core.Logger import log
# URL 队列调度
class Scheduler(threading.Thread):
__slots__ = ('redis_connection', 'url_rate', 'follow_info_url_queue', 'user_info_url_queue', 'url_queue_name')
def __init__(self, redis_connection, url_rate):
threading.Thr... |
from enum import Enum
class Exchange(Enum):
Binance = 1
Huobi = 2
Gemini = 3
class BaseDataAPI:
def __init__(self, exchange: Exchange, api_key: str, secrete_key: str):
self.api_key = api_key
self.secrete_key = secrete_key
self.exchange = exchange
def set... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 The FATE Authors. 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/lice... |
from botocore.credentials import Credentials
from aiodynamo.credentials import Key
from aiodynamo.sign import make_default_endpoint
KEY = Key("AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY")
CREDENTIALS = Credentials(KEY.id, KEY.secret)
SERVICE_NAME = "dynamodb"
REGION = "us-east-1"
URL = make_defa... |
# 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.
"""Script to setup the environment to run unit tests.
Modifies PYTHONPATH to automatically include parent, common and pylibs
directories.
"""
import os... |
import math
import time
class vector:
x = 0.0
y = 0.0
def __init__(self):
self.X = 0.0
self.y = 0.0
def __str__(self):
return '{x:%s, y:%s}' % (self.x, self.y)
class car:
# given by system
id = None
token = None
# given by system - end
# given by use... |
#
# 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"); you may not... |
# Generated by Django 2.2.9 on 2020-01-01 17:07
from django.db import migrations, models
import django.db.models.deletion
import survey_app_repo.survey.models
class Migration(migrations.Migration):
dependencies = [
('survey', '0003_auto_20200101_1301'),
]
operations = [
migrations.Creat... |
from setuptools import setup
setup(
name='microconfig',
version='0.0.1',
packages=['microconfig'],
url='',
license='',
author='haimcohen',
author_email='hcloli@gmail.com',
description=''
)
|
# All the ways of invalidating getattr
# TODO should test getclsattr as well
# TODO should also test some crazier stuff, like descriptors with inheritance
def get(self, obj, typ):
print '__get__ called'
print type(self)
print type(obj)
print typ
return self.elem
def set(self, obj, typ):
print... |
from nonebot import (CommandSession, IntentCommand, NLPSession, get_bot, log,
on_command, on_natural_language)
from nonebot import permission as perm
from nonebot.permission import *
import random
import datetime
import asyncio
import json
from os import path
from bot_config import GROUP_U... |
from evawiz_basic import *
def request(handler,*args):
#def request_connect_user(self):
#handler.contact_server('mod_connect_user')
dprint('step into disconnect_user')
#save auth information
handler.clear_auth_info()
print('You\'ve disconnectted to evawiz server.')
pass
|
from .__plugin__ import Plugin as _P
from .__plugin__ import publicFun
from PySide2 import QtCore, QtWidgets
import re
from functools import partial
import os.path as op
class Plugin(_P):
def __init__(self, app):
super().__init__(app)
self.widget = Widget(app)
@publicFun(guishortcut="Ctrl+^")
... |
import os
import pickle
def dump(name, value, end=".pickle"):
full_name = check_name(name, end)
create(name)
with open(full_name, "wb") as file:
pickle.dump(value, file)
return value
def create(name, end=".pickle", only=None):
full_name = check_name(name, end)
# existing test
... |
#!/usr/bin/python -u
import sys,os,re
from datetime import datetime
from stat import *
import tempfile
from cStringIO import StringIO
from cPickle import Pickler, Unpickler
import subprocess as sub
import string
reload(sys)
sys.setdefaultencoding("utf-8") # Needs Python Unicode build !
try:
import json
except:
... |
# coding=UTF8
import os
import shutil
import pyexiv2
import time
import utils
# noinspection PyBroadException
class PictureArchiver:
_verbose = True
_debug = False
def __init__(self, src_path, dest_path):
self._srcPath = src_path
self._destPath = dest_path
self._move_files = Fals... |
from tqdm import tqdm
from time import sleep
import logging
from pynonymizer.database.provider import DatabaseProvider, SEED_TABLE_NAME
from pynonymizer.database.exceptions import UnsupportedTableStrategyError
from pynonymizer.database.mysql import execution, query_factory
from pynonymizer.database.basic.input import r... |
from numpy import *
from scipy import *
from scipy.signal import remez, resample
from .halfbandfir import halfbandfir
from fractions import gcd
from .upfirdn import upfirdn
def resample_cascade(x, fs_start, fs_end, N=42):
"""
Resample a signal from one sampling frequency to another, using a halfband
filte... |
# Pytathon if Stement
# if Statement
sandwich_order = "Ham Roll"
if sandwich_order == "Ham Roll":
print("Price: $1.75")
# if else Statement
tab = 29.95
if tab > 20:
print("This user has a tab over $20 that needs to be paid.")
else:
print("This user's tab is below $20 that does not require immediate payment.")
... |
"""
This is the base file of the friendly computing machine!
"""
from .import math
from .math import mult
|
# -*- coding: utf-8 -*-
import os
import sys
from news_crawler.spiders import BaseSpider
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
from datetime import datetime
sys.path.insert(0, os.path.join(os.getcwd(), "..",))
from news_crawler.items import NewsCrawlerItem
from news_crawler.... |
# Generated by Django 2.2.7 on 2019-12-11 08:37
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import re
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappabl... |
# coding: utf-8
# flake8: noqa
"""
Emby Server API
Explore the Emby Server API # noqa: E501
OpenAPI spec version: 4.1.1.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
# import models into model package
from embyapi.models.activity... |
from typing import Any, Callable, Dict, List, Optional, Tuple
from concurrent.futures import Executor, Future
from itertools import repeat
from freak.models.response import EngineResponse
from networkx import DiGraph
from networkx.algorithms.dag import is_directed_acyclic_graph
def submit_and_execute_single_job(
... |
import tensorflow as tf
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.resnet50 import preprocess_input
from tensorflow.keras.preprocessing.sequence import pad_sequences
import numpy as np
from pickle import load
# map an integer to a word
def word_for_id(integer, tokenizer):
... |
# 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 writing, software
# distributed under th... |
from py21cmmc_fg.c_wrapper import stitch_and_coarsen_sky
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 23)
X, Y = np.meshgrid(x,x)
z = X**2 + Y**2
z = np.atleast_3d(z)
z = np.tile(z ,(1,1,6))
print(z.shape)
plt.imshow(z[:,:,0])
plt.savefig("derp1.png")
z = np.atleast_3d(z)
out = stitch_... |
"""
Provides :py:class:`UnaryMixin` mixin class
It provides unary operator support to the :py:class:`Lazy` class
"""
from .core import Lazy, LazyMixin
from .ops import lazy_operator
class UnaryMixin(LazyMixin):
"""
Binary operator support
"""
@lazy_operator
def __neg__(self: Lazy) -> Lazy:
... |
'''
Questions
1. Can the statue list be given sorted?
Observations
1. All sizes are non negative integers, unique. No repeats
2. kind of like sorting an array and seeing how many elements need to be in between
3. What is the minimum number of additional statues needed? 0. The maximum? The range of list, or largest-sma... |
from collections import defaultdict
import numpy as np
# from itertools import zip_longest as zip
def return_dim_ndarray(value):
""" helper function to always have at least 1d numpy array returned """
if isinstance(value, list):
return np.array(value)
elif isinstance(value, np.ndarray):
r... |
import os
import slivka.conf.logging
import slivka.server
home = os.path.dirname(os.path.abspath(__file__))
os.environ.setdefault('SLIVKA_HOME', home)
slivka.conf.logging.configure_logging()
application = app = slivka.server.create_app()
|
from typing import TypedDict
class IAppConfig(TypedDict):
appDbConStr: str
dumpFolder: str
flaskSecret: str
flaskPort: str
logstashHost: str
logstashPort: int
|
# ResNet-18, 5 classes, 25,000 images, 100 linear probing epochs, no bottleneck, classical.
def results():
tepochs = [11, 21, 51, 101, 201, 300]
pepochs = range(0, 101)
accs = [[68.14, 69.1, 70.64, 70.04, 71.34, 70.32, 71.78, 71.52, 72.12, 71.1, 72.26, 71.9, 72.56, 72.64, 73.0, 72.26,
72.98, 72... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RWatermelon(RPackage):
"""Illumina 450 methylation array normalization and metrics.
1... |
# -*- coding: utf-8 -*-
# Notification Template types
REPLY_TYPE = 'reply'
DOCUMENT_OWNER = 'document_owner'
ROOT_PATH = 'h:notification/templates/'
def includeme(config):
pass
|
import datetime
import uuid
from app.domains.users.validators import is_user_name_valid, is_user_email_valid
from database import db
class Users(db.Document):
_id = db.StringField(default=str(uuid.uuid4()), primary_key=True)
name = db.StringField(required=True, validation=is_user_name_valid)
last_name = ... |
"""
checks to make sure that the challenge_set is internally consistent
usage: python check.py
"""
import json
stats = {
"tests": 0,
"errors": 0,
}
required_playlist_fields = ["num_holdouts", "pid", "num_tracks", "tracks", "num_samples"]
optional_playlist_fields = ["name"] + required_playlist_fields... |
# coding: utf-8
"""
SimScale API
The version of the OpenAPI document: 0.0.0
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from simscale_sdk.configuration import Configuration
class MULESSolver(object):
"""NOTE: This class is auto generated by O... |
# -*- coding: utf-8 -*-
import numpy as np
from ensemble_model import Ensemble_Model
import cv2
COLLISION_RANGE = 0.3
COLLISION_NUM = 10
ARRIVAL_RANGE = 0.48
class PredictEnv:
def __init__(self, model):
self.model = model
def _termination_fn(self, image, goal):
collision = False
arr... |
# 多変量正規分布はベクトルが従う分布と考えることができる。
# そのためStanで扱う場合はベクトルとmatrixを使って表現する。
import numpy as np
import seaborn as sns
import pandas
import matplotlib.pyplot as plt
from matplotlib.figure import figaspect
from matplotlib.gridspec import GridSpec
import mcmc_tools
from scipy.stats import norm
import time
# data-mvn
# 1行が1名のデータ
#... |
import os
import urllib
from bioconda_utils import recipe
from ruamel.yaml import YAML
"""
This script read the metadata from bioconda repo and annotate the metadata from the recipes in the tools
"""
yaml = YAML()
yaml_recipe = YAML(typ="rt") # pylint: disable=invalid-name
with open('../annotations.yaml', 'r') as r... |
"""Definitions for the primitive `scalar_bit_rshift` x >> y."""
from ..lib import UniformPrimitiveInferrer, assert_scalar
from ..xtype import Integral
from . import primitives as P
def pyimpl_scalar_bit_rshift(x: Integral, y: Integral) -> Integral:
"""Implement `scalar_bit_rshift`."""
assert_scalar(x, y)
... |
from databases import Database
from dotenv import load_dotenv
from google.cloud import storage
from starlette.applications import Starlette
from starlette.responses import JSONResponse
import uvicorn
from config import Config
import loader
import pubsub
load_dotenv()
# Load configuration from sources
cfg = Config()... |
from __future__ import division
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['xtick.direction'] = 'in'
plt.rcParams['ytick.direction'] = 'in'
plt.rcParams['axes.spines.right'] = False
plt.rcParams['axes.spines.top'] = False
plt.rcParams['axes.linewidth'] = 2
plt.rcParams['xtick.m... |
# -*- coding: utf-8 -*-
# @Time : 2021/4/7 下午5:38
# @Author : anonymous
# @File : urls.py
# @Software: PyCharm
# @Description:
from django.urls import path, include
from rest_framework import routers
from .views import TasksViewSet
router = routers.DefaultRouter()
router.register(prefix=r'tasks', viewset=Tasks... |
# Copyright 2016 by MPI-SWS and Data-Ken Research.
# Licensed under the Apache 2.0 License.
"""
This sub-module provides a collection of filters for providing linq-style
programming (inspired by RxPy).
Each function appears as a method on the Publisher base class, allowing for
easy chaining of calls. For example:
... |
# mlt2/core.py
# Copyright 2019 Matthias Lesch <ml@matthiaslesch.de>
# MIT License: http://www.opensource.org/licenses/mit-license.php
"""
mlt2.core
---------
The core functionality.
:copyright: 2014-2020 by Matthias Lesch <ml@matthiaslesch.de>
:license: MIT license
"""
import os,re,sys
from col... |
# flake8: noqa
# TODO(vorj): When we will meet flake8 3.7.0+,
# we should ignore only W291 for whole file
# using --per-file-ignores .
import clpy
import unittest
class TestUltimaCIndexer(unittest.TestCase):
def test_cindexer_argument_mutation(self):
x = clpy.backend.ultima.e... |
from .package import template
|
from tuprolog import logger
from ._ktadapt import *
# noinspection PyUnresolvedReferences
import jpype
# noinspection PyUnresolvedReferences
import jpype.imports
# noinspection PyUnresolvedReferences
import it.unibo.tuprolog.core.operators as _operators
from tuprolog.jvmutils import jiterable
from tuprolog.pyutils impo... |
# Copyright 2019 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from dataclasses import dataclass
from pathlib import Path
from pants.engine.console import Console
from pants.engine.fs import (
Digest,
DirectoryToMaterialize,
FileContent,
Inpu... |
# $Id: SuperGlobal.py 1047 2009-01-15 14:48:58Z graham $
import __main__
class SuperGlobal:
"""
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/457667
Here so can use in testing.
Creates globals.
i.e.
superglobal = SuperGlobal()
superglobal.data = ....
However many times yo... |
import matplotlib.pyplot as plt
from plotnine import *
import pandas as pd
df_penduduk = pd.read_csv('https://storage.googleapis.com/dqlab-dataset/datakependudukandki-dqlab.csv')
df_penduduk_luas_jumlah = df_penduduk.groupby(['NAMA KELURAHAN', 'LUAS WILAYAH (KM2)'])[['JUMLAH']].agg('sum').reset_index()
(ggplot(data=d... |
import os
import re
import sys
import gzip
import pickle
import ftputil
import argparse
import datetime
import tempfile
import urllib.request
server = 'ftp.seismo.nrcan.gc.ca'
tmpdir = os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','metadata','INTERMAGNET')
parser = argparse.ArgumentParser()
parser.add... |
"""Hight cipher."""
from arxpy.bitvector.core import Constant
from arxpy.bitvector.operation import RotateLeft as ROL
from arxpy.primitives.primitives import KeySchedule, Encryption, Cipher
class HightKeySchedule(KeySchedule):
"""Key schedule function."""
rounds = 34 # key whitening seen as a round
inp... |
"""
file_name
@author: Gregory Kramida
Copyright: (c) Gregory Kramida 2016
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... |
"""
Configuration Parser for V2D
"""
import json
import threading
import os
lock = threading.Lock()
def get_config():
with lock:
if hasattr(get_config, "config"):
return get_config.config
fname = os.environ.get("V2D_CONFIG_FILE", "config.json")
with open(fname, "r") as fin:
... |
import json
import requests
import os
import sql
def call_crawlers() -> bool:
"""
Fetches the list of all shops, does some load balancing magic and calls all registered crawler
instances to start them
:return: If the calls have been successful
"""
product_ids = sql.getProductsToCrawl()
#... |
from django import forms
from django.forms import widgets
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
from accounts.models import Profile
class UserRegisterForm(UserCreationForm):
class Meta(UserCreationForm.Meta... |
db_entity.zaruba_field_name = zaruba_entity_name_data.zaruba_field_name |
from abc import ABC, abstractmethod
class AbstractWriter(ABC):
@abstractmethod
def write(self, data):
pass
@abstractmethod
def release(self):
pass
|
import unittest
from katas.kyu_8.grasshopper_summation import summation
class SummationTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(summation(1), 1)
def test_equals_2(self):
self.assertEqual(summation(8), 36)
|
import pygame
import numpy as np
import random
import copy
from astar import astar
from constants import DISPLAY_WIDTH, DISPLAY_HEIGHT, PIXEL_SIZE, BLACK, GREEN
class Snake:
def __init__(self):
self.x = round(random.randrange(0, DISPLAY_WIDTH - PIXEL_SIZE) / 20.0) * 20
self.y = round(random.randra... |
'''
Units tests for the cpptraj wrappers for nasqm
'''
import os
import pytest
import numpy as np
from pynasqm.nmr.nmrgroupsingle import NMRGroupSingle
import pynasqm.userinput as nasqm_user_input
import pynasqm.inputceon as inputceon
def setup_module(module):
'''
Switch to test directory
'''
os.chdir(... |
"""Utility functions & decorators for dealing with FOOOF, as a module."""
from importlib import import_module
from functools import wraps
###################################################################################################
################################################################################... |
import random
from time import sleep
from magicgui import magicgui
from magicgui.tqdm import tqdm, trange
# if magicui.tqdm.tqdm or trange are used outside of a @magicgui function, (such as in
# interactive use in IPython), then they fall back to the standard terminal output
# If use inside of a magicgui-decorated ... |
#!/usr/bin/env python
"""FunCLI root execution function."""
import logging
import click
from .constants import CONTEXT_SETTINGS, PASS_CONTEXT
from .classes import FunCLI
@click.command(cls=FunCLI, context_settings=CONTEXT_SETTINGS)
@click.option('-d', '--debug', is_flag=True, help='Enable DEBUG mode.')
@click.optio... |
# -*- coding: utf-8 -*-
############################################################################
#
# Copyright © 2012, 2013, 2014 OnlineGroups.net 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 accomp... |
from django.db import models
from data_refinery_common.models.computational_result import ComputationalResult
from data_refinery_common.models.sample import Sample
class SampleResultAssociation(models.Model):
sample = models.ForeignKey(Sample, blank=False, null=False, on_delete=models.CASCADE)
result = mode... |
"""Streets _dags file."""
from __future__ import print_function
from airflow.operators.python_operator import PythonOperator
from trident.operators.s3_file_transfer_operator import S3FileTransferOperator
from airflow.operators.latest_only_operator import LatestOnlyOperator
from trident.operators.poseidon_email_operator... |
#!/usr/bin/env python3
# rewritten by me from C code
# C code author: @andreyorst
for i in range(0, 100):
if not i % 3:
print('Fizz', end='')
if not i % 5:
print('Buzz', end='')
if i % 3 and i % 5:
print(i, end='')
print()
|
# -*- encoding: utf-8 -*-
import os
from colorama import Fore
import nltk
import re
import sys
import tempfile
from utilities.GeneralUtilities import print_say
from CmdInterpreter import CmdInterpreter
# register hist path
HISTORY_FILENAME = tempfile.TemporaryFile('w+t')
PROMPT_CHAR = '~>'
"""
AUTHORS' SCOPE:
... |
# -*- coding: utf-8 -*-
"""
Contains the mode that control the external changes of file.
"""
import os
from pyqode.core.api import TextHelper
from pyqode.core.api.mode import Mode
from pyqode.qt import QtCore, QtWidgets
from pyqode.core.cache import Cache
class FileWatcherMode(Mode, QtCore.QObject):
""" Watches t... |
import unittest
from tests.recipes.recipe_lib_test import BaseTestForMakeRecipe
class TestLibx264Recipe(BaseTestForMakeRecipe, unittest.TestCase):
"""
An unittest for recipe :mod:`~pythonforandroid.recipes.libx264`
"""
recipe_name = "libx264"
sh_command_calls = ["./configure"]
|
import json
import numpy as np
with open('../data/inceptionV3.json', 'r') as fp:
std = json.load(fp)
print("std read finish")
with open('../data/inceptionV3-check.json', 'r') as fp:
out = json.load(fp)
print("out read finish")
for key in std.keys():
print("checking", key, "...")
if key not in out.k... |
# Copyright 2021 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.