content
stringlengths
5
1.05M
from django.urls import path from . import views urlpatterns = [ path('', views.operaciones, name='operacion'), path('sumar/<int:x>/<int:y>/',views.suma,name='adicion'), path('restar/<int:x>/<int:y>/',views.resta,name='sustracción'), path('multiplicar/<int:x>/<int:y>/',views.multiplicacion,name='produ...
import pytest from lib.durak.draw_pile import DrawPile @pytest.fixture def cards(): return ["10D", "10C", "2S", "5C", "8D", "2C"] @pytest.fixture def mocked_draw_cards(cards, get_draw_pile_cards): return get_draw_pile_cards(cards) @pytest.fixture def default_parameters(): return { "drawn_card...
# Time: O(n) # Space: O(1) # # You are climbing a stair case. It takes n steps to reach to the top. # # Each time you can either climb 1 or 2 steps. # In how many distinct ways can you climb to the top? # class Solution: # @param n, an integer # @return an integer def climbStairs(self, n): prev,...
import pytest from PyQt5.QtCore import QDate from PyQt5 import QtGui from gui.component.calendar.CoolCalendar import CoolCalendar def test_coolcalendar_constructor(qtbot): # Given # When try: CoolCalendar() # Then except Exception: pytest.fail("Could not create CoolCalendar")...
# Copyright (c) 2020 - 2021 Open Risk (https://www.openriskmanagement.com) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to ...
#!/usr/bin/env python # -*- encoding: utf-8 -*- import os.path from flask import current_app, redirect, render_template, request, send_file, url_for from flask.ext.babel import gettext from sqlalchemy.orm.exc import NoResultFound from pokr.cache import cache from pokr.database import db_session from pokr.models.bill...
"""Elastic search indexes for knowledge base.""" import elasticsearch_dsl as dsl from resolwe.elastic.indices import BaseDocument, BaseIndex from .models import Feature, Mapping # pylint: disable=invalid-name # Analyzer for feature identifiers and names, used during boosting. identifier_analyzer = dsl.analyzer('iden...
# coding: utf-8 """ See the :class:`Logger` class. """ from __future__ import absolute_import import logging from ..listener import Listener from .generic import BaseIOHandler from .asc import ASCWriter from .blf import BLFWriter from .canutils import CanutilsLogWriter from .csv import CSVWriter from .sqlite import...
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2019-02-07 17:24 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('contracts', '0002_auto_20180123_1340'), ] operations = [ migrations.AlterFi...
from http import HTTPStatus class MissingFieldError(Exception): def __init__(self, field, instance): self.field = field self.instance = instance def __str__(self): return f'{self.instance.__class__.__name__} object is missing field {self.field._name!r}' class InvalidFieldError(Excep...
class GameStats: game_state = 0 xp = 0 level = 0 solved_exercises = 0
return sum(1 if i in "aeiou" else 2 for i in eval(dir()[0])[0])
from project import db class AddUpdateDelete(): def add(self, resource): db.session.add(resource) return db.session.commit() def update(self): return db.session.commit() def delete(self, resource): db.session.delete(resource) return db.session.commit() def...
from wordcount import wordcount if __name__ == "__main__": wordcount.app.run(debug=True)
""" Client class. Base class for the clients. """ import logging from abc import ABCMeta, abstractmethod from json import dumps as serialize from typing import Any, Callable, Dict, Iterator, List, Optional, Union from apply_defaults import apply_config, apply_self # type: ignore from .config import config from .exc...
import matplotlib matplotlib.use("agg") import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import glob import os import common plt.figure(figsize=(4,2)) summary = pd.read_table(snakemake.input.bio) not_bio_related = summary['name'][summary.not_bio_related == 'x'] packages = pd.read_table(snake...
from brainex.database.genexengine import GenexEngine
import logging from settei.presets.logging import LoggingConfiguration class TestHandler(logging.Handler): records = [] def emit(self, record): self.records.append(self.format(record)) def has_handlers(logger: logging.Logger) -> bool: while logger is not None: for h in logger.handlers...
import threading import pygame from .arenas import TCRArena from .display import Display DEFAULT_GAME = 'tin-can-rally' GAMES = {'tin-can-rally': TCRArena, } class Simulator(object): def __init__(self, config=None, size=(8, 8), frames_per_second=30, background=True): if config is None: ...
from django.urls import path from . import consumers websocket_urlpatterns = [ path('ws/room/<room_id>/post/', consumers.ThreadConsumer), ]
from contextlib import redirect_stdout from line_profiler import LineProfiler from boltons.funcutils import wraps from datetime import datetime def profiledec(func): profiler = LineProfiler() profiled_func = profiler(func) @wraps(func) def nfunc(*args, **kwds): try: return profi...
from rl_ctrnn.rl_ctrnn import RLCtrnn import wandb from behavior.oscillator import Oscillator from rl_ctrnn.ctrnn import Ctrnn from multiprocessing import Process from time import sleep import numpy as np PROJECT = "rl_rule" ITERATIONS = 10000 CTRNN = { "time_constants": {0: 1.0, 1: 1.0}, "biases": {0: -9.7341...
import numpy as np from sklearn.metrics import roc_auc_score class OneClassEvaluate(): def __init__(self): self.gt_list_px_lvl = [] self.pred_list_px_lvl = [] self.gt_list_img_lvl = [] self.pred_list_img_lvl = [] self.img_path_list = [] self.fp_rate = 0.0 s...
# -*- coding: utf-8 -*- # Created by restran on 2017/9/21 from __future__ import unicode_literals, absolute_import import logging import unittest logger = logging.getLogger(__name__) class WhatEncodeTest(unittest.TestCase): def setUp(self): pass if __name__ == '__main__': unittest.main()
#!/usr/bin/env python """ # Author: Shrad Shukla # coding: utf-8 #Author: Shrad Shukla #Usage: This is a module for the BCSD code. #This module bias corrects a forecasts following probability #mapping approach as described in Wood et al. 2002 #Date: August 06, 2015 # In[28]: """ from __future__ import division #import...
# -*- coding: utf-8 -*- """Plotting examples for DBA.""" from sktime.clustering.metrics.averaging import dba from sktime.datasets import load_arrow_head from sktime.datatypes import convert_to def plot_dba_example(): """Plot dba.""" import matplotlib.pyplot as plt X_train, y_train = load_arrow_head(spli...
import json class Block(): def __init__(self, blockData, pruneTransactions=True): # Useful stats for each block blockData['tx_count'] = len(blockData['transactions']) blockData['op_count'] = sum([len(tx['operations']) for tx in blockData['transactions']]) # Avoid excess bloat by re...
import logging from Queue import Empty from multiprocessing import Process, Event from multiprocessing import Queue as mQ from threading import Thread from Queue import Queue as Q from time import sleep import praw from wsgi.engine import get_reposts_count from wsgi.scripts import GET_USER_AGENT_R from wsgi.scripts....
from .feeder import Feeder, SimpleSEFeeder, UrlListFeeder from .parser import Parser from .downloader import Downloader, ImageDownloader from .crawler import Crawler __all__ = [ 'Crawler', 'Downloader', 'ImageDownloader', 'Feeder', 'SimpleSEFeeder', 'UrlListFeeder', 'Parser' ]
# %% 플로이드-와샬 import numpy as np import math import itertools as it from numpy.lib.function_base import copy def solution(N, road, K): table = [ [math.inf for _ in range(N)] for _ in range(N) ] for a, b, l in road: table[a-1][b-1] = min(table[a-1][b-1], l) table[b-1][a-1] ...
# # This source file is part of the EdgeDB open source project. # # Copyright 2019-present MagicStack Inc. and the EdgeDB 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...
import sys import unittest import datetime import flask from flask.ext.mongoengine import MongoEngine from . import FlaskMongoEngineTestCase class BasicAppTestCase(FlaskMongoEngineTestCase): def setUp(self): super(BasicAppTestCase, self).setUp() db = MongoEngine() class Todo(db.Documen...
import wx from nerven_panels import * from colours import * from consts import * class QualityPanel(NervenPanel): def __init__(self, parent, epoc_mgr): wx.Panel.__init__(self, parent) self.epoc_mgr = epoc_mgr self.pnl = wx.Panel(self) self.init_text() self.init_image() ...
class Config: SECRET_KEY = 'secret' SQLALCHEMY_DATABASE_URI = 'postgresql://postgres:postgres@localhost/db_dev' class TestConfig(Config): SQLALCHEMY_DATABASE_URI = 'postgresql://postgres:postgres@localhost/db_test' def config(env): configs = { 'development': Config, 'testing': TestCo...
#!/usr/bin/python3 import sys, math import matplotlib.pyplot as plt sys.path.append("../") from simulator import * if __name__ == "__main__": # Alkaline battery # 6 Ohm load plt.xlabel('t [h]') plt.ylabel('$U_{Batt}$ [V]') # not adaptive # -> always: T_ON = T_OFF = 50s load = ResistorLoad(6.0, 50.0...
"""includes similarity scores given sentence rep mods """
import sys import numpy as np from matplotlib import pyplot as pl def regression(x, y): from scipy.stats import linregress pl.rc('text', usetex = True) pl.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']}) fit = linregress(np.log10(x), np.log10(y)) d = fit.slope p = 10**fit.interc...
import argparse from dataclasses import fields from config import Config from trainer import Trainer from utils import set_seed def get_args(): parser = argparse.ArgumentParser() for field in fields(Config): name = field.name default = getattr(Config, name) parser.add_argument(f"--{na...
import sys sys.path.append("~/.local/lib/python3.6/site-packages") import healpy as hp import numpy as np import pylab as pl import pysm import matplotlib.pyplot as plt import scipy.stats as st import emcee import incredible as cr from pygtc import plotGTC from multiprocessing import Pool,cpu_count import dill import t...
import re def process_input(file_contents): container = dict() for lines in file_contents: regex_outer_bag = re.compile('((\S+\s){2}(bags))\s(contain)') outside_bag_tuple = re.findall(regex_outer_bag,lines) outside_bag = outside_bag_tuple[0][0].replace(' bags','') regex_i...
import argparse import json import logging import os import requests import sys import csv import re from datetime import datetime from . import config from .classes import files from .classes import nodes from .commands import uploadchannel_wrapper from .exceptions import InvalidUsageException from .exceptions import...
from socialnetwork import db, login_manager from werkzeug.security import generate_password_hash, check_password_hash from flask_login import UserMixin from datetime import datetime @login_manager.user_loader def load_user(user_id): return User.query.get(user_id) class User(db.Model, UserMixin): ...
import numpy as np import torch import torchvision #例子1:torch.tensor():直接导入的方式 flag = False if flag: # 均匀分布 a = np.random.rand(5,2) print(f'ndarray数据类型:{a.dtype}',a) b = torch.tensor(a) print(f'Tensor的数据类型:{b.dtype}',b) #例子2:从numpy创建tensor,改变tensor或numpy的值对方也随之改变 flag = False if flag: r = np...
from torch.nn.functional import embedding from data import dataloader import torch import torchvision.ops as ops import torchvision.models as models import torchvision.transforms as transforms from torch.utils.data import Dataset, DataLoader import os import yaml import shutil import pickle import subprocess import n...
names_list = ['Cecil', 'Brian', 'Edna', 'Gertrude', 'Beverly'] scores_list = [10, 20, 30, 2, 100] zipped = zip(names_list, scores_list) print(list(zipped)) scores_list.pop() zipped = zip(names_list, scores_list) print(list(zipped)) print(dict(zip(names_list, scores_list)))
import json import logging import os import sys import warnings from types import SimpleNamespace from typing import List, Sequence, Union, Optional, Dict import pytorch_lightning as pl from pytorch_lightning.utilities import rank_zero_only from pathlib import Path def get_project_root() -> Path: return Path(__f...
import warnings warnings.filterwarnings('ignore') import pandas as pd import numpy as np import pickle import statsmodels.formula.api as smf import statsmodels.api as sm from statsmodels.tsa.seasonal import seasonal_decompose import seaborn as sns import pandas_profiling import datetime import sqlite3 import calendar ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 13 16:28:42 2019 @author: alankar """ import numpy as np import matplotlib.pyplot as plt def dla_walk(lattice,arrive): #starts a particle from center and moves according to dla rules lattice = np.copy(lattice) #not change the original array a...
import xlwt import pymysql import re import traceback from structure import TABLE, COLUMN, DRIVER class CoTableDriver(DRIVER): def parse(self, s): comment, table_name, columns, engine, charset = "", "None", [], "Default", "Default" table_name, columns = s return comment, table_name, column...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Web Calendar', 'category': 'Hidden', 'description':""" Odoo Web Calendar view. ========================== """, 'author': 'Odoo SA, Valentino Lab (Kalysto)', 'version': '2.0', 'depends'...
#!/usr/bin/env python3 import os import re import sys import urllib.request # api_filename = "projects.md" api_filename = "groups.md" url = "https://gitlab.com/gitlab-org/gitlab-ce/raw/master/doc/api/" + api_filename doc_dir = "doc_tmp" if not os.path.exists(doc_dir): os.makedirs(doc_dir) filename, headers =...
def exponet_factoring(n, a): i = 9 while ((a**i)%n != 1): i += 1 return i
import shutil import os import argparse import csv def read_csv(source_path="./", target_path="./", csv_path="./"): if not os.path.isdir(source_path): print('source_path ', source_path, ' is not a dir') return if not os.path.isdir(target_path): print('target_path ', target_path, ' is n...
from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager from django.conf import settings from django.utils import timezone from markdownfield.models import MarkdownField, RenderedM...
"""Optimization ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import numpy as np import tensorflow as tf def create_optimizer(params): return { "Adagrad": tf.train.AdagradOptimizer, "Adam": tf.train.AdamOptimizer, ...
import abc from typing import AbstractSet class BaseStorage(abc.ABC): """Abstract base class for storing invite link tokens""" def insert(self, token: str, *, payload: dict, max_uses=1): """Insert token to storage. Shoud call super().insert(...)""" if type(payload) != dict: raise...
from django.db.models.signals import post_delete, post_save, pre_save from django.dispatch import receiver from datahub.omis.order.models import Order, OrderAssignee from datahub.omis.order.pricing import update_order_pricing @receiver(pre_save, sender=Order) def update_order_pricing_on_pre_order_save(sender, instan...
from rest_framework import permissions from tacticalrmm.permissions import _has_perm class AuditLogPerms(permissions.BasePermission): def has_permission(self, r, view): return _has_perm(r, "can_view_auditlogs") class ManagePendingActionPerms(permissions.BasePermission): def has_permission(self, r, ...
from django.test import TestCase from konnection.authors.models import Author from django.contrib.auth.models import User class AuthorTestCase(TestCase): def setUp(self): self.expected_display_name = 'Croissants' self.expected_github_url = 'http://www.github.com/croissants' self.expected_a...
from django.test import TestCase from .models import Repo import datetime from django.utils import timezone from django.urls import reverse class RepoModelTests(TestCase): """ class facilitates the creation of repo objects """ def setUp(self): """ method runs before all tests ...
from pydantic import BaseModel, Field, validator from common.constant import Message class UserBaseSchema(BaseModel): username: str = Field(..., max_length=20, description="用户名") class UserRegisterSchema(UserBaseSchema): password: str = Field(..., max_length=100, description="密码") class UserLoginSchema(Us...
# FFT (Log Intensity) # This data transform takes the 3D fourier transform of a 3D dataset # and returns the FFT's log intensity. The data is normalized such # that the max intensity is 1. # # WARNING: Be patient! Large datasets may take a while. def transform_scalars(dataset): from tomviz import utils impor...
# -------------------------------------------------------------------------- # 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. # Changes may cause...
# Titanic Query Practice # Module 4, Sprint 3 # Michael Toce question_list = ["How many passengers survived, and how many died?","How many passengers were in each class?","How many passengers survived/died within each class?","What was the average age of survivors vs nonsurvivors?","What was the average age of each pa...
import patterns as patterns import utils as utils symbol = 'INFY' data = utils.get_symbol_data(symbol = symbol) marubozus = patterns.bullish_marubozu(data = data) marubozu_dates = [d.get('date').strftime('%Y-%m-%d') for d in marubozus] print 'Dates: {}'.format(marubozu_dates)
import sqlite3 import random name = "Nyaa" titles = [ "Missing Link of the Annihilator -Absolute Zero-", "Epigraph of the Closed Curve -Closed Epigraph-", "Protocol of the Two-sided Gospel -X-day Protocol-", "Solitude of the Mournful Flow -A Stray Sheep-", "Solitude of the Astigmatism -Entangled Sh...
line=input() line=line.split(" ") a=int(line[0]) b=int(line[1]) while(a!=b): if(a>b): a=int(a*0.5) if(a<b): b=int(b*0.5) print(a)
""" This is a file for importing basic libraries, which I use continuously. """ #Python library import numpy as np import pandas as pd #My library import jchem reload(jchem)
# File: C (Python 2.4) from pandac.PandaModules import * from direct.interval.IntervalGlobal import * from direct.actor.Actor import Actor from direct.directnotify.DirectNotifyGlobal import directNotify from direct.showbase.PythonUtil import ScratchPad from direct.task import Task from pirates.leveleditor import NPCLi...
from distutils.core import setup setup( name='python-codegen', packages=['python-codegen'], version='0.1', license='MIT', description='Python code generator written in Python', author='Alejandro Gonzalez', author_email='alejandro@gonzaleze.com', url='https://github.com/gonzalejandro/pyt...
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. # # This source code is licensed under the BSD license found in the # LICENSE file in the root directory of this source tree. import copy import os import tempfile from typing import Any, Dict, List, Tuple, Type import unittest import pytest impo...
################################################################################################################################ # *** Copyright Notice *** # # "Price Based Local Power Distribution Management System (Local Power Distribution Manager) v1.0" # Copyright (c) 2016, The Regents of the University of Calif...
#!/usr/bin/env python # encoding: utf-8 """ @version: 0.8 @author: muyeby @contact: bxf_hit@163.com @site: http://muyeby.github.io @software: PyCharm @file: NameNer.py @time: 16-7-27 下午9:25 """ import sys import time from math import log import pickle import os sys.path.append('..') from utils.dataset import read_data...
import dataclasses from typing import Any, get_type_hints import pytest # type: ignore from dataclass_builder import ( OPTIONAL, REQUIRED, MissingFieldError, UndefinedFieldError, build, dataclass_builder, fields, ) from dataclass_builder.factory import _create_fn from tests.conftest impor...
from ..models import *
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from profiles_api import serializers from profiles_api import models from rest_framework import viewsets from .models import UserProfile from rest_framework.authtoken.views import ObtainAuthToken from...
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish...
#CALCULANDO O TOTAL DE SEGUNDOS #DESAFIO 2 print('*DESAFIO 02*') a = int(input("digite a quantidade de dias!")) b = int(input("digite a quantidade de horas!")) c= int(input("digite a quantidade de minutos! ")) d = int(input("digite a quantodade de segundos! ")) ds = a * 86400 hs = b * 3600 ms = c * 60 print("a quanti...
from .base import QA import glob import os import collections import numpy as np import fitsio import multiprocessing as mp import scipy.ndimage from astropy.table import Table import desiutil.log from desispec.maskbits import ccdmask from ..run import get_ncpu def _fix_amp_names(hdr): '''In-place fix of head...
import json, asyncio import aiohttp async def login(username, password, challstr): url = 'https://play.pokemonshowdown.com/action.php' values = {'act': 'login', 'name': username, 'pass': password, 'challstr': challstr } async with aiohttp.ClientSessi...
import pytest from manorm.region import GenomicRegion, ManormPeak, GenomicRegions def test_region_init(): region = GenomicRegion(chrom='chr1', start=1, end=100) assert region.summit == 50 region = GenomicRegion(chrom='chr1', start=1, end=100, summit=51) assert region.summit == 51 with pytest.raise...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'GUI.ui' # # Created by: PyQt5 UI code generator 5.10.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_mainWindow(object): def setupUi(self, mainWindow): mainWindow.s...
from openerp import fields, models, api, _ class dteEmail(models.Model): ''' Email for DTE stuff ''' _inherit = 'res.company' dte_email = fields.Char('DTE Email', related='partner_id.dte_email') dte_service_provider = fields.Selection( ( ('', 'None'), ...
from sklearn.linear_model import Ridge import sys from social_features import get_social_features from social_features import get_reply_only_social_features import time from collections import * import re import pickle import numpy as np from sklearn.preprocessing import Imputer def main(): input_file = sys.ar...
from cffi import * from pkg_resources import * from collections import Iterable from weakref import * import sys ffi = FFI() _weakkey_dict = WeakKeyDictionary() def _castToPtr2(x, _type): if isinstance(x, ffi.CData): if _type.item==ffi.typeof(x): return ffi.addressof(x) return x if isinstance(x, Iterable): ...
"""plugin""" # -*- coding:utf-8 -*- from .nmapparser_alivehosts import NmapParserAliveHosts from .nmapparser_openports import NmapParserOpenPorts
import logging import threading import time from lib.globals import LOGGER_TAG import lib.emotions_library class EmotionsDisplayer(threading.Thread): def __init__(self, name): super(EmotionsDisplayer, self).__init__(name=name) self.logger = logging.getLogger(LOGGER_TAG) self.execute_comma...
from tools.utils import StopWatch def create_stop_watch()->StopWatch: return StopWatch()
import random # random 메소드 사용을 위해 import a = random.sample(range(1, 10), 5) # 1<= x < 10의 난수 5개 리스트로 생성 print(a) # 정렬 전 리스트 def quickSort(a, start, end):# 재귀함수용 함수 선언(리스트, 시작인덱스, 종료인덱스) # print(a) if start < end: # 시작 인덱스 보다 끝 인덱스가 클 경우 left = start # left 변수에 시작 인덱스 할당 pivot = a[end] # //piv...
# MIT License # # Copyright (c) 2020 NightChips64 # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge,...
"""Recalibration utilities under the prior probability shift assumption.""" import numpy as np from numpy.typing import ArrayLike def recalibrate( predictions: ArrayLike, *, training: ArrayLike, test: ArrayLike ) -> np.ndarray: """Recalibrate the probabilities predicted by a classifier under the prior pro...
#-*- coding: utf-8 -*- # --------------------------------------------------------------------# # --------------------------------------------------------------------# # ---------- Made by pablo Arias @ircam on 11/2015 # ---------- Copyright (c) 2018 CREAM Lab // CNRS / IRCAM / Sorbonne Université # ---------- # -------...
from django.urls import path from . import views app_name = 'learn' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('exams/', views.ExamListView.as_view(), name='exams'), path('notes/', views.NotesListView.as_view(), name='notes'), path('mathematics/exams/<int:pk>/', views.Mat...
begin_unit comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl|'\n' comment|'# not use this file except in compliance with the License. You may obtain' nl|'\n' comment|'# a copy of the License at' nl|'\n' comment|'#' nl|'\n' comment|'# http://www.apache.org/licenses/L...
import os import tempfile import unittest import mock from harbinger.common.utils import Utils from harbinger.executors.yardstick import YardstickExecutor class TestYardstickExecutor(unittest.TestCase): def setUp(self): self.mock_framework = mock.Mock() self.mock_framework.name = 'test_framework...
from bottle import template def page(config, backend, state, **kwargs): # accepts lists of warnings, errors, infos, successes for which we'll show # blocks kwargs['events_count'] = backend.get_events_count() kwargs['add_urls'] = state['add_urls'] kwargs['remove_urls'] = state['remove_urls'] re...
# White Balance correction function by Monica Tessman and Malia Gehan import cv2 import numpy as np from . import print_image from . import plot_image from . import apply_mask from . import fatal_error def white_balance(device, img, debug=None, roi=None): """Corrects the exposure of an image based on its histogr...
# Copyright 2014 - Mirantis, 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 ag...
from flask import Blueprint, jsonify, request from easyagro.domain.budget.use_cases import CreateBudget from easyagro.gateway.budget.database import SqlAlchemyBudgetDatabaseGateway from easyagro.gateway.budget.notification import ( SendGridEmailNotificationGateway, SendGridSmsNotificationGateway) from easyagro.gat...
import datetime as dt import glob import re import camelot import pandas as pd from dateutil.relativedelta import relativedelta pdf = sorted(glob.glob1("pdfs", "*.pdf"))[-1] pars_row_tol = 4.5 pars_cols = ["228, 249, 473"] ext_current = camelot.read_pdf(f"pdfs/{pdf}", flavor="stream", pages="1-end", ...