content
stringlengths
5
1.05M
import stat from medperf.comms import Comms import medperf.config as config from medperf.commands import Login from medperf.utils import storage_path import pytest from unittest.mock import mock_open @pytest.fixture(params=["token123"]) def comms(mocker, request): comms = mocker.create_autospec(spec=Comms) m...
from shutil import copy import os # To list all the files which have more than 100 lines # find ALLIN -name "*.csv" -type f -exec sh -c 'test `wc -l {} | cut -f1 -d" "` -gt "100"' \; -print | tee abc # get the current path path = os.getcwd() # prepare the destination path dest = path + "/FILTERED/" # open the file ...
""" Tests for seed_services_cli.identity_store """ from unittest import TestCase from click.testing import CliRunner from seed_services_cli.main import cli import responses import json class TestSendCommand(TestCase): def setUp(self): self.runner = CliRunner() def tearDown(self): pass d...
"""Unit tests for the nag solver. .. codeauthor:: Derek Huang <[email protected]> """ import numpy as np import pytest # pylint: disable=relative-beyond-top-level from .._fast_gd import nag_solver # mixtures of learning rate schedules and step sizes _nag_learn_rates = [("backtrack", 1.), ("constant", 0.1)] @p...
import sys from geo.calc import Calc, Distance if sys.version_info[0] >= 3: def test_add(): assert Calc().add(2, 3) == 5, 'Should be 5' def test_mul(): assert Calc().multiply(2, 3) == 6, 'Should be 6' def test_power(): assert Distance(2).power(2) == 4, 'Should be 4' else: ...
import os import json from assisted_service_client import ApiClient, Configuration, api, models class InventoryHost: def __init__(self, host_dict): self._host = models.Host(**host_dict) self._inventory = models.Inventory(**json.loads(self._host.inventory)) def get_inventory_host_nics_data(...
from flask import request from flask_jwt_extended import get_jwt_identity, jwt_required from flask_restful import Resource from ...models import Client, User from ...schemas import ClientSchema from .responses import respond class ClientListResource(Resource): @jwt_required def get(self): schema = C...
# Copyright 2018 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. A copy of the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "LICENSE.txt" file accom...
# Copyright (c) 2019, CRS4 # # 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, distribu...
from onegov.fsi.models.course_event import ( COURSE_EVENT_STATUSES_TRANSLATIONS, COURSE_EVENT_STATUSES ) from onegov.fsi.models.course_notification_template import \ NOTIFICATION_TYPE_TRANSLATIONS, NOTIFICATION_TYPES from onegov.org.layout import DefaultLayout as BaseLayout from onegov.fsi import _ class Form...
from .abc import ( BaseAuth, BaseAuthSession, BaseSync, InvalidAuthSession, ServiceImplementation, ) from .exc import ( ServiceAPIError, ServiceAuthError, ServiceError, ServiceRateLimitError, ServiceTokenExpiredError, ServiceUnavailableError, UserCancelledError, ) from .r...
""" time: 17 min errors: off by one with slice s[mj:mi] forgot to move failure pointer """ class Solution: def minWindow(self, s: str, t: str) -> str: j = 0 matched = 0 ht = {} minRes = float('inf') mi = mj = 0 for c in t: ht[c] = ht.get...
import json from typing import List from pkg_resources import resource_filename class Registry: """ It will get every contract address from the registry contract and return this address with the contract ABI. Attributes web3: web3.Web3 web3 object """ def __init__(self, web3:...
from django.urls import reverse from ....acl import ACL_CACHE from ....admin.test import AdminTestCase from ....cache.test import assert_invalidates_cache from ....threads import test from ....threads.models import Thread from ...models import Category class CategoryAdminTestCase(AdminTestCase): def assertValidT...
import pandas as pd import numpy as np from glob import glob import argparse import os def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--sub-dir', type=str, default='./subs') args, _ = parser.parse_known_args() return args if __name__ == '__main__': args = parse_args()...
# Generated by Django 4.0.1 on 2022-02-04 13:28 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('Clients', '0001_initial'), ('Organizations', '0001_initial'), ] operations = [ ...
import os import logging from pathlib import Path from typing import List, Optional from redis import Redis from photon.common.redis_semaphore import ParamsNT, Semaphore from photon.common.config_context_common import ConfigContextCommon class RedisCommon(object): """ Wrapper class for accessing Redis. ...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse from itertools import zip_longest def replace_oovs(source_in, target_in, vocabulary, source...
s = "731671765313306249192251196744265747423553491949349698352031277450632623957831801698480186947885184385861560789112949495459501737958331952853208805511125406987471585238630507156932909632952274430435576689664895044524452316173185640309871112172238311362229893423380308135336276614282806444486645238749303589072962904...
# _base_ = './faster_rcnn_r50_fpn_1x_coco.py' _base_ = [ '../_base_/models/faster_rcnn_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # fp16 settings fp16 = dict(loss_scale=512.)
#!/usr/bin/env python # encoding: utf-8 import gym import gym_trivial N_ITER = 10 if __name__ == "__main__": env = gym.make("trivial-v0") for i in range(N_ITER): x = env.step(env.action_space.sample()) print(x)
from django.urls import path from web.endpoint import views urlpatterns = [ path('', views.HomeView.as_view(), name='home'), path(r'upload/', views.UploadView.as_view(), name='upload'), path(r'star/', views.StarView.as_view(), name='star'), ]
from .inventory_service import InventoryService, ReservationState, ReservationException
# Assumptions: validate_crud_functions available # Assumes __uripwd is defined as <user>:<pwd>@<host>:<plugin_port> from __future__ import print_function from mysqlsh import mysqlx mySession = mysqlx.get_session(__uripwd) mySession.drop_schema('js_shell_test') schema = mySession.create_schema('js_shell_test') # Crea...
#defines an effect class Effects(): def __init__(self): self.goalPatternList = [] self.effectPatternList = [] self.probList = [] self.valueList = [] def printInfo (self): print("values:", self.valueList) print("probs:", self.probList) print("effectList:"...
import mock from rest_framework import status from rest_framework.test import APITestCase try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse DEFAULT_ACCEPT = ( 'text/html,application/xhtml+xml,application/xml;q=0.9,' 'image/webp,image/apng,*/*;q=0.8...
import redis def sigmaActions(occur): ''' Every small step counts. ''' cpool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True, db=0,) r = redis.Redis(connection_pool=cpool) r.lpush(...
# Copyright (2013) Sandia Corporation. Under the terms of Contract # DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government # retains certain rights in this software. # # This software is released under the FreeBSD license as described # in License.txt import time import random import _gui import json # Pyth...
#!/usr/bin/env python3 ''' @attention: sudo apt-get install python3-pip sudo pip3 install --upgrade setuptools sudo pip3 install smbus sudo pip3 install smbus2 sudo pip3 install unicornhatmini sudo pip3 install bme680 sudo pip3 install pimoroni-sgp30 sudo pip3 install rv3028 sudo ...
from signews.vectorizer import TFIDF from signews.database import Tweet def calculate_idf(): # Obtain all tweets tweet_objects = Tweet.select(Tweet.body) tweets = [tweet.body for tweet in tweet_objects] tf_idf_vectorizer = TFIDF() tf_idf_vectorizer.calculate_idf(tweets) # Store the word and ...
#!/usr/bin/env python 3 # -*- coding: utf-8 -*- # # Copyright (c) 2020 PanXu, Inc. All Rights Reserved # """ ner metric Authors: PanXu Date: 2020/06/27 20:48:00 """ from typing import Tuple, Dict, Union, List from torch import Tensor from torch.distributed import ReduceOp from easytext.metrics import ModelMetric...
# -*- coding: utf-8 -*- # !/usr/bin/python ################################### PART0 DESCRIPTION ################################# # Filename: class_read_csv_input_data_save_word_to_database.py # Description: # # Author: Shuai Yuan # E-mail: [email protected] # Create: 2015-12-06 15:22:38 # Last: __author__ = 'yuens' ...
from dataclasses import dataclass from typing import Optional @dataclass class Endpoint: host: str port: int ssl: bool @dataclass class Credentials: username: str password: str @dataclass class RawCommand: prefix: str command: str args: list[str] class Com...
# Lifo queues # That stands for last in first out. You can imagine this queue like some sort of stack. The element you put last on top of the stack is the first that you can get from it. import queue q = queue.LifoQueue() numbers = [1, 2, 3, 4, 5] for x in numbers: q.put(x) while not q.empty(): print(q.get()...
from tests.utils import W3CTestCase class TestDisplayInlineGrid(W3CTestCase): vars().update(W3CTestCase.find_tests(__file__, 'display-inline-grid'))
#!/usr/bin/python import time from neopixel import * import argparse import sys # LED strip configuration: LED_COUNT = 3 # Number of LED pixels. LED_PIN = 18 # GPIO pin connected to the pixels (must support PWM!). LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz) LED_DMA...
from rest_framework import serializers from .models import DigitalBookPDF class DigitalBookPDFSerializer(serializers.ModelSerializer): class Meta: model = DigitalBookPDF fields = ( 'id', 'book', 'pdf', )
import collections class NyotaUhura: def valid_no_decrease(self, start, end): validcodes = [] for code in range(start, end): code = str(code) decrease = False for pos in range(0, len(code)-1): value1 = int(code[pos]) value2 = int(...
""" A single regression test case. """ import unittest from regression_tests.test_case_name import TestCaseName from regression_tests.utils.os import make_dir_name_valid class TestCase: """A single regression test case.""" # Prevent nosetests from considering this class as a class containing unit #...
# -*- coding: utf-8 -*- """与素数相关的数值函数 """ from rsa._compat import range import rsa.common import rsa.randnum __all__ = ['getprime', 'are_relatively_prime'] def gcd(p, q): """返回最大公约数,辗转相除法 >>> gcd(48, 180) 12 """ while q != 0: (p, q) = (q, p % q) return p def get_primality_testin...
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-04-03 20:45 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('mathswizard', '0035_studentprofile_levelprog'), ] operations = [ migr...
from otree.api import ( models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer, Currency as c, currency_range ) import random author = 'Your name here' doc = """ Your app description """ class Constants(BaseConstants): name_in_url = 'questionaire' players_per_group = None num_rou...
#!/usr/bin/env python ''' This node is for combining all the sensor readings into a message and publishing on /sensor_reading. ''' import rospy from ros_cellphonerobot.msg import Sensors from sensor_msgs.msg import Range def cb(msg): global sensor_readings message = Sensors() message = sensor_readings ...
from data_importers.management.commands import BaseHalaroseCsvImporter class Command(BaseHalaroseCsvImporter): council_id = "E07000029" addresses_name = ( "parl.2019-12-12/Version 1/polling_station_export-2019-11-14cope.csv" ) stations_name = ( "parl.2019-12-12/Version 1/polling_statio...
from .backend import * from .frontend import * from .preprocessing import * from .utils import *
from __future__ import division import json from collections import OrderedDict from datetime import timedelta from decimal import Decimal, ROUND_UP import numpy as np from django.conf import settings from django.contrib.auth.models import User from django.db import connection, transaction from django.db.models impor...
import unittest import os from selenium import webdriver from selenium.webdriver.common.keys import Keys from test.browser import getDriver from app import app from app.model.user import User app_url = app.config.get('APP_URL') app_port = app.config.get('APP_PORT') app_domain = f'{app_url}:{app_port}' class TestLogin...
import config import dataset import os import engine import torch import utils import params import sandesh import pandas as pd import torch.nn as nn import numpy as np from torch.optim import lr_scheduler from model import TweetModel from sklearn import model_selection from sklearn import metrics import transformers ...
"""Use an omero server to authenticate user and gather group info This is heaviliy inspired by https://flask-ldap3-login.readthedocs.io/ """ import logging import omero from flask_ldap3_login import AuthenticationResponseStatus from omero.gateway import BlitzGateway from enum import Enum log = logging.getLogger(_...
from plugins import moderation from plugins import tournaments from plugins import messages from plugins import workshop from plugins.games import *
import json import os from pathlib import Path from subprocess import Popen from typing import Dict import pandas as pd mdk_config = { "analysis_settings_json": "analysis_settings.json", "lookup_data_dir": "keys_data", "lookup_module_path": "src/keys_server/ParisWindstormKeysLookup.py", "model_data_di...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), ] operations = [ migrations.CreateModel( name='Facebook...
__version__ = "0.0.4" __author__ = 'Mario Duran-Vega' __credits__ = 'QOSF' from .q_simulator import *
from typing import Any, Dict import tqdm from pytools.pytorch import distributed from pytools.pytorch.engines.callbacks import Callback from pytools.pytorch.summary import Summary from pytools.pytorch.typing import Engine from pytools.pyutils.logging.group import LogGroup, global_group from pytools.pyutils.logging.ha...
from .interface import Interface __all__ = [ 'Interface', ]
# coding=utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals
""" Author : Abraham Flores File : MCWildFire.py Language : Python 3.5 Created : 12/7/2017 Edited : 12/18/2017 San Digeo State University MTH 636 : Mathematical Modeling """ import math,random,os,glob from random import shuffle from scipy.stats import uniform import matplotlib.pyplot as plt ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Apply various transforms to data in a BIOM-format table. """ from __future__ import absolute_import, division, print_function # standard library imports import argparse from gzip import open as gzip_open # 3rd party imports import biom import numpy as np try: impo...
import base64 import zlib import json import time # python ecdsa 开发库请到 https://github.com/warner/python-ecdsa # 或者 tls 技术支持分享的链接 http://share.weiyun.com/24b674bced4f84ecbbe6a7945738b9f4 # 下载,下载完毕之后进入其根目录,运行下面的命令进行安装, # python setup.py install # 下面是转换私钥格式命令 # openssl ec -outform PEM -inform PEM -in private.pem -out pr...
from abc import ABC, abstractmethod from xquant.portfolio import Portfolio class Strategy(ABC): ''' Strategy -------- An abstract base class serves as the parent class of the user's strategy. The user must create a child class and implement the stock_selection method. ''' def __init__(sel...
from os import path import yaml from so_crawl.crawl import fetch_snippets def _get_name_from_question_link(full_link): # First, throw away the anchor part of the link... anchor_pos = full_link.find('#') if anchor_pos >= 0: full_link = full_link[:anchor_pos] # Now, get the final part of link...
class ArbolBinario: def __init__(self, valor, izquierda=None, derecha=None): self.__valor = valor self.__izquierda = izquierda self.__derecha = derecha def insertar_izquierda(self, valor): self.__izquierda = ArbolBinario(valor) return self.__izquierda def insertar_...
import random from geopandas import GeoDataFrame, GeoSeries from shapely.geometry import Point, LineString, Polygon, MultiPolygon import numpy as np class Bench: param_names = ['geom_type'] params = [('Point', 'LineString', 'Polygon', 'MultiPolygon', 'mixed')] def setup(self, geom_type): if ge...
# coding=UTF-8 # vim: set fileencoding=UTF-8 : ''' DESCRIPTION TennisModel is sample module of classes for simulating tennis tournaments. Contains business logic of tennis Single Elimination Tournaments. ''' import random import model.tournaments as tmt def is_in_interval(value): '''Helper function to t...
""" Utility methods for use during training & evaluation """ def load_dataset(dataset_file, narrative_token, dialog_token, eos_token): sequence = [] with open(dataset_file, "r", encoding="utf-8") as f: for line in f: line = line.strip() if line == "": if len(sequ...
"""Test rsvp module""" from app.tests.basetest import BaseTest class RsvpMeetup(BaseTest): """Rsvps tests class""" def test_if_no_data(self): """Tests if no data is provided in rsvps creation""" respon = self.client.post( "/api/v1/meetups/1/rsvps") self.assertEqual(respon....
#tests models tests_model = { 'RGraph': [ { 'Title': 'Tree Animation', 'Description': """ A static JSON Tree structure is used as input for this visualization.<br /><br /> <b>Click</b> on a node to move the tree and center that node.<br /><br /> ...
# Copyright 2020 ByteDance 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 writin...
from collections import MutableSequence class uniquelist(MutableSequence): """This is a list type that only adds unique values. Otherwise it behaves entirely normally""" def __init__(self, data=None): super(uniquelist, self).__init__() if not (data is None): self._list = list(da...
import os.path from unittest import TestCase import numpy as np from aspire.utils import ( Rotation, crop_pad_2d, get_aligned_rotations, grid_2d, grid_3d, register_rotations, uniform_random_angles, ) DATA_DIR = os.path.join(os.path.dirname(__file__), "saved_test_data") class UtilsTestCa...
#!/usr/bin/python # # Copyright 2010 Google Inc. All Rights Reserved. __author__ = '[email protected] (Ahmad Sharif)' import unittest from automation.common import machine from automation.server import machine_manager class MachineManagerTest(unittest.TestCase): def setUp(self): self.machine_manager = machi...
from pyspark.sql import SparkSession spark = SparkSession.builder.master("local").appName('ReadParquet').config("spark.driver.host", "localhost").config( "spark.ui.port", "4040").getOrCreate() peopleDF = spark.read.json("people.json") # DataFrames can be saved as Parquet files, maintaining the schema information...
# ------------------------------ # 530. Minimum Absolute Difference in BST # # Description: # Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes. # Example: # Input: # 1 # \ # 3 # / # 2 # Output: # 1 # Explanation: # The minimum ...
import tensorflow as tf from garage.tf.models import Model class SimpleMLPModel(Model): """Simple MLPModel for testing.""" def __init__(self, name, output_dim, *args, **kwargs): super().__init__(name) self.output_dim = output_dim def _build(self, obs_input): return tf.fill((tf.s...
import numpy as np import torch from torch.utils.data import Dataset class CBOWDataSet(Dataset): def __init__(self, corpus, pipeline='hier_softmax', nodes_index=None, turns_index=None, vocab_size=None, neg_samples=None, ...
# pylint: disable=W0212 ''' Unit tests for operators.py. These tests should NOT require MPI. ''' import unittest as ut import numpy as np from dynamite.bitwise import popcount, parity, intlog2 class PopcountParity(ut.TestCase): test_cases = [ (0, 0), (1, 1), (2, 1), (3, 2), ...
#import libraries from selenium import webdriver import time import datetime import pandas as pd def automate_sender( driverpath : str = "Path to chromedriver", sender_file_path : str = "sender.txt", sender_df_path : str = "mdcu71_namelist.csv", greeting_file_path : str = "greeting_mdcu.txt", in_pr...
#################### # IMPORT LIBRARIES # #################### import streamlit as st import pandas as pd import numpy as np import plotly as dd import plotly.express as px import seaborn as sns import matplotlib.pyplot as plt import matplotlib.font_manager import plotly.graph_objects as go import functio...
"""Queue classes.""" import os from collections import defaultdict from datetime import datetime import logging import numpy as np import pandas as pd import astropy.coordinates as coord import astropy.units as u from astropy.time import Time, TimeDelta import astroplan from .Fields import Fields from .optimize import...
import pandas as pd import statsmodels.api as sm from patsy import dmatrices from statsmodels.stats.outliers_influence import variance_inflation_factor from .condition_fun import * def vif(dt, y, x=None, merge_coef = False, positive="bad|1"): ''' Variance Inflation Factors ------ vif calculates varianc...
__author__ = "Christian Kongsgaard" __license__ = 'MIT' # -------------------------------------------------------------------------------------------------------------------- # # IMPORTS # Modules # RiBuild Modules import datetime # -----------------------------------------------------------------------------------...
import pytezos from django.contrib.auth.models import Permission from django.test import TestCase from django.urls.base import reverse from apps.wallet.models import ( CashOutRequest, MetaTransaction, PaperWallet, Transaction, Wallet, WalletPublicKeyTransferRequest, ) from project.utils_testing...
# constants.py FRAME_MAX_X = 500 FRAME_MAX_Y = 500 CELL_WIDTH = 10 # basic colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) BLUE = (0, 0, 255) GREEN = (0, 255, 0) RED = (255, 0, 0)
import pathlib from types import ModuleType from jinja2 import Template from omymodels.models.gino import core as g from omymodels.models.pydantic import core as p from omymodels.models.dataclass import core as d from omymodels.models.sqlalchemy import core as s from omymodels.models.sqlalchemy_core import core as sc ...
''' Created on 1.12.2016 @author: Darren '''''' Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you ...
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright 2013 Kitware 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 cop...
import logging import time import cStringIO from PIL import Image from libmproxy.protocol.http import decoded import re def request(context, flow): try: logging.debug("request") if (flow.request.pretty_host(hostheader=True).endswith("docs.google.com")): #logging.debug("Before:") ...
import numpy as np import skimage.color import skimage.filters import skimage.io import skimage.viewer # read and display the original image image = skimage.io.imread('images/coins.png') viewer = skimage.viewer.ImageViewer(image) viewer.show() # blur and grayscale before thresholding blur = skimage.color.rgb2gray(im...
# -*-coding:utf8-*- import random from abenc_bsw07 import * import sqlite3 class RegistrationCenter: def __init__(self): self.groupObj = PairingGroup('SS512') self.cpabe = CPabe_BSW07(self.groupObj) (self.pk, self.mk) = self.cpabe.setup() def initation(self): # Xij key #######...
utc_offset = 8 data_extension = ".ill" '''login token''' login_token = "put your token here" '''path''' illust_data_path = "data\\" illust_thbnl_path = "thumbnails\\" illust_cache_path = "cache\\" auth_head_path = "auth\\" download_path = "your download folder\\" r18_subfolder = "R-18\\" gif_path = download_path grou...
#!/usr/bin/python # -*- coding: utf-8 -*- # ------------------------------------------------------------------------------- # Copyright (c) 2012 Michael Hull. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions...
"""Parsing ISO dates. Originally taken from pyiso8601 (http://code.google.com/p/pyiso8601/) Modified to match the behavior of dateutil.parser: - raise ValueError instead of ParseError - return naive datetimes by default - uses pytz.FixedOffset This is the original License: Copyright (c) 2007 Michael Tw...
# Project Euler Problem 2 # Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million. # Holly Becker # Done 2008-12-20 def main(): a = 1 b = 1 c = a+b total = 0 while c<4000000: if c%2==0: total+=c a=b b=c c=a+b print(total) # 2013-05-01 def even_fibonacc...
from decorators import group from db.models.group import Group from telepot.exception import TelegramError from db.queries import get_max_warns, get_user, group_exist, user_exist from db.inserts import (set_welcome_msg, addto_db, commit_and_close, set_rules, set_chat_link, warn_user, set_max_war...
from flask import current_app from flask.ext.login import UserMixin, AnonymousUserMixin from werkzeug.security import generate_password_hash, check_password_hash from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, \ BadSignature, SignatureExpired from .. import db, login_manager from sqlalchemy ...
""" Created on Fri Jan 07 20:53:58 2022 @author: Ankit Bharti """ from unittest import TestCase, main from cuboid_volume import * class TestCuboid(TestCase): def test_volume(self): self.assertAlmostEqual(cuboid_volume(2), 8) self.assertAlmostEqual(cuboid_volume(1), 1) self.assertAlmostE...
#!/usr/bin/env python # -*- coding: utf-8 -*- # ************************************** # @Time : 2018/11/13 10:16 # @Author : Xiang Ling # @Lab : nesa.zju.edu.cn # @File : RT_Test.py # ************************************** import argparse import os import random import sys import numpy as np import torch...
# Generated by Django 3.0.4 on 2020-03-29 12:26 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='IletisimModel', fields=[ ...
""" Histogram of Oriented Gradients Based on: https://scikit-image.org/docs/dev/auto_examples/features_detection/plot_hog.html """ import matplotlib.pyplot as plt from skimage import exposure, io from skimage.feature import hog image1 = io.imread("image.png") fd, hog_image = hog(image1, orie...
class RemoteAddrMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): self.process_request(request) response = self.get_response(request) # Code to be executed for each request/response after # the view is c...