content
stringlengths
5
1.05M
import yaml from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient class OpenAPISchemaTest(TestCase): def setUp(self): self.client = APIClient() def test_schema_ok(self): resp = self.client.get("/schema/") self.assertEqual(resp.sta...
import socket import os import json import unittest import sys import _thread import logging import time import random sys.path.append(os.path.dirname(os.path.abspath(__file__ + '/..'))) from pubsub.publisher import Publisher os.chdir(os.getcwd() + '/tests') from logger import init_logging log = init_logging('noc-net...
# import the necessary packages from scipy.spatial import distance as dist from imutils.video import FileVideoStream from imutils.video import VideoStream from imutils import face_utils import numpy as np import argparse import imutils import time import dlib import cv2 from time import sleep import wx import os import...
import json from aws_cdk.aws_dynamodb import Attribute, AttributeType, Table from aws_cdk.aws_events import Rule, RuleTargetInput, Schedule from aws_cdk.aws_events_targets import LambdaFunction from aws_cdk.aws_iam import PolicyStatement from aws_cdk.aws_lambda import Runtime from aws_cdk.aws_lambda_python import Pyth...
import numpy as np from .configs import * from droidbot.input_event import * class Action: """ An action that the RL agent can send to the device, including the following fields Name Meaning action_type Probability of each action type, including gesture, intent, key gesture_...
import pytest from assertpy import assert_that import year2020.day13.reader as reader import year2020.day13.solver as solver def test_example_a(): puzzle = (939, [7, 13, None, None, 59, None, 31, 19]) result = solver.solve_a(puzzle) assert_that(result).is_equal_to(295) @pytest.mark.solution def test_so...
import pytest from lib import part1, part2 def test_lib(): assert part1(data) == 5934 data = [3, 4, 3, 1, 2]
class ParkingSystem: # # Instance Variables (Accepted), O(1) time, O(1) space wrt addCar # def __init__(self, big: int, medium: int, small: int): # self.big = big # self.medium = medium # self.small = small # def addCar(self, carType: int) -> bool: # if carType == 1: # ...
"""Tests for the queries utils of the active_users app.""" import pytz from dateutil.relativedelta import relativedelta from datetime import date, datetime from django.test import TestCase from .. import query_utils as utils class QueryUtilsTest(TestCase): longMessage = True def test_get_month_names(self): ...
import cards import player import game import json import csv import os import logging import random from keras.models import Sequential, load_model from keras.layers.core import Dense from keras.optimizers import sgd def initialize_network(): # parameters hidden_size = 40 model = Sequential() # mod...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator 2.3.3...
################################################### ## ## ## This file is part of the MEL code v1.0 ## ## ## ## The contents are covered by the terms of the ## ## BSD 3-clause license included in the LICENSE ## ## file,...
"""Tensorflow Tensor Library Module.""" import logging import tensorflow as tf import tensorflow_probability as tfp log = logging.getLogger(__name__) class tensorflow_backend: """TensorFlow backend for pyhf""" __slots__ = ['name', 'precision', 'dtypemap', 'default_do_grad'] def __init__(self, **kwargs)...
from server_database_connection import mycursor while 1: mycursor = mydb.cursor() mycursor.execute("SELECT code_id FROM process_codes") code_id = mycursor.fetchone() mycursor.execute("SELECT node_id FROM free_node") node = mycursor.fetchone() node_id = mycursor.fetchone() s...
#!/usr/bin/env python3 import configparser import requests import argparse import json import yaml import os import subprocess import shutil from glob import glob # Get config from user dir config_file = os.path.expanduser("~/.puzzlecad") config = configparser.ConfigParser() config.read(config_file) client_id = conf...
from __future__ import print_function from yambopy import * from schedulerpy import * import argparse import os layer_separation = 12 folder = 'gw+bse' yambo = 'yambo' p2y = 'p2y' prefix = 'bn' scheduler = Scheduler.factory def create_save(): #check if the nscf cycle is present if os.path.isdir('nscf/%s.s...
from typing import List from netqasm.lang import instr as ins from netqasm.logging.output import InstrLogger as NQInstrLogger from netqasm.logging.output import QubitGroups, QubitState from netsquid.qubits import qubitapi as qapi from netsquid.qubits.qubit import Qubit from squidasm.sim.glob import QubitInfo, get_run...
from django.core.management.commands.migrate import Command as MigrationCommand from django.db import connection class Command(MigrationCommand): """This command should be used along with t_manage.py""" def add_arguments(self, parser): parser.add_argument("schema", type=str) super().add_argum...
""" The flask application package. """ from flask import Flask from os import environ from applicationinsights.requests import WSGIApplication app = Flask(__name__) app.wsgi_app = WSGIApplication(environ.get('APPINSIGHTS_INSTRUMENTATIONKEY'), app.wsgi_app) import python_webapp_flask.views
from __future__ import annotations import logging from functools import cached_property import cirq import numpy as np from factor import MExp, approximate_fraction, size_in_bits, prepare_state, bits_to_integer class OrderFinder(object): def __init__(self, a: int, N: int): """Class that finds the multi...
from typing import Optional from fastapi import APIRouter, File, HTTPException from fastapi.param_functions import Query from starlette.responses import Response, FileResponse from starlette.requests import Request from config import gender_classifier, SHOW_ALL, logger, ALLOWED_FILE_EXTENSIONS, DO_SENTIMENT_ANALYSIS fr...
import os import shutil import subprocess import unittest from pyspark.sql import SparkSession class ValidateJsonSpecs(unittest.TestCase): DRUGS_REFERENCES_PATH = "../data/gold/drugs_references.json" ANALYTICS_PATH = "../data/gold/" def test_should_compute_drugs_analytics(self): drugs_analytics_...
# Generated by Django 3.1 on 2020-10-10 09:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('backend', '0012_cafe_close'), ] operations = [ migrations.CreateModel( name='age', fields=[ ('id', mod...
import torch def hook_DCN_v2_Ref(m, x, y): # Only modulated_deform_conv2d() is ignored in feature flip fusion, # same as default DCNv2. # conv Flops = 2 x k^2 x Cin x Cout x W x H # dcn Flops = + W x H x k^2 x 13 + W x H x k^2 x 9 x Cin (bilinear interpolate, 9 -> 6 for MACs) # or just: ->0 + W x ...
# flake8: noqa F401 from stable_baselines.common.vec_env.base_vec_env import AlreadySteppingError, NotSteppingError, VecEnv, VecEnvWrapper, \ CloudpickleWrapper from stable_baselines.common.vec_env.dummy_vec_env import DummyVecEnv from stable_baselines.common.vec_env.subproc_vec_env import SubprocVecEnv from s...
import pytube #fin des imports print("Entrez le lien de votre video youtube") lien = input() youtube = pytube.YouTube(lien) video = youtube.get_videos() s = 1 for v in video: print(str(s)+". "+str(v)) s += 1 print("Entrez la qualitée de votre video:") n = int(input()) vid = video[n-1] print("Entrez...
from django.utils.translation import ugettext_lazy as _ from mayan.apps.task_manager.classes import CeleryQueue from mayan.apps.task_manager.workers import worker_b queue_parsing = CeleryQueue( name='parsing', label=_('Parsing'), worker=worker_b ) queue_parsing.add_task_type( dotted_path='mayan.apps.document...
# coding: utf-8 import os from django.shortcuts import redirect, render_to_response, get_object_or_404, RequestContext from django.core.urlresolvers import reverse import composer import writer from models import Song def index(request): return render_to_response('composer/index.html', { 'song_count':...
import datetime import os import shutil from typing import Dict import pytest from config import LOG_PATH from utils import logger as _logger from utils.crypto import hmac_sha1_encode from utils.datetime_utils import ( _date, _datetime, _strftime, datetime_range, datetime_today, is_within_a_wee...
height = input('How tall are you, in inches? ') height = int(height) if height >= 36: print('\nYou\'re tall enough to ride!') else: print('\nYou\'ll be able to ride when you\'re a little older.')
from django.apps import AppConfig class GhostapiConfig(AppConfig): name = 'ghostapi'
import logging import subprocess import restic.errors logger = logging.getLogger(__name__) def execute(cmd): logger.debug('Executing restic command: %s', str(cmd)) try: process = subprocess.run(cmd, capture_output=True, text=True, ...
from .criterions import *
REVISION = 'r0.1.18 beta' DATE = '2018/08/02'
# Code generated by `typeddictgen`. DO NOT EDIT. """V1beta1EndpointSliceDict generated type.""" from typing import TypedDict, List from kubernetes_typed.client import V1ObjectMetaDict, V1beta1EndpointDict, V1beta1EndpointPortDict V1beta1EndpointSliceDict = TypedDict( "V1beta1EndpointSliceDict", { "add...
from time import time #define NONE = 0 WHITE = 1 BLACK = 2 SIZE = 8 PLAYER = BLACK # PLAYER = WHITE NUM = 1000 board = [[NONE for i in range(SIZE)] for i in range(SIZE)] turn = BLACK def printb(): print(end="\n ") for i in range(SIZE): print(" ", i + 1, end="") print("\n -------...
# ---------------------------------------------------------------------- # Collections manipulation # ---------------------------------------------------------------------- # Copyright (C) 2007-2017 The NOC Project # See LICENSE for details # ---------------------------------------------------------------------- # Pyt...
""" This example introduces the use of TFLearn functions to easily summarize variables into tensorboard. TFLearn can summarize: - Loss / Accuracy: The model loss and accuracy over training steps. - Activations: Histogram of operation output values.(Requires to add each activation to monitor into tf.Graphkeys.ACTIV...
#v2.1.0 #https://github.com/romanvm/script.module.simpleplugin/releases from simpleplugin import *
from pathlib import Path from os.path import dirname import pytest import miniflask # noqa: E402 def init_mf(): return miniflask.init(module_dirs=str(Path(__file__).parent / "modules"), debug=True) all_modules = ["otherdir", "otherdir.module2", "parentdir", "parentdir.module1", "parentdir.module2", "parentdir....
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: if not nums: return [] res, i, start = [], 0, 0 while i < len(nums)-1: if nums[i]+1 != nums[i+1]: res.append(self.printRange(nums[start], nums[i])) ...
# -*- coding: utf-8 -*- # # ke_model.py # # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.o...
# Copyright 2020 The TensorFlow 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/licenses/LICENSE-2.0 # # Unless required by...
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from __future__ import absolute_import, division, print_function from cryptography import utils from cryptography.exceptions import ( ...
from utility import db_access films = db_access.list_of_all_films() stores = db_access.list_of_all_stores() template = "{:>5} {:30} {:>15} {:>15} " row = template.format("ID", "Title", "In Inventory", "Rentals") print(row) for film in films: film_id = film['film_id'] inventory = db_access.inventory_for_fi...
#python standard library import os #this package from iperflexer.iperfparser import IperfParser from iperflexer.iperfexpressions import HumanExpression, ParserKeys, CsvExpression import iperflexer.oatbran as bran from iperflexer.coroutine import coroutine class HumanExpressionSum(HumanExpression): """ Chang...
import numpy as np import matplotlib.pyplot as plt import scipy.stats as st # from scipy.special import erf # Global variables that were just used in main number_of_iterations = 100 z_range = 8 r = 0.9 r_s = 0.9 mean_gen = 0 sd_gen = 1 k_val = -2 percent_step = 0.33 # Global variables that are used in here (the mod...
from itertools import chain class Instrumento(): def tocar_individual(self): raise NotImplementedError('Deve ser implementado') class Violao(Instrumento): def tocar_individual(self): return 'Blem' class Tambor(): def __init__(self): self.flag = False def tocar_individual(s...
import hashlib import json import os import shutil import subprocess import yaml from .zulip_tools import parse_os_release, run ZULIP_PATH = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) ZULIP_SRV_PATH = "/srv" PUPPET_MODULES_CACHE_PATH = os.path.join(ZULIP_SRV_PATH, "zulip-puppet-cac...
# -*- coding: utf-8 -*- """ CryoSolver package - Simulation example @author: Sofiya Savelyeva, Steffen Klöppel TU Dresden 2020 """ """ ......................................................................... Calculation of a turbine """ ### REMOVE IF PACKAGE IS INSTALLED import sys path = '../' if (pa...
import warnings warnings.filterwarnings("ignore") import pandas as pd import numpy as np from sklearn.decomposition import PCA from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from scipy.signal import savgol_filter from sklearn.base import BaseEstimator, TransformerMi...
import numpy as np import torch as t import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from .decoder import Decoder from .encoder import Encoder from selfModules.embedding import Embedding from utils.functional import kld_coef, parameters_allocation_check, fold from beam_searc...
#!/usr/bin/env python3 import ness6rest import argparse nessus_url = "https://localhost:8834" parser = argparse.ArgumentParser() parser.add_argument('--login', required=True) parser.add_argument('--password', required=True) args = parser.parse_args() scan = ness6rest.Scanner(url=nessus_url, login=args.login, passw...
import tcod from input_handlers import handle_keys from game_states import GameStates from render_functions import clear_all, render_all, RenderOrder from map_objects.game_map import GameMap from fov_functions import initialize_fov, recompute_fov from entity import Entity, get_blocking_entity_at_location from compon...
#write import statement for Die class from src.homework.homework9.die import Die ''' Create a Player class. ''' class Player: def __init__(self): ''' Constructor method creates two Die attributes die1 and die2 ''' self.die1 = Die() self.die2 = Die() def ro...
import pandas as pd import numpy as np from .representation import DGM from .factors import TableCPD from .data_preparation import DiscreteDataPreparer class ParameterEstimator: def fit(self, graphical_model, data: pd.DataFrame, **options): raise NotImplementedError() class MleParameterEstimator: def ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import faiss import numpy as np from scipy.sparse import csr_matrix def get_prototypes(Y, Wx, B, num_pts_per_cluster): """ Gets Z from embeddings and centroids Args: Y: sparse label matrix, (N...
from setuptools import setup, find_packages from setuptools.command.install import install with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setup( name="hyperparameter", version="0.2.0", description= "A hyper-parameter library for researchers, data scientists and m...
import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) sys.path.insert( 0, os.path.abspath( os.path.join(os.path.dirname(__file__), "../mkdocs_exclude_search") ), ) # pylint: disable=wrong-import-position,unused-import from plugin import ExcludeSear...
# Usage: >> python search_center_region.py --index index.csv --query queries/sample_query.jpg --result-path datacars # or >> py search_center_region.py -i <your_index_filename> -q <your_query_image> -r <your_dataset> # import the necessary packages from module.colordescriptor import ColorDescriptor from module.searche...
CHANGE_DATAMGR_PERM = 'Change Session Data Manager' MGMT_SCREEN_PERM = 'View management screens' ACCESS_CONTENTS_PERM = 'Access contents information' ACCESS_SESSIONDATA_PERM = 'Access session data' ARBITRARY_SESSIONDATA_PERM = 'Access arbitrary user session data' CHANGE_IDMGR_PERM = 'Change Browser Id Manager' MANAGE_C...
from PySide2.QtCore import Qt, QCoreApplication from PySide2.QtGui import QShowEvent from PySide2.QtWidgets import QDialog, QDialogButtonBox, QVBoxLayout, QFormLayout, QLabel, QComboBox, \ QWidget, QSizePolicy from livia.input.DeviceFrameInput import Device from livia_ui.gui.views.utils.DevicePanel import DevicePa...
import math import pandas as pd import numpy as np import rpy2.robjects as robj import rpy2.robjects.packages as rpack r = robj.r from sklearn import datasets, preprocessing, metrics, ensemble from ..util.data import install_package, fix_types, convert_to_numpy_columns, import_or_install from ..util.formula import ad...
import json import jsonlines import os import time import tensorflow as tf from tqdm import tqdm import numpy as np from nets import c3d as model from config import PredConfig as C from dataset import load_train_dataset, load_test_dataset # Basic model parameters GPU_LIST = [ int(i) for i in os.environ["CUDA_VISIBL...
#LING380 Final Project #Chatbot import random import pickle from nltk.corpus import wordnet as wn from parsing import parser botDict = {} #''' with open('responses.p','rb') as f: # opens (and closes) file to read (r) as bytes (b) botDict = pickle.load(f) #''' def train(key, sent): parsedSe...
#!/usr/bin/env python # -*- coding: UTF-8 -*- import re import sys import argparse import warnings import collections from flask import current_app from werkzeug.utils import cached_property from . import mimetype from . import compat from .compat import deprecated, usedoc def defaultsnamedtuple(name, fields, defa...
import unittest import numpy as np import torch from scipy.spatial import distance class test_utils(unittest.TestCase): def test_import(self): import utils from utils import ddict def test_ddict(self): from utils import ddict # Test basics dd = ddict(a=1.0, b=[1,2]) ...
import requests import time from concurrent.futures.thread import ThreadPoolExecutor from django.core.management.base import BaseCommand from httpbench.header import get_username_header_key from httpbench.throttle import Throttle from typing import Iterator, Tuple HEADER_KEY = get_username_header_key() DEFAULT_TIMEOU...
import asyncio import discord from discord.ext import commands from Cogs import Message from Cogs import DL from Cogs import PickList import urllib import re def setup(bot): # Add the bot bot.add_cog(IntelArk(bot)) class IntelArk(commands.Cog): def __init__(self, bot): self.bot = bo...
#!/usr/bin/env python import rospy from sensor_msgs.msg import Image from mbzirc_comm_objs.msg import ObjectDetection, ObjectDetectionList class MetricsCounter(object): def __init__(self): self.frame_count = 0 self.detection_list_count = 0 self.circle_count = [ 0, 0, ...
from cassandra.query import SimpleStatement from flask import abort from gsrest.db.cassandra import get_session from gsrest.model.addresses import AddressTx, \ AddressOutgoingRelations, AddressIncomingRelations from gsrest.service.entities_service import get_entity, get_id_group from gsrest.service.common_service ...
# coding=utf-8 # Copyright 2020 The Google Research 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 applicab...
from . import singleton_cli from . import atable from . import aanalysis from . import sets from . import isets from . import icompression from . import pgm from . import aanalysis from . import plotdata from . import ray_cluster
import cdms2 import string ############################################################################## # PJG 20130522 # THIS FUNCTION IS EXPECTED TO BE MODIFIED BY USERS. IT IS MEANT TO POINT TO # MODEL OUTPUT CLIMATOLOGIES THAT ARE USED BY THIS PACKAGE, IN PARTICULAR # interpolate_new_model_to_metrics_grid.py ...
"""template demo""" from xtapi import MainApp, Templates, Request app = MainApp() templates = Templates(directory='html') @app.get("/") async def root(request: Request): return templates.render('index.html', {"request": request}) if __name__ == '__main__': app.run(name='template_demo:app', reload=True)
from vtk import * import os.path xmlRootDir = "../../../../VTKData/Data/Infovis/XML/" if not os.path.exists(xmlRootDir): xmlRootDir = "../../../../../VTKData/Data/Infovis/XML/" treeReader = vtkXMLTreeReader() treeReader.SetFileName(xmlRootDir+"vtklibrary.xml") treeReader.SetEdgePedigreeIdArrayName("tree edge") tree...
from fabric.api import * import subprocess main_dir = subprocess.check_output("git rev-parse --show-toplevel", shell=True).rstrip() env.warn_only = True # Testing @task def test_role(puppetrole='docker_test_role', image='centos-7') : """[local] Test a role on the specified OS on a Docker image""" local( 'cd ' + ...
import argparse import os import string import time from string import punctuation import torch as t from model.rvae import RVAE from nltk.corpus import stopwords from nltk.translate.bleu_score import sentence_bleu from pymystem3 import Mystem from rouge import Rouge from stop_words import get_stop_words from torch.au...
"""Support for HomeKit Controller air quality sensors.""" from aiohomekit.model.characteristics import CharacteristicsTypes from aiohomekit.model.services import ServicesTypes from openpeerpower.components.air_quality import AirQualityEntity from openpeerpower.core import callback from . import KNOWN_DEVICES, HomeKit...
# circulaRprint # # Circular Plotter controller for Raspberry Pi # # Author: Oehrly, 2018 # ################################################# # # draws the calculated x-y-points on screen # as it is drawing based on x-y coordinates if stepper class or the calcul...
example = """ # Inline An [external]( https://spec.commonmark.org/0.29/#link-reference-definitions 'Common Mark Spec') link. An [internal](:/bbca0bcbc64541d5bfdbf7678217006e) link. # References An [other external] link. An [other internal] link. [other external]: https://spec.commonmark.org/0.29/#link-reference-defi...
from celery import shared_task @shared_task def hello(): print("hello there!")
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: wxnacy(wxnacy@gmail.com) # Description: import hashlib from urllib.request import urlopen class MD5(): @classmethod def encrypt(cls, text): """ 计算字符的md5摘要 :param str: :return: """ return hashlib.md5(text.enc...
""" Functions to access information about recipy's environment. """ # Copyright (c) 2015-2016 University of Edinburgh and # University of Southampton. from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_l...
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setuptools.setup( name='alpaca_kernel', version='0.1.19', author='Thijn Hoekstra', author_email='t.w.hoekstra@student.tudelft.nl', description='Fork of jupyter_micropython_kernel by goatchurchpr...
from __future__ import annotations import itertools import multiprocessing import os import pickle import string import uuid from collections import defaultdict from dataclasses import dataclass, field from functools import partial from itertools import chain from multiprocessing import get_context from typing import ...
# Development settings from .base import * SECRET_KEY = "0hgq)139a$a!9+$gh^y2#qdtrl)h#lf*u&5(uwz@#82^)-hrbz" DEBUG = True ALLOWED_HOSTS = ["localhost", "127.0.0.1"] DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "BlogDjango", # postgres db name "USER": "k...
from dataclasses import dataclass from cltl_service.backend.schema import TextSignalEvent from emissor.representation.container import Index from emissor.representation.scenario import Modality, TextSignal @dataclass class TripleExtractionTextSignalEvent(TextSignalEvent): confidence: float audio_segment: Ind...
from keras.models import Sequential,Model,model_from_json from keras.models import Model,Sequential, Input, load_model from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D, BatchNormalization, AveragePooling2D, GlobalAveragePooling2D from keras.applications import VGG16, DenseNet201 from keras.optimizers...
from sstcam_sandbox.plotting.setup import Plotter from sstcam_sandbox import get_plot from sstcam_sandbox.d190209_spectra.spe_numba import sipm import numpy as np from tqdm import tqdm class xyPlotter(Plotter): def plot(self, x, y): self.ax.plot(x, y) kwargs = dict( norm=1, eped=0, eped_sigm...
#!/usr/bin/python import MySQLdb # Get connect to MySQL daemon db = MySQLdb.connect(host = "localhost", user = "user", passwd = "userpass", db = "sproject") # Create the Cursor object to execute all queries c = db.cursor() # Ok, do the job! c.execute("SELECT * FROM status") # Save the query result data = c.fe...
#! /usr/bin/env python ''' Solvers and example test cases for Day 10 of the Advent of Code 2021. Problem description: <https://adventofcode.com/2021/day/10> ''' from typing import Iterable, Optional import unittest def part1(lines: Iterable[str]) -> int: ''' Solver for Day 10, part 1 ''' score = 0 ...
### This is test App: manu-hello-world-app## ## ## from __future__ import division, print_function # coding=utf-8 import sys import os import glob import re import numpy as np import time from math import ceil # Keras from keras.models import load_model from imageio import imread from keras.preprocessing import imag...
""" SPDX-Copyright: Copyright (c) Schoening Consulting, LLC SPDX-License-Identifier: Apache-2.0 Copyright 2021 Schoening Consulting, 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://...
from django.test import TestCase from rest_framework.reverse import reverse from rest_framework.test import APIClient from rest_framework.authtoken.models import Token from django.contrib.auth.models import User def noaccess(self): """Expect no unauthorized access to the endpoint""" self.assertEqual(self.clie...
import re from argparse import BooleanOptionalAction from typing import List, Union, Optional from clavier import log as logging from genie_client_cpp.config import CONFIG from genie_client_cpp.remote import Remote from genie_client_cpp.context import Context from . import remove from . import kill from . import buil...
import os import unittest from src import app class BasicTests(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_main_page(self): response = self.app.get('/', follow_redirects=True) self.assertEqual(response.status_code, 200) def registe...
from __future__ import absolute_import import flask from flask import Blueprint import pale RESPONSE_CLASS = flask.Response class ContextualizedHandler(object): """Flask route functions get called with no arguments unless there are arguments specified in the route path. This contextualizer object wraps ...
# importing the modules import turtle import random import time # variables delay = 0.1 score = 0 high_score = 0 screen = turtle.Screen() screen.title("snake game") screen.bgcolor("green") screen.setup(width=700, height=700) screen.tracer(0) # screen border border_pen = turtle.Turtle() border_pen....
#! /usr/bin/env python """ File: Polynomial_dict.py Copyright (c) 2016 Austin Ayers License: MIT Course: PHYS227 Assignment: 7.28 Date: April 3, 2016 Email: ayers111@mail.chapman.edu Name: Austin Ayers Description: Uses a dictionary to hold coefficients, and changes the add function so that it uses a dictionary """ ...