content
stringlengths
5
1.05M
"""Unit tests for the token set index""" from annif.lexical.tokenset import TokenSet, TokenSetIndex def test_mllm_tokenset(): tokens = [1, 3, 5] tset = TokenSet(tokens) assert tset.subject_id is None assert not tset.is_pref assert len(tset) == len(tokens) assert sorted(list(tset)) == sorted(t...
import logging import traceback from functools import wraps logger=logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) logger.propagate = True def log_error(func): @wraps(func) def wrapped(*args, **kwargs): try: return func(*args,**kwargs) except BaseException as e...
# -*- coding: utf-8 -*- """ transistor.examples.books_to_scrape.workgroup ~~~~~~~~~~~~ This module implements a working example of a BaseWorker and BaseGroup. :copyright: Copyright (C) 2018 by BOM Quote Limited :license: The MIT License, see LICENSE for more details. ~~~~~~~~~~~~ """ from transistor import BaseWorker...
class NoMoreQuestionError(BaseException): pass
import os from typing import List from concurrent.futures import ProcessPoolExecutor import numpy as np import pandas as pd import rdkit.RDLogger from rdkit import Chem from tqdm.auto import tqdm from loguru import logger def normalize_inchi(inchi: str): try: mol = Chem.MolFromInchi(inchi) if mol...
#!/usr/bin/env python # encoding: utf-8 import csv import nltk.data count = 0 rf = open("report_ONS.csv", "w") csv_writer = csv.writer(rf) with open("report_ONN.csv", "r") as f: csv_reader = csv.reader(f) for row in csv_reader: text = row[5] sent_detector = nltk.data.load("tokenizers/punkt/eng...
# coding=utf-8 import pandas as pd import sys import optparse from lxml import etree from sklearn import metrics def main(argv=None): # parse the input parser = optparse.OptionParser() parser.add_option('-g') parser.add_option('-t') options, args = parser.parse_args() gold_file_nam...
from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("register", views.register, name="register"), path("check", views.check, name="check"), path("login", views.login_view, name="login_view"), path("logout", views.logout_view, name="logout_view...
import requests, base64, json from flask import request, Response, render_template def auth_required(method=None, okta=True): def decorator(f): def wrapper(*args, **kwargs): def get_header(): auth_header = request.headers.get("Authorization") if auth_header and 'B...
from pgcopy import CopyManager from . import test_datatypes class TestPublicSchema(test_datatypes.TypeMixin): temp = '' datatypes = ['integer', 'bool', 'varchar(12)'] def temp_schema_name(self): # This will set self.schema_table correctly, so that # TypeMixin.test_type will instantiate Cop...
# -*- coding: utf-8 -*- """ Test parsing of 'simple' offsets """ from __future__ import unicode_literals import time import datetime import unittest import parsedatetime as pdt from . import utils class test(unittest.TestCase): @utils.assertEqualWithComparator def assertExpectedResult(self, result, check, *...
pi=3.14 raio=5 area=pi*raio print(area)
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # copyright [2013] [Vitalii Lebedynskyi] # # 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 # # Unl...
from tkinter import * import sqlite3 root = Tk() root.title('Using Databases') root.geometry('300x300') # Creating or Connecting database conn = sqlite3.connect('address_book.db') # Creating cursor c = conn.cursor() c.execute("""CREATE TABLE address( first_name text, last_name text, ...
import logging from functools import singledispatchmethod from tinkoff.invest.services import Services from tinkoff.invest.strategies.base.errors import UnknownSignal from tinkoff.invest.strategies.base.signal import ( CloseLongMarketOrder, CloseShortMarketOrder, OpenLongMarketOrder, OpenShortMarketOrd...
import numpy as np import os.path import refnx, scipy # the ReflectDataset object will contain the data from refnx.dataset import ReflectDataset # the reflect module contains functionality relevant to reflectometry from refnx.reflect import ReflectModel # the analysis module contains the curvefitting engine from re...
from pyautogui import press, pixelMatchesColor flag = 0 while True: if pixelMatchesColor(889, 393, (161, 116, 56), 1): flag = 1 elif pixelMatchesColor(1026, 391, (161, 116, 56), 1): flag =0 if flag: press("right") else: press("left") ##you have to install pyautogui ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals from enum import Enum from lxml import etree import sys import os import codecs import re import spacy import pickle import json import networkx as nx import TermPreprocessor2 as tprep import OntologyOps as ontutils import NlpUtils....
''' This file is a part of Test Mile Arjuna Copyright 2018 Test Mile Software Testing Pvt Ltd Website: www.TestMile.com Email: support [at] testmile.com Creator: Rahul Verma 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 ...
from orbs_client.account import create_account from orbs_client.client import Client
""" test_passlock.py Tests for passlock. """ import logging from passlock import __version__ logging.disable(logging.CRITICAL) def test_version(): assert __version__ == '0.1.4'
# Copyright 2020 Google LLC # # 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, s...
# Generated by Django 3.1.6 on 2021-03-31 12:51 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0007_auto_20210330_1640'), ] operations = [ migrations.AlterField( model_name='basket',...
# coding: utf-8 import celery @celery.shared_task() def sleep(message, seconds=1): import time time.sleep(seconds) print(f'bar: {message}') return seconds
#!/usr/bin/env python3 import os import glob import subprocess from utility.general_repo_tools import get_repo_root if __name__ == '__main__': root = get_repo_root() format_directories = [os.path.join(root, d) for d in ['apps', 'apps_test', 'core_csiro']] ignored_files = ["*gatt_efr32*", "*gatt_nrf52*",...
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python 3.6 if len(A) < 3: return 0 A = sorted(A) product_A = A[0] * A[1] * A[-1] product_B = A[-1] * A[-2] * A[-3] max_product = max(product_A, product_B...
from django.contrib.auth import get_user_model from django.contrib import messages from django.core.mail import send_mail from django.conf import settings from django.db.models import Q from django.db.models.functions import Concat from django.db.models import Value from .serializers import ( UserDetailSerializer, ...
# coding=utf-8 # -*- python -*- # # This file is part of GDSCTools software # # Copyright (c) 2015 - Wellcome Trust Sanger Institute # All rights reserved # # File author(s): Thomas Cokelaer <[email protected]> # # Distributed under the BSD 3-Clause License. # See accompanying file LICENSE.txt distributed with t...
# See # import this into lldb with a command like # command script import pmat.py import lldb import shlex import optparse def pmat(debugger, command, result, dict): # Use the Shell Lexer to properly parse up command options just like a # shell would command_args = shlex.split(command) parser = create_pmat_op...
# -*- coding: utf-8 -*- from .pyver import PY2 __all__ = ( 'BufferIO', 'StringIO', ) if PY2: from io import BytesIO, StringIO class BufferIO(BytesIO): pass else: from io import StringIO class BufferIO(StringIO): pass
from django.apps import AppConfig class DocMgmtConfig(AppConfig): name = 'doc_mgmt'
from flask import Flask from flask_cors import CORS import config as c app = Flask(__name__) CORS(app) @app.route("/") def helloWorld(): return "Hello, cross-origin-world!"
#!/usr/bin/env python # Constrainted EM algorithm for Shared Response Model # A Reduced-Dimension fMRI Shared Response Model # Po-Hsuan Chen, Janice Chen, Yaara Yeshurun-Dishon, Uri Hasson, James Haxby, Peter Ramadge # Advances in Neural Information Processing Systems (NIPS), 2015. (to appear) # movie_data is a th...
# -*- coding: utf-8 -*- from datetime import datetime from collections import OrderedDict from django.shortcuts import render, redirect from django.http import Http404, HttpResponse from django.core.urlresolvers import reverse from django.conf import settings from django.contrib.auth.decorators import login_required f...
import subprocess from pathlib import Path if __name__ == '__main__': script_path = Path(Path.cwd(), 'HjerrildTest.py') constants_path = Path(Path.cwd(),'constants.ini') workspace_path = Path(Path.cwd()) for guitar in ['martin', 'firebrand']: for train_mode in ['1Fret', '2FretA', '2FretB',...
import re import math from .constants import * import lightcrs.utm as utm import lightcrs.mgrs as mgrs # WGS84 geoid is assumed # N .. 0 # E .. 90 # S .. 180 # W .. 270 # latitude south..north [-90..90] # longitude west..east [-180..180] class LatLon(object): def __init__(self, lat : float, ...
# Copyright 2018 GCP Lab Keeper 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 ...
from flask_babel import _ from flask_wtf.form import FlaskForm from flask_wtf.recaptcha import RecaptchaField from wtforms.fields.core import StringField from wtforms.fields.html5 import EmailField from wtforms.fields.simple import SubmitField, TextAreaField from wtforms.validators import DataRequired, Email, Length ...
import torch import torch.nn as nn import torch.nn.functional as F import torchvision import numpy as np from blocks import simple_block, Down_sample, Up_sample from torchsummary import summary # simplest U-Net class init_U_Net(nn.Module): def __init__( self, input_modalites, ...
import pandas as pd import requests from io import StringIO from os import path import os from csv import writer as csv_writer import hydrostats.data as hd import hydrostats.visual as hv import hydrostats as hs import datetime as dt import matplotlib.pyplot as plt import matplotlib.dates as mdates stations_pd = pd.rea...
r""" This file implements the documentation and default values of the ``vice.yields.agb.settings`` global yield settings dataframe. .. note:: While the code in this file is seemingly useless in that the implemented class does nothing other than call its parent class, the purpose is for this instance to have its own ...
import unittest import nlpaug.augmenter.char as nac import nlpaug.util.text.tokenizer as text_tokenizer class TestCharacter(unittest.TestCase): def test_empty(self): texts = ['', None] augs = [ nac.OcrAug(), nac.KeyboardAug(), ] for text in texts: ...
n1 = int(input('Digite o primeiro número: ')) n2 = int(input('Digite o segundo número: ')) if n1 > n2: print('O primeiro valor {} é maior'.format(n1)) elif n2 > n1: print('O segundo valor {} é maior'.format(n2)) elif n1 == n2: print('Não existe valor maior, os dois são iguais')
""" The program translate image to minecraft block map @author: Tang142857 @project: workspace @file: img2block.py @date: 2021-06-30 Copyright(c): DFSA Software Develop Center """ import cv2 import numpy import translator import entry def read_image(img_path: str, **kwargs): """ Return the bit map of the i...
# -*- coding: utf-8 -*- from sympy import Rational as r from .BetaFunction import BetaFunction from Definitions import tensorContract import itertools class ScalarMassBetaFunction(BetaFunction): def compute(self, a,b, nLoops): perm = list(itertools.permutations([a, b], 2)) permSet = set(perm) ...
from bs4 import BeautifulSoup, NavigableString from pathlib import Path def extract_references_page(html_string): """Extract the references in report282b, 283b, or 284b.html. Keeps any double spaces present in the original reference, as well as <i> and other minor HTML tags. """ # Add in extra <p>...
import json import argparse from src.model_handler.TrainHandler import start_training def parse_args(): parser = argparse.ArgumentParser(description="Adipocyte Fluorescence Predictor CLI Tool") parser.add_argument("-s", "--setting_file", type=str, help="JSON filepath that contains sett...
import enum import numpy as np import string import random from collections import namedtuple class DIRECTION(enum.Enum): UP = 0 RIGHT = 1 DOWN = 2 LEFT = 3 class TURN(enum.Enum): NONE = 0 LEFT = -1 RIGHT = 1 class BOARD_OBJECT(enum.Enum): EMPTY = 0 BODY = 1 TAIL = -1 APP...
import json import logging from django.conf import settings from django.shortcuts import render from django.http import JsonResponse from django.contrib.auth.decorators import login_required from identity.keystone import Keystone from swift_cloud_tools.client import SCTClient log = logging.getLogger(__name__) @login...
import abc __all__ = ['PowerDNSDatabaseMixIn'] class PowerDNSDatabaseMixIn(object): """ PowerDNSDatabaseMixIn class contains PowerDNS related queries """ __metaclass__ = abc.ABCMeta @abc.abstractmethod def _execute(self, operation, params=()): pass def gslb_checks(self): ...
from typing import List, Any from copy import deepcopy class Message: """ A message class for tranferring data between server and client """ def __init__( self, sender: str = "SERVER", house: str = "", room: str = "", text: str = "", action: str = "", ...
"""denne filen tar kun inn viewsets og legger dem inn i urlpatterns """ from rest_framework import routers from .views import BrukerViewSet, NamesViewSet, UserViewSet, BorstViewSet, registrationView router = routers.DefaultRouter() router.register('api/kalas', BrukerViewSet, 'kalas') router.register('api/names', Names...
import collector from server import APP # R0201 = Method could be a function Used when a method doesn't use its bound # instance, and so could be written as a function. # pylint: disable=R0201 class TestRoot: """Test various use cases for the index route.""" def test_route_with_no_worker(self, mocker): ...
from ..utils import get_by_key import datetime from ..models import meetups from ..models.meetups import MEETUPS_LIST from ..models import users from ..models.users import USERS_LIST QUESTIONS_LIST = [] class Questions(): def put(self, question_id, created_on, created_by, meetup, title, body,votes): s...
#!/usr/bin/env python3 """ Usage: check_ntp.py <host> <min_stratum> $ check_ntp.py pool.ntp.org 3 """ import sys import ntplib def check_health(host, min_stratum=3, port=123, ntp_version=3, timeout=5): try: c = ntplib.NTPClient() resp = c.request(host, port=port, version=ntp_version, timeout=timeou...
# Python variants vards = "Māris" uzvards = "Danne" # Vecais standarta veids pilnsVards = vards + " " + uzvards # Labāks variants pilnvsVards = "{} {}".format(vards, uzvards) # Jaunais veids pilnsVards = f"{vards} {uzvards}" print(pilnsVards)
import logging import os from re import template from typing import Dict, List, Tuple, cast from zipfile import ZipFile import requests import typer from .TemplateLoader import TemplateLoader from .TemplateOptions import TemplateOptions from .TemplateRenderer import TemplateRenderer from .utils import download CURVE...
# -*- coding: utf-8 -*- """ Module for the structural design of steel members. """ import numpy as np class Geometry: """ Structural element geometry. Class for the geometric properties of a structural element. Parameters ---------- cs_sketch : CsSketch object Cross-section sketch...
a = [10, 7, 5, 4] while True: m = max(a) index = a.index(m) a = [x + 1 for x in a] a[index] -= 4 print(a)
import random import IMLearn.learners.regressors.linear_regression from IMLearn.learners.regressors import PolynomialFitting from IMLearn.utils import split_train_test import numpy as np import pandas as pd import plotly.express as px import plotly.io as pio pio.templates.default = "simple_white" def country_to_col...
harness.add_runtime('softboundcets-O3', {"CC": "${CLANG}", "AS": "${CLANG}", "CFLAGS": "-O3 -fsoftboundcets -L${SOFTBOUND_RUNTIME_DIR}", "LDFLAGS": "-lm -lrt -lsoftboundcets_rt"})
import discord import asyncio import random from discord.ext import commands class MM(commands.Cog): def __init__(self, client): self.client = client def botAdminCheck(ctx): return ctx.message.author.id == 368671236370464769 # Guilds Checker @commands.command() @commands.guild_...
import pytari2600.memory.cartridge as cartridge import unittest import pkg_resources class TestCartridge(unittest.TestCase): def test_cartridge(self): cart = cartridge.GenericCartridge(pkg_resources.resource_filename(__name__, 'dummy_rom.bin'), 4, 0x1000, 0xFF9, 0x0) # Write should do nothing ...
from typing import Callable # noinspection PyCompatibility from concurrent.futures import Future from .predicated_work_subscription_event_listener import PredicatedWorkSubscriptionEventListener from yellowdog_client.scheduler import work_client as wc from yellowdog_client.model import WorkRequirement from yellowdog_cl...
import os, logging import tool_shed.util.shed_util_common as suc import tool_shed.util.metadata_util as metadata_util from galaxy.web.form_builder import SelectField def build_approved_select_field( trans, name, selected_value=None, for_component=True ): options = [ ( 'No', trans.model.ComponentReview.approved_sta...
# read in all LAMOST labels import numpy as np import pyfits from matplotlib import rc from matplotlib import cm import matplotlib as mpl rc('font', family='serif') rc('text', usetex=True) import matplotlib.pyplot as plt from matplotlib.colors import LogNorm direc = "/home/annaho/aida41040/annaho/TheCannon/data" pri...
## directory where the gps files are located #GPS_FILE_DIRECTORY = "C:/Users/raulms/Documents/Python Scripts/Codes/5StopsCentroids/Input/" GPS_FILE_DIRECTORY = "/home/pablo/projects/python/data/bhulan/sampledata/" ## file extension of the gps files # for now only handling excel files GPS_FILE_EXTENSION = "*.xlsx" ## ...
import numpy as np import torch import torch.nn as nn from awave.losses import get_loss_f from awave.utils.train import Trainer class AbstractWT(nn.Module): def fit(self, X=None, train_loader=None, pretrained_model=None, lr: float = 0.001, num_epochs: ...
from models import Employee from db import session from flask_restful import reqparse from flask_restful import abort from flask_restful import Resource from flask_restful import fields from flask_restful import marshal_with employee_fields = { 'id': fields.Integer, 'created_at': fields.DateTime, 'updated...
class Plot(object): def __init__(self,name,array_func,event_weight_func,hist, dim=1, selection_func=None ): self.name = name self.array_func = array_func self.event_weight_func = event_weight_func self.hist = hist self.dim = dim sel...
from django.contrib import admin from fabric_bolt.fabfiles.models import Fabfile # #class FabfileAdmin(admin.ModelAdmin): # form = FabfileForm admin.site.register(Fabfile)
from setuptools import setup, Command import subprocess class PyTest(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): errno = subprocess.call(['py.test']) raise SystemExit(errno) setup( name='Flask-S...
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class BST: def __init__(self): self.root = None def insert(self, data): if self.root is None: print("Adding the first node of the tree") ...
import os import pytest import sqlalchemy as sa from imicrobe.load import models from orminator import session_manager_from_db_uri @pytest.fixture() def test_session(): engine = sa.create_engine(os.environ['IMICROBE_DB_URI'], echo=False) try: with engine.connect() as connection: connecti...
""" 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...
__author__ = 'denis_makogon' import proboscis from proboscis import asserts from proboscis import decorators from gigaspace.cinder_workflow import base as cinder_workflow from gigaspace.nova_workflow import base as nova_workflow from gigaspace.common import cfg from gigaspace.common import utils GROUP_WORKFLOW = 'g...
from django.contrib.auth.models import User from django.db import models class University(models.Model): name = models.CharField(max_length=80, unique=True) acronym = models.CharField(max_length=40) def __str__(self): return self.name class Organization(models.Model): name = models.CharFiel...
import numpy as np from io import StringIO try : from colorama import Fore except: class ForeDummy: def __getattribute__(self, attr): return '' Fore = ForeDummy() NULL_BYTE = b'\x00' def read_null_terminated_string(f, max_len=128): string = b'' next_char = b'' while next_...
import os import sys import tempfile import subprocess import cv2 import pymesh import numpy as np import torch import triangle as tr from tridepth import BaseMesh from tridepth.extractor import calculate_canny_edges from tridepth.extractor import SVGReader from tridepth.extractor import resolve_self_intersection, cle...
from __future__ import print_function import logging import os import psutil import signal import socket from .worker import Worker from ..common import algorithm_loader def run(bind_address, yaml, parameter_server_url, timeout): algorithm = algorithm_loader.load(yaml['path']) _run_agents( bind_addr...
# guests_at_party #fetch the input functions from BTCInput import * #create an empty guests list guests=[] number_guests=read_int('How many guests do you expect? ') # read in 10 sales figures for count in range(1,number_guests+1): # assemble a prompt string prompt='Enter the names of the guests: ' # ...
import rospy from python_qt_binding import QtCore from python_qt_binding import QtGui from python_qt_binding import QtWidgets from python_qt_binding.QtWidgets import QWidget from rqt_ez_publisher import ez_publisher_model as ez_model from rqt_ez_publisher import widget as ez_widget from rqt_ez_publisher import publishe...
""" link: https://leetcode-cn.com/problems/generalized-abbreviation problem: 输出字符串的所有缩写,缩写规则为将连续n位用字符串n替代,不可以连续替换 solution: dfs + 备忘录。记录上一操作是否转换了数字。 solution-fix: 所有缩写可能数量定为 2**n 个,n为原串长度。可以将缩写串表达成长度为 n 的一个二进制数,第 i 为 0 时表示缩写,1 代表不变取原字符。 更高的时间复杂度,但空间复杂度更好。 """ class Solution: def generateAbbreviat...
try: from . import generic as g except BaseException: import generic as g class LoaderTest(g.unittest.TestCase): def test_obj_groups(self): # a wavefront file with groups defined mesh = g.get_mesh('groups.obj') # make sure some data got loaded assert g.trimesh.util.is_sha...
def create_db_table_pages_metadata(db, drop=True): if drop: db["pages_metadata"].drop(ignore=True) db["pages_metadata"].create({ "id": str, "page_idx": int, # This is just a count as we work through the pages "page_char_start": int, "page_char_end": int, "page_le...
from django.contrib.auth import get_user_model from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.db.models import Count from django.shortcuts import render, get_object_or_404, redirect from django.urls import reverse, reverse_lazy from django...
#!/usr/bin/env python3 import rospy import numpy as np import math from std_msgs.msg import Float32 from std_msgs.msg import Int32 from sensor_msgs.msg import PointCloud2, PointField from sensor_msgs import point_cloud2 import os import open3d.ml as _ml3d import open3d.ml.torch as ml3d import open3d as o3d import copy ...
import collections import os def ensure_dir(dirname): """ Ensure directory exists. Roughly equivalent to `mkdir -p` """ if not os.path.isdir(dirname): os.makedirs(dirname) def derive_out_path(in_paths, out_dir, out_extension='', strip_in_extension=True, ...
# import json # from fastapi.testclient import TestClient # from main import app # import hashing # client = TestClient(app) # class TestUser(): # def test_create_user(self): # new_user = self.user_thiago() # response = client.post('/user', data = json.dumps(new_user)) # new_user_response...
from abc import abstractmethod from pyautofinance.common.engine.engine_component import EngineComponent class Timer(EngineComponent): def __init__(self, when, **parameters): self.when = when self.parameters = parameters @abstractmethod def execute(self, cerebro, strat=None): # Returns t...
# Author: OMKAR PATHAK # Created On: 31st July 2017 # Best = Average = O(nlog(n)), Worst = O(n ^ 2) # quick_sort algorithm def sort(List): if len(List) <= 1: return List pivot = List[len(List) // 2] left = [x for x in List if x < pivot] middle = [x for x in List if x == pivot] right = [x ...
#!/usr/bin/env python """ $ python main.py grid.txt 4 70600674 """ import sys from operator import mul from functools import reduce def get_adjacents(grid, a, b, size): x_range = range(a, a + size) y_range = range(b, b + size) y_range_rev = range(b, b - size, -1) yield [grid[a][y] for y in y_range]...
# -*- coding: utf-8 -*- import unittest import compat import sys from plmn.network_checks import * class NetworkRegisterVerizon(unittest.TestCase): def test_register_on_verizon(self): NetworkChecks.network_register('Verizon', 'vzwinternet') NetworkChecks.network_connect('Verizon', 'vzwinternet') ...
"""Tests for C-implemented GenericAlias.""" import unittest import pickle from collections import ( defaultdict, deque, OrderedDict, Counter, UserDict, UserList ) from collections.abc import * from contextlib import AbstractContextManager, AbstractAsyncContextManager from os import DirEntry from re import Pattern,...
# =============================================================================== # Copyright 2012 Jake Ross # # 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/licens...
import functools import importlib import os import sys import matplotlib as mpl from . import _backports from ._mplcairo import ( cairo_to_premultiplied_argb32, cairo_to_premultiplied_rgba8888, cairo_to_straight_rgba8888, ) @functools.lru_cache(1) def get_tex_font_map(): return mpl.dviread.PsfontsMa...
import numpy as np import modules_disp as disp class Module: def sgd_step(self, lrate): pass # For modules w/o weights class Linear(Module): def __init__(self,m,n): self.m, self.n = (m, n) # (in size, out size) self.W0=np.zeros([self.n,1]) # (n x 1) self.W = np.random.norm...
import discord import random import configparser config = configparser.ConfigParser() def loadconfig(): config = configparser.ConfigParser() config.read('config.sffc') Version = config['Data']['version'] token = config['Data']['token'] alttoken = config['Data']['alttoken'] prefix = con...
import functools import gc def clear_all_lru_caches(): gc.collect() wrappers = [ a for a in gc.get_objects() if isinstance(a, functools._lru_cache_wrapper) ] for wrapper in wrappers: wrapper.cache_clear()
""" /****************************************************************************** This source file is part of the Avogadro project. Copyright 2016 Kitware, Inc. This source code is released under the New BSD License, (the "License"). Unless required by applicable law or agreed to in writing, software di...