content
stringlengths
5
1.05M
from xml.etree import ElementTree from scipy import io as sio # To avoid having to write the full string for each XML element, I use this simple dict # The goal is to only specify the name of the parameter (i.g., 'cell_cell_adhesion_strength') # The get_xml_stem() function will take care of the rest using this dict CE...
from bs4 import BeautifulSoup import nltk.data from nltk.tokenize import word_tokenize import glob import gzip import sys tokenizer = nltk.data.load('tokenizers/punkt/dutch.pickle') def good_sentence(s): if len(s) < 4 or s.count(',') > 4: return False else: digits = filter(lambda x:x.isdigit()...
# Generated by Django 2.2 on 2019-05-08 12:43 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("alert", "0001_initial"), ] operations = [ migrations.DeleteModel(name="Registration",), ]
#!/usr/bin/env python # -*- coding: utf-8 -*- import simplejson as json from alipay.aop.api.constant.ParamConstants import * class KoubeiMarketingCampaignRetailDmSetModel(object): def __init__(self): self._campaign_end_time = None self._content_id = None self._operate_type = None @p...
# # Copyright 2014 Quantopian, Inc. # # 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 wr...
import codewars_test as test from solution import filter_list test.assert_equals(filter_list([1,2,'a','b']),[1,2]) test.assert_equals(filter_list([1,'a','b',0,15]),[1,0,15]) test.assert_equals(filter_list([1,2,'aasf','1','123',123]),[1,2,123])
from lassolver.matrices.base import * from lassolver.matrices.iid_gauss import * from lassolver.matrices.uni_invar import * from lassolver.matrices.partial_ortho import *
""" Re-scan until fit achieves desired confidence ********************************************* Problem ======= Scan a peak and, in real time, fit Gaussian model to the data. Repeatedly re-scan the same region until the uncertainty in the Gaussian width parameter, sigma, is below some threshold. Approach ======== U...
from behave_http.environment import before_scenario from example.app import app from example.models import db def before_all(context): context.app = app context._ctx = app.test_request_context() context._ctx.push() def after_all(context): db.session.close() db.session.remove() context._ctx....
from typing import Any, Optional from schema import Optional as SchemaOptional from schema import Or, Schema from dev.helpers import run_command from dev.task import Task class DockerComposeExec(Task): __schema__ = Schema({ 'container': str, 'run': Or(str, [str]), SchemaOptional('env'): ...
from django.apps import AppConfig from actstream import registry from django.contrib.auth.models import User from coreapp.models import Project class CoreappConfig(AppConfig): name = 'coreapp' def ready(self): registry.register(User,self.get_model('ProjectType'),self.get_model('Project'),self.get_model...
#!python3 import itertools import time import math def find_shortest_path(distances:list)->list: num_of_towns = len(distances) shortest_distance_so_far = math.inf shortest_path_so_far = None for path in itertools.permutations(range(0,num_of_towns)): distance = 0 for i in range(1,len(path)): prev_town = pa...
from output.models.ibm_data.valid.d4_3_15.d4_3_15v26_xsd.d4_3_15v26 import Root __all__ = [ "Root", ]
import cv2 import numpy as np def distort_color(img): img_max = np.broadcast_to(np.array(255, dtype=np.uint8), img.shape[:-1]) img_min = np.zeros(img.shape[:-1], dtype=np.uint8) hsv_img = cv2.cvtColor(img.copy(), cv2.COLOR_BGR2HSV).astype(np.int32) # hue hsv_img[:, :, 0] = np.maximum( np....
import scrapy #SCRAPY SPIDER class QuotesSpider(scrapy.Spider): name = "quotes" start_urls = ['https://duma.mos.ru/ru/60/conference?date%5Bfrom%5D=0&date%5Bto%5D=0&sort=date-desc&page=1#results'] page_number = 1 def parse(self, response): text_urls = response.css('td:nth-child(4) .link-im...
import logging as log import cv2 from imutils.video import FPS import numpy as np from collections import namedtuple from argparse import ArgumentParser from openvino.inference_engine import IENetwork, IECore from src import faceDetector, headPos_Estimator from math import cos, sin, pi CPU_DEVICE_NAME = "CPU" Fac...
import pytest import torch import numpy as np from pytorch_memlab import LineProfiler, profile, profile_every, set_target_gpu, clear_global_line_profiler def test_display(): def work(): # comment linear = torch.nn.Linear(100, 100).cuda() linear_2 = torch.nn.Linear(100, 100).cuda() ...
"""UWEC Language Tools corpus.student module Provides functions for defining and managing a student corpus. """ # Python 3 forward compatability imports. from __future__ import print_function from __future__ import division from __future__ import absolute_import from __future__ import unicode_literals import re f...
import numpy as np import keras from layers.conv_deform_1d import ConvDeform1D from layers.ddcconv1d_keras import DDCConv1D def get_layers_of_type(model: keras.models.Model, layer_type: type): return [l for l in model.layers if isinstance(l, layer_type)] def keras_fetch(model, fetches, input_data): inputs =...
import setuptools from pipenv.project import Project from pipenv.utils import convert_deps_to_pip from githubot import __version__ pfile = Project(chdir=False).parsed_pipfile requirements = convert_deps_to_pip(pfile['packages'], r=False) test_requirements = convert_deps_to_pip(pfile['dev-packages'], r=False) entry...
from string import ascii_lowercase, ascii_uppercase config = { 'secret_key': 'asdf', 'short_url_size': 6, 'min_short_url_size': 1, 'max_short_url_size': 50, 'max_attempts_until_short_url_size_increases': 3, 'alphabet': ascii_lowercase + ascii_uppercase + '0123456789', 'app': { 'SQ...
from ..provider import ProviderMixin def test_get_auth_params(): class ParentClass: def get_auth_params(self, request, action): return {} class ChildClass(ProviderMixin, ParentClass): pass result = ChildClass().get_auth_params(None, None) assert "prompt" in result and res...
from tkinter import * from better_profanity import profanity class Slang: def __init__(self,root): self.root=root self.root.title("Slang Detector") self.root.geometry("500x360") self.root.iconbitmap("logo508.ico") self.root.resizable(0,0) def on_enter1(e): ...
# Generated by Django 2.2.4 on 2021-03-29 21:05 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('day_tripper_application', '0002_remove_user_birthday'), ] operations = [ migrations.CreateModel( ...
import aurorawatchuk __author__ = 'Steve Marple' __version__ = '0.2.2' __license__ = 'MIT' class AuroraWatchUK_SS(object): """Take a snapshot of the AuroraWatch UK status. This class mimics the behaviour of the :class:`.aurorawatchuk.AuroraWatchUK` class but its fields are evaluated just once and cache...
from networkx.exception import AmbiguousSolution from RDG import RDG, Node, Edge, plot, save from pprint import pprint from progress.bar import Bar from time import time # table = """TTT F CTT L ATT I GTT V # TTC F CTC L ATC I GTC V # TTA L CTA L ATA I GTA V # TTG L ...
import sys import os import json import ziputil import time from uuid import uuid4 from requests_factory import RequestFactory from base64 import b64encode from cryptography.hazmat.backends import default_backend as new_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives import...
#AUTHOR: Josep Fanals Batllori #CONTACT: u1946589@campus.udg.edu # --------------------------- LIBRARIES import numpy as np import pandas as pd # --------------------------- END LIBRARIES # --------------------------- INITIAL DATA: Y, SHUNTS AND Y0i df_top = pd.read_excel('Dades_v1.xlsx', sheet_name='Topology') # data...
# -*- coding: utf-8 -*- # Author: Daniel Yang <daniel.yj.yang@gmail.com> # # License: BSD 3 clause # reference: # https://github.com/LeelaChessZero/lc0 def MCTS_demo(): pass
# main.py # # Creating a new instance of OmniApp and running it. from omniapp.omniapp import OmniApp from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg from kivy.lang import Builder from pathlib import Path from itertools import chain import matplotlib.pyplot as plt import os # Create ...
"""Validation helpers.""" from sklearn_hierarchical_classification.constants import ( VALID_ALGORITHM, VALID_PREDICTION_DEPTH, VALID_TRAINING_STRATEGY, ) class ParameterValidator(object): """Parameter validation logic for the HierarchicalClassifier class.""" def __init__(self, instance): s...
import json import numpy as np #Importamos las funcion creada para calcular el puntaje de similitud, metodo de pearso from compute_scores import pearson_score #Definición de función para buscar los usuarios similares a el usuario indicado def find_similar_users(dataset, user, num_users): if user not in dataset:...
from torch import nn from torch.nn import functional as F from networks.layers import NoisyLinear, CNNEncoder class DQN(nn.Module): def __init__( self, width: int, height: int, num_frames: int, num_actions: int, noisy_net: bool = False, noisy_std_init: floa...
""" Define the database schema and some helpers. N.B. Schema defaults only applied once object commited. """ from __future__ import absolute_import, print_function from functools import total_ordering import os import subprocess import shlex import time import discord import sqlalchemy as sqla import sqlalchemy.orm a...
import os import random import string import binascii class Func: @classmethod def generate_device_id(cls): device_id = cls.random_hex(4) + \ '-' + cls.random_hex(2) + \ '-' + cls.random_hex(2) + \ '-' + cls.random_hex(2) + \ '-' + cls.random_hex(6) ...
import sbf import numpy as np import matplotlib.pyplot as plt def histogram(surface_file): de, di = read_de_di(surface_file) return np.histogram2d(di, de, bins=200, range=((0, 2.5), (0, 2.5))) def read_de_di(surface_file): f = sbf.read_file(surface_file) return f['d_e'].data, f['d_i'].data def main(...
#!/usr/bin/env python import re from bots import Factory input_pattern = re.compile(r'^value (\d+) goes to bot (\d+)$') p2 = r'^bot (\d+) gives (low|high) to (bot|output) (\d+) and (high|low) to (bot|output) (\d+)$' instruction_pattern = re.compile(p2) instructions = [] factory = Factory() with open('input.txt', 'r'...
from selenium import webdriver from pages.main_page import MainPage from pages.product_page import ProductPage from pages.cart import Cart from selenium.webdriver.support.wait import WebDriverWait class Application: def __init__(self): self.driver = webdriver.Chrome() self.driver.implicitly_wait(...
import logging import os import re import shlex import subprocess import sys import threading logger = logging.getLogger('textpipes') MULTISPACE_RE = re.compile(r'\s+') # built-in resource classes: # make_immediately, default, short # other suggestions: # gpu, gpushort, multicore, bigmem, long def make_override_str...
import numpy as np import keras from keras.models import * from keras.models import Model from keras.layers import * import keras.backend as K from keras import optimizers from keras.preprocessing.image import ImageDataGenerator #from .config import IMAGE_ORDERING from .model_utils import get_segmentation_model, resiz...
# 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...
import matplotlib.pyplot as plt import numpy as np def time_fun(x, slope, shift): return 1/(1+np.exp((slope*x - shift))) shift = 10 slope = 0.001 z = [] x = [i for i in range(50000)] y = [time_fun(i, slope, shift ) for i in x] plt.plot(x,y) plt.show()
import numpy as np import pytest from physt.config import config from physt.histogram1d import Histogram1D from physt import h1 @pytest.fixture def values(): return np.asarray([4, 0, 3, 7.2]) @pytest.fixture(params=[4, np.asarray([4, 0.17, 3, 7.2], dtype=float), [1, 2, 3, 4]]) def array_like(request): retu...
import numpy as np class Board: PATTERN_RULES = ['h', 'v', 'd1', 'd2'] def __init__(self, player1, player2): self._grid = np.zeros((3, 3)) self.player_info = {-1: player1, 1: player2, 0: Player("","")} self.curr_player...
"MultiWii: Python MSP communication Library" import serial import struct from .commands import MSPCommands class MultiWii: def __init__(self, SerialPort:str, BaudRate:int=115200, **kwargs): """ Initialise Serial communication with Flight Controller Takes Serial Port address(required) and ...
import numpy as np import pandas as pd from html_utils import HTMLDataParser class WorldometersHTMLDataParser(HTMLDataParser): def __init__(self, url_to_parse): super().__init__(url_to_parse) self._data_frame = None self._data_frame_parsed = None self._is_parsed = False def pr...
from __future__ import absolute_import, print_function from django.conf import settings CLIENT_ID = getattr(settings, 'PHABRICATOR_CLIENT_ID', None) CLIENT_SECRET = getattr(settings, 'PHABRICATOR_CLIENT_SECRET', None) PHABRCIATOR_DOMAIN = getattr(settings, 'PHABRICATOR_DOMAIN') ACCESS_TOKEN_URL = 'https://{0}/oaut...
import json, os, time, random studentPath = "students.json" coursePath = "courses.json" gradePath = "grades.json" class SMS(): lastName = "" firstName = "" __jsonStudent = [] __jsonCourses = [] __jsonGrades = [] id = -1 def __init__(self, *args, **kwargs): # Loads json files into class va...
import asyncio import csv from collections import deque from datetime import datetime from typing import List, Deque, AsyncGenerator, Any from aat.config import EventType, InstrumentType, Side, TradingType from aat.core import ExchangeType, Event, Instrument, Trade, Order from aat.exchange import Exchange class CSV(E...
#!/usr/bin/env python # coding=utf-8 import sys import os from time import sleep import yfinance as yf import atexit import logging from lifxlan import * from pathlib import Path import traceback from functions.common_constants import * from functions.common_functions import * APP_NAME = "stock_colors" DOW_JONES_AVER...
# https://refactoring.guru/design-patterns/chain-of-responsibility class Handler1(): def execute(self, value): if value == True: # some logic here print("proceeding handler 1") return True else: raise Exception('can not proceed') class Handler2(): ...
from __future__ import with_statement import os.path import re from setuptools import find_packages, setup from setuptools.command.test import test import sys try: with open(os.path.join(os.path.dirname(__file__), 'requirements.txt')) as f: requirements = [i for i in f if not i.startswith('#')] except IOEr...
import wx, cv2, os class imageframe (wx.Frame): def __init__(self, parent, directory, fname, imageannotation, thickness): wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=u"Image Preview", pos=wx.DefaultPosition, size=wx.Size(800, 600), style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL...
"""implement the fips project registry""" import yaml registry = None #------------------------------------------------------------------------------- def load(fips_dir) : """load registry on demand""" global registry if registry is None : with open(fips_dir + '/registry.yml', 'r') as f : ...
from django.shortcuts import render, redirect from django.core.paginator import Paginator from django.db.models.base import ObjectDoesNotExist from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from blog.serializers import CommentSerializer from...
import getpass import json import multiprocessing import os try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse default_config = { 'restart_supervisor_on_update': False, 'restart_systemd_on_update': False, 'auto_update': False, 'serve_default_site': True, '...
#!/usr/bin/env python from setuptools import setup, find_packages setup( name="storages", version="0.1dev1", description="", long_description=open("README.rst").read(), url="https://github.com/dstufft/storages", license=open("LICENSE").read(), author="Donald Stufft", author_email="don...
# Copyright 2019 Contributors to Hyperledger Sawtooth # # 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 ...
#------------------------------------------------------------------------------- # Name: club # Purpose: # # Author: Lorenzo Bolognese # # Created: 29/11/2019 # Copyright: (c) Lorenzo Bolognese 2019 # Licence: MIT #------------------------------------------------------------------------------- cl...
# -*- coding: utf-8 -* # http://58921.com 票房统计数据 import scrapy import json from datetime import date, datetime import sys from ..items import FilmOfficeItem from scrapy.loader import ItemLoader # reload(sys) # sys.setdefaultencoding('utf-8') class FilmSpider(scrapy.Spider): name = "film" page = 0 cust...
# Software License Agreement (BSD License) # # Copyright (c) 2012, Willow Garage, Inc. # 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...
""" Image regularizers """ import tensorflow as tf from ..types import Callable def l1_reg(factor: float = 1.0) -> Callable: """ Mean L1 regularization. Parameters ---------- factor Weight that controls the importance of the regularization term. Returns ------- reg ...
"""Tables related to a session. During a Session, a user acquires data from a single animal. Data is acquired during multiple Recordings. The exact kinds of data acquired depend on a variety of factors and might change over time. """ import datajoint as dj from adamacs import subject schema = dj.schema() @schema cl...
import os from githammer import DatabaseNotInitializedError from .hammer_test import HammerTest class HammerInitTest(HammerTest): def test_plain_init_does_not_create_database(self): self.assertFalse(os.listdir(self.working_directory.name)) def test_update_fails_when_database_not_created(self): ...
import torch def iteration(outputs,fn,rtol=1e-05,atol=1e-08,maxSteps=10,detach=True): last = outputs if detach: last = last.detach().requires_grad_() for _ in range(maxSteps): outputs = fn(last) if (outputs-last).mean()<=atol+rtol*(last.mean()): return outputs if...
import flingclient as fc from flingclient.rest import ApiException from datetime import datetime # Per default the dockerized fling service runs on localhost:3000 In case you # run your own instance, change the base url configuration = fc.Configuration(host="http://localhost:3000") # Every call, with the exception of...
"""The types module contains common type annotation definitions.""" from pathlib import Path import typing as t from typing_extensions import Literal def _get_literal_args(literal_type) -> tuple: # pragma: no cover """Backwards compatible method to get arguments passed to ``Literal`` in lieu of ``typing.ge...
# -*- coding: utf-8 -*- """ Created on Tue May 25 10:24:05 2021 @author: danaukes https://en.wikipedia.org/wiki/Rotation_formalisms_in_three_dimensions https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles """ import sympy sympy.in...
from __future__ import print_function stop = False for c in range(100,1000): for b in range(100,c): for a in range(100,b): if a + b + c == 1000: if a**2 + b**2 == c**2: print("A:", a, "B:", b, "C:", c) print("Problem 9:", a*b*c) ...
"""This module contains the general information for LstorageExtension ManagedObject.""" from ...ucscmo import ManagedObject from ...ucsccoremeta import UcscVersion, MoPropertyMeta, MoMeta from ...ucscmeta import VersionMeta class LstorageExtensionConsts(): pass class LstorageExtension(ManagedObject): """Th...
from dartcms.apps.users.models import UserGroup from dartcms.utils.fields import RteField from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.translation import get_language from mptt.models import MPTTModel, TreeForeignKey class Page...
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals, print_function import datetime from decimal import Decimal from random import randint # Django imports from django.conf import settings from django.core.management.base import BaseCommand from semillas_backend.users.factory import User...
from django.urls import reverse_lazy from .default import * SHOW_ADMIN = False INSTALLED_APPS += [ 'zazi.apps.mpesa_proxy', ] SITE_DOMAIN = MPESA_PROXY_URL = config('MPESA_PROXY_URL', default="", cast=str) API_URL = MPESA_API_URL = config('MPESA_API_URL', default="", cast=str) try: from .local_settings imp...
#!/usr/env python import pysam import os,argparse,sys from argparse import RawTextHelpFormatter from collections import OrderedDict import numpy as np class Arguments(): def __init__(self): splash='pybamer --coverage and read length statistics from your bam file--\n' parser = argparse.ArgumentParser(descri...
"""Module allowing for ``python -m statelint ...``.""" from .cli import main if __name__ == "__main__": raise SystemExit(main())
import discord import random from discord import Permissions from colorama import Fore, Style import asyncio import requests from discord.ext import commands import time import random import string token = "" bot = commands.Bot(command_prefix= ".") @bot.command() async def locateip(ctx, arg): ...
''' Tests for RandomCodons class of analysis module. ''' from nose.tools import assert_equal, assert_not_equal, assert_raises from coral import design, reaction, RNA def test_randomcodons(): ''' This test is pretty basic right now - not sure how much checking can be done for a random DNA base generator....
# generates red version of textures to act as hit models. Will generate a cache in the .minecraft folder # ONLY WORKS ON WINDOWS until I find a better way to get the .minecraft folder import json import os from pathlib import Path from shutil import copyfile from PIL import Image RERENDER = False root_dir = Path('.....
import torch import argparse import os import importlib from torch.utils.data import DataLoader from torch.nn import functional as F from pathlib import Path import pretty_midi as pyd from src.data.clean_data import get_clean_df from src.models.trainer import train from src.models.sketchnet.utils import...
import unittest from transportmodels import Transport, TransModel class TestTransport(unittest.TestCase): def test_solve1(self): t = Transport() t.set_supplies([200, 250]) t.set_demands([100, 150, 200]) t.set_cost_matrix([[90, 70, 100], [80, 65, 75]]) t.solve() x ...
# Linear congruential psuedo random generator. seed = int(input()) A = 9 B = 5 C = 8 current_value = seed next_value = 0 while seed != next_value: next_value = current_value * A next_value = next_value + B next_value = next_value % C print(next_value) current_value = next_v...
from mayan.apps.views.http import URL from .settings import setting_organization_installation_url def get_organization_installation_url(request=None): result = setting_organization_installation_url.value if not result and request: result = URL( netloc=request.get_host(), port=request.get_...
import numpy as np from numpy.fft import fft, ifft import matplotlib.pyplot as plt def correlate(a, b): return ifft(fft(a) * np.conjugate(fft(b))) / len(a) def correlate2(a, b, norm=1): N = len(a) at = list(a) + [0] * N bt = list(b) + [0] * N res = ifft(fft(at) * np.conjugate(fft(bt)))[:N] i...
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-11-22 20:50 from __future__ import unicode_literals import datetime from django.conf import settings import django.contrib.postgres.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): ...
from celery import shared_task from django.conf import settings from django.core.mail import send_mail from django.template.loader import render_to_string @shared_task(bind=True) def send_verification_code(self, email: str, code: str) -> int: """send emails containing verification code Args: email (s...
import json import boto3 import logging logger = logging.getLogger() logger.setLevel(logging.DEBUG) # import requests device_topic = "message" client = boto3.client('iot-data', region_name='ap-southeast-2') logger.info("cold start") def lambda_handler(event, context): code = 400 logger.debug(event) ...
from hpbandster.optimizers.config_generators.random_sampling import RandomSampling
from InquirerPy import prompt, inquirer from InquirerPy.separator import Separator from ...flair_management.skin_manager.skin_manager import Skin_Manager class Prompts: @staticmethod def select_weapon_type(default="exit", **kwargs): skin_data = Skin_Manager.fetch_skin_data() type_choices = [ ...
from . import radiation_test as test_radiation from . import config if __name__ == "__main__": try: test_radiation.test() except AssertionError as err: if config.dev_mode != False: raise AssertionErrror(err) else: raise AssertionError("The flight computer has radiation in it. Please reboot ...
""" test_common_prepare.py """ """ test_prepare_1d_spherical.py """ import os import sys import seekr2.modules.common_base as base import seekr2.modules.mmvt_base as mmvt_base import seekr2.prepare as prepare from seekr2.modules import common_prepare import seekr2.modules.common_cv as common_cv from seekr2.modules....
from abc import ABC, abstractmethod from app.http.http_statuses import HTTP_UNAUTHORIZED, HTTP_CONFLICT, HTTP_BAD_REQUEST, HTTP_NOT_FOUND class HttpException(Exception, ABC): @property @abstractmethod def status(self): pass class BadRequestException(HttpException): @property def status(...
# Copyright 2019 PerfKitBenchmarker 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 appli...
from ProjectTools import ConfigHelper as cfgh class BaseConfigChecker(): ThrowIfConfigFileBad = True CheckedKeyCount = 0 cfg = None def __init__(self, cfg : cfgh.ConfigHelper, throwIfConfigFileBad): self.cfg = cfg self.ThrowIfConfigFileBad = throwIfConfigFileBad def CheckConfig(se...
# ------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. # ----------------------------------------------------------------------...
from aiowing import settings from aiowing.apps.web.models import Record if __name__ == '__main__': with settings.manager.allow_sync(): Record.delete().execute() records = [] for index in range(settings.RECORDS_COUNT): if index % 2 == 0: active = True ...
import subprocess as sub def shutdown(time=0,force=False,warning_off=False): # TODO: solve unix version problem ''' :param time: int , Time in second for shutdown :param force: bool ,True for Force shutdown :param warning_off: bool , True for shutdown without any warning , this option ignore time...
from flask import render_template from app import app @app.route('/') @app.route('/index') def index(): return render_template("index.html", title='Home') @app.route('/senators') def senators(): user = {'nickname': 'Ana'} # fake user senators = [ # array of senators { 'senator': {'ni...
import google.cloud from google.cloud import bigquery import pandas as pd #import datetime #import time def gcs_to_bq(): # Construct a BigQuery client object. client = bigquery.Client() # TODO(developer): Set table_id to the ID of the table to create. table_id = "bda-kict-2020.dataset_asia_...
#!/usr/bin/env python3 # Copyright 2020, Schweitzer Engineering Laboratories, Inc # SEL Confidential """ Various tools for unit tests """ import os import sys import random import unittest import io import logging, logging.handlers import shutil import traceback import subprocess import pathlib import re import traceba...
from typing import Callable, Iterator, List, Union from etuples.core import ExpressionTuple from kanren import run from unification import var from unification.variable import Var from aesara.graph.basic import Apply, Variable from aesara.graph.opt import LocalOptimizer from aesara.graph.unify import eval_if_etuple ...