content
stringlengths
5
1.05M
import torch import torch.nn as nn from packaging import version from mmcv.cnn import kaiming_init, normal_init from .registry import INPUT_MODULES from .utils import build_norm_layer def conv1x1(in_planes, out_planes, stride=1): """1x1 convolution""" return nn.Conv2d(in_planes, out_planes, kernel_size=1, ...
# -*- coding: utf-8 -*- # ---------------------------------------------------------------------- # Copyright © 2010, RedJack, LLC. # All rights reserved. # # Please see the LICENSE.txt file in this distribution for license # details. # ---------------------------------------------------------------------- import unitt...
#-*- coding: utf-8 -*- #!/usr/bin/env python from os import path # dirs BASE_DIR = path.dirname(path.realpath(__file__)) + '/' MODULES_DIR = BASE_DIR + 'modules/' AUDIO_DIR = BASE_DIR + 'audio/' # api url (server) SERVER_API_URL = 'http://localhost:3000/' # voice lang LANG = 'en-EN'
""" Main entrypoint for starttls-policy CLI tool """ import argparse import os from starttls_policy_cli import configure GENERATORS = { "postfix": configure.PostfixGenerator, } def _argument_parser(): parser = argparse.ArgumentParser( description="Generates MTA configuration file according to STARTTL...
import numpy as np class ValueLog(): """Implemements a key/value aggregating dictionary log with optional grouping/precision and custom aggregation modes""" def __init__(self): self.log_values = {} def log(self, key, val, agg="mean", scope="get", group=None, precision=None): ...
from time import sleep import threading import datetime import paho.mqtt.client as mqtt #### CONSTANTS #### #MQTTServer="home.bodhiconnolly.com" MQTTServer="192.168.1.100" MQTTPort=1882 waitTime=datetime.timedelta(milliseconds=50) ledTopic="room/lights/strips/" functionTopic="room/function/#" systemTopic="system/fun...
import json import string import random import os import httplib2 import requests # Flask Imports from flask import Flask, render_template, request, redirect, url_for, jsonify from flask import abort, g, flash, Response, make_response from flask import session as login_session from flask_httpauth import HTTPBasicAuth ...
# BaseOperator.py # # Base class for all machines and human operators. # # Attributes: # name # states: a list of states that this operator can be in, at any time. For example: ["busy", idle"] # start_time: the time at which the behavior starts. # # Member functions: # methods to change state, and print the fra...
# coding=utf-8 import os import unittest from parameterized import parameterized from conans.client.conf import default_settings_yml from conans.model.editable_cpp_info import EditableCppInfo from conans.model.settings import Settings def _make_abs(base_path, *args): p = os.path.join(*args) if base_path: ...
from dags.spark_common import SparkJobCfg, spark_job, user_defined_macros, EntityPattern from dags.spark_common import dag_schema_path, hadoop_options, LOCAL_INPUT, LOCAL_DATAWAREHOUSE from datetime import timedelta from airflow import DAG args = { 'owner': 'alexey', 'start_date': '2021-06-10' } dag = DAG( ...
from .mesh import import_mesh from .curve import import_curve from .brep import import_brep #from .default import import_default
#!/usr/bin/python import sdk_common # Block in charge of tagging the release class SDKNewsAndTag(sdk_common.BuildStep): def __init__(self, logger=None): super(SDKNewsAndTag, self).__init__('SDK News & Tag', logger) self.branch_name = self.common_config.get_config().get_branch_name() self.g...
from .ast_transformers import InvertGenerator, transformAstWith from .descriptor_magic import \ wrapMethodAndAttachDescriptors, BindingExtensionDescriptor import six import inspect def coroutine(func): def start(*args, **kwargs): g = func(*args, **kwargs) six.next(g) return g retur...
import re import xmlsec from lxml import etree def parse_tbk_error_message(raw_message): message_match = re.search(r'<!--(.+?)-->', raw_message) if message_match: message = message_match.group(1).strip() match = re.search(r'(.+?)\((\d+?)\)', message) if match: error = mat...
import os import djcelery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'findingaids.settings') os.environ['PYTHON_EGG_CACHE'] = '/tmp' os.environ['VIRTUAL_ENV'] = '/home/httpd/findingaids/env/' djcelery.setup_loader() # from django.core.handlers.wsgi import WSGIHandler # application = WSGIHandler() from django.co...
from acme import Product import random ADJECTIVES = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved'] NOUNS = ['Anvil', 'Catapult', 'Disguise', 'Mousetrap', '???'] def generate_products(n=30, price_range=(5, 10), weight_range=(5, 100)): """Generate n number of products within a specified price and weigh...
import sys, os sys.path.append('/Users/syrus/Proyectos/exercita/website/') sys.path.append('/Users/syrus/Sites/exercita/') os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' TEMPLATE_EXAMPLE = '''<ul> {% for gender in gender_list %} <li>{{ gender.grouper }} <ul> {% for item in gender.list %} ...
""" My purpose in life is to take the NWS AWIPS Geodata Zones Shapefile and dump them into the PostGIS database! I was bootstraped like so: python ugcs_update.py z_16mr06 2006 03 16 python ugcs_update.py z_11mr07 2007 03 11 python ugcs_update.py z_31my07 2007 05 31 python ugcs_update.py z_01au07 2007 08 01 python ugc...
import requests import logging from lxml import html class HTDownloader(): def __init__(self, htid, res, i): self.htid = htid self.i = i self.res = res def get(self): logging.debug("Download image: {}".format(self.i)) return down_img(self.htid, self.i, self.res) ...
import asyncio from contextlib import asynccontextmanager from sys import version_info from typing import AsyncIterator import pytest from aioredis import create_redis_pool from aiohttp_client_cache.backends.redis import DEFAULT_ADDRESS, RedisBackend, RedisCache from aiohttp_client_cache.session import CachedSession ...
from django.contrib import admin from .models import Book, Author, Publisher, Loaned # Register your models here. class BookAdmin(admin.ModelAdmin): list_display = ('name', 'date_added') search_fields = ["name"] ordering = ["name"] admin.site.register(Book, BookAdmin) admin.site.register(Author) admin.site.register...
from .manage import *
#!/usr/bin/env python ## # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
import blocksci import re import sys chain = blocksci.Blockchain("/home/hturki/bitcoin-blocksci.bak") address_file = open("/home/hturki/stackoverflow_addr_raw.txt", "r").read() addresses = address_file[1:-1].split("', '") len(addresses) blocksci_addresses = {} bad_addresses = set({addresses[10], addresses[18], addre...
#!/usr/bin/env python ''' We get the lidar point cloud and use it to determine if there are any obstacles ahead Author: Sleiman Safaoui Email: snsafaoui@gmail.com Github: The-SS Date: Oct 3, 2018 ''' # python from __future__ import print_function import numpy as np import copy import math from numpy import pi # RO...
from rdflib import Literal from .namespaces import BRICK, TAG, OWL parameter_definitions = { "Parameter": { "tags": [TAG.Point, TAG.Parameter], "subclasses": { "Delay_Parameter": { "tags": [TAG.Point, TAG.Delay, TAG.Parameter], "subclasses": { ...
input = """ male(john). republican(john). male(matt). republican(matt). female(joana). republican(joana). female(luise). democrat(luise). moreMaleRepublicans :- #count{X:republican(X), female(X)} < N, #count{Y: republican(Y), male(Y)} = N. """ output = """ male(john). republican(john). ...
from auto_yolo import envs from yolo_air_stage1 import durations, distributions, config readme = "Running simple on addition task." envs.run_experiment( "addition-stage1", config, readme, alg="simple", task="arithmetic2", durations=durations, distributions=distributions )
from singledispatch import singledispatch from sqlalchemy import types from sqlalchemy.dialects import postgresql from sqlalchemy.orm import interfaces from graphene import (ID, Boolean, Dynamic, Enum, Field, Float, Int, List, String) from graphene.types.json import JSONString try: from sqla...
#!/usr/bin/python # TrayIcon # Access to various monitoring capabilities (HIDS, dashboard, ip configuration, network recognition, etc.) # Alerting plugin (IM notifications, irssi, OSSEC) that can help to display and monitor notification informations) # Deamon plugin (sort of tail -f over selected files, RSS gathering...
""" Pipeline object class for EmrActivity """ from .activity import Activity from ..config import Config from .schedule import Schedule from ..utils import constants as const from ..utils.exceptions import ETLInputError config = Config() MAX_RETRIES = config.etl.get('MAX_RETRIES', const.ZERO) class EmrActivity(Acti...
from django.test import TestCase from . models import Urls, Statistics class UrlsTestClass(TestCase): ''' Class that test the characterics of the Urls objects and its methods ''' def setUp(self): ''' Method that runs at the beginning of each test ''' self.url = Urls(shor...
import ipdb import numpy as np import os from multiprocessing import Process, Queue, Lock from moviepy.video.io.VideoFileClip import VideoFileClip as Video import skvideo.measure as skv from glob import glob import csv from tqdm import tqdm def job(item): fn, indir, outdir = item outdir = os.path.splitext(fn....
from biocrnpyler import * kb, ku, ktx, ktl, kdeg = 100, 10, 3, 2, 1 parameters = {"kb": kb, "ku": ku, "ktx": ktx, "ktl": ktl, "kdeg": kdeg} myMixture = BasicExtract(name="txtl", parameters=parameters) A1 = DNAassembly(name="G1", promoter="pBest", rbs="BCD2", transcript="T1", protein="GFP", initial_co...
from django.db import models from django.conf import settings from django import forms # Create your models here. class Dataset(models.Model): name = models.CharField(max_length=200, null=True, blank=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) columns = models.Intege...
""" OpenVINO DL Workbench Class for annotate dataset job Copyright (c) 2021 Intel Corporation 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 ...
from bs4 import BeautifulSoup from contextlib import suppress RUN_EXAMPLE = 2 class Match: """ This class stores information about a class """ def __init__(self, team1: str, team2: str, state, _, score1: int, score2: int): self.team1 = self._sanitize(team1) self.team2 = se...
from django.apps import AppConfig class AwewardsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'awewards'
from setuptools import setup, find_packages with open("requirements.txt") as f: requirements = f.readlines() long_description = "Automated tool to provision Greengrass 2.0" setup( name="ggv2_provisioner", version="0.0.8", author="Gavin Adams", author_email="gavinaws@amazon.com", url="https://...
''' Load the CIOD module tables from DICOM Standard PS3.3, Annex A. All CIOD tables are defined in chapter A of the DICOM Standard. Output the tables in JSON format, one entry per CIOD. ''' from typing import List, Tuple import sys import re from bs4 import Tag from dicom_standard import parse_lib as pl from dicom_st...
import requests import json import yaml def checkDomains(domains): url = 'https://www.virustotal.com/vtapi/v2/url/report' scans = [] for dom in domains: params = {'apikey':getApiKey('vt'), 'resource':dom} try: response = requests.get(url, params=params) scans.append...
from torchvision import models import torch.nn as nn class model(nn.Module): def __init__(self, input_dim, output_dim): super(model, self).__init__() self.restored = False self.input_dim = input_dim self.output_dim = output_dim num = len(input_dim) feature = [] for i in range(num): feature.append( ...
INSTRUCTIONS = """ """ from utils.decorators import time_this @time_this def solution(inputs): """ """ test_case_inputs = [ ]
class SilkObject: __slots__ = [] def __ne__(self, other): return not self.__eq__(other) class SilkStringLike(SilkObject): __slots__ = [] from . import primitives
from .transpose import transpose
from functools import partial from flask import Blueprint, current_app, g from api.client import SecurityTrailsClient, ST_OBSERVABLE_TYPES from api.mappings import Mapping from api.schemas import ObservableSchema from api.utils import get_json, jsonify_data, get_key, jsonify_result enrich_api = Blueprint('enrich', _...
from sqlite3 import dbapi2 as sqlite3 from flask import Flask, request, session, g, redirect, url_for, abort, \ render_template, flash, _app_ctx_stack import requests, os from bs4 import BeautifulSoup # configuration try: DATABASE = 'simply-billboard.db' DEBUG = True SECRET_KEY = 'development key' USERNAME = ...
#!/usr/bin/env python # Copyright 2015 Dmitriy Robota. # # 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 applica...
from settings import * class BonusBox: def __init__(self, data, gui): self.boxID = int(data["boxID"]) self.x = int(data["x"]) self.y = int(data["y"]) self.type = int(data["type"]) self.size = 2 self.gui = gui if self.type == 1: # cargo ...
# Copyright (c) 2016, Ethan White # 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 copyright # notice, this list of conditions and...
from validator.rule_pipe_validator import RulePipeValidator as RPV from validator import rules as R from validator import Validator, validate, validate_many, rules as R def test_rpv_001_simple(): data = "10" # with integer rules = [R.Integer(), R.Size(10)] rpv = RPV(data, rules) assert rpv.execut...
import os import random class Hangman(): def __init__(self): self.word = self.pick_random_word() self.word = self.word.upper() self.hidden_word = ["-" for character in self.word] self.word_length = len(self.word) self.used_letters = [] self.running = True ...
def test_add_pet(client, jwt): r = client.post( "/pets", json=dict( pet_type="cat", name="tospik", breed="persian", owner="emreisikligil" ), headers=dict(Authorization=f"Bearer {jwt}") ) assert r.status_code == 201 body = r....
import asyncio import youtube_dl import urllib.request import datetime from bot_client import * global queue queue = [] global nowPlaying nowPlaying = [] global ytdl_opts ytdl_opts = { 'format': 'bestaudio/best', #'ignoreerrors': True, #'no_warnings': True, #'debug_pr...
# --- import -------------------------------------------------------------------------------------- import os import numpy as np import WrightTools as wt from . import _pulse from ._scan import Scan # --- define -------------------------------------------------------------------------------------- here = os.pa...
import torch from torch import nn from torch.nn import functional as F from typing import List from resnet_layer import ResidualLayer class ConvDecoder(nn.Module): def __init__(self, in_channels: int, embedding_dim: int, hidden_dims: List = [128, 256], ...
from dassl.engine import TRAINER_REGISTRY from dassl.engine.trainer import TrainerMultiAdaptation from dassl.data import DataManager from dassl.utils import MetricMeter from torch.utils.data import Dataset as TorchDataset from dassl.optim import build_optimizer, build_lr_scheduler from dassl.utils import count_num_para...
''' A data model focused on material objects. ''' import synapse.lib.module as s_module class MatModule(s_module.CoreModule): def getModelDefs(self): modl = { 'types': ( ('mat:item', ('guid', {}), {'doc': 'A GUID assigned to a material object.'}), ('mat:spec', (...
from .test_utils import * print('#############################################') print('# TESTING OF MainDeviceVars MODEL FUNCTIONS #') print('#############################################') @tag('maindevicevars') class MainDeviceVarsModelTests(TestCase): def setUp(self): from utils.BBDD import...
from flask import request from .argument import ListArgument class QueryStringParser: """ A class to parse the query string arguments""" @staticmethod def parse_args(qs_args_def): """ Parse the query string """ qs_args_dict = QueryStringParser.args_def_to_args_dict(qs_args_def) ...
from machine import Pin, Timer import utime SOUND_SPEED = 0.0343 # in second CM_TO_INCH = 0.393701 CM_TO_FEET = 0.0328084 trigger = Pin(16, Pin.OUT) echo = Pin(17, Pin.IN) def get_distance(timer): trigger.high() utime.sleep(0.0001) trigger.low() start = 0 stop = 0 while echo.value()...
# Copyright (c) 2019 Microsoft Corporation # Distributed under the MIT software license from ..postprocessing import multiclass_postprocess import numpy as np def test_multiclass_postprocess_smoke(): n = 1000 d = 2 k = 3 b = 10 X_binned = np.random.randint(b, size=(d, n)) feature_graphs = []...
import requests import base64 from datetime import datetime from datetime import timedelta from collections import UserString class RefreshingToken(UserString): def __init__(self, token_url, client_id, client_secret, initial_access_token, initial_token_expiry, refresh_token, expiry_offset=60, p...
#FLM: AT Font Info: Andres Torresi #configurar nombreFamilia='Tagoni' nombreDisenador='Andres Torresi' emailDisenador='andres@huertatipografica.com.ar' urlDisenador='http://www.andrestorresi.com.ar' urlDistribuidor='http://www.huertatipografica.com.ar' year='2012' ## from robofab.world import CurrentFont # all the ...
#import sys import select, queue from .pool import Pool from .io import open_listenfd, sys def main(*args, **kwargs): """ @params: init project """ if len(sys.argv) != 2: print("Usage: %s ports", sys.argv[0]) sys.exit(1) assert len(sys.argv) != 2 port = sys.argv[1] #type: in...
# -*- coding:utf-8 -*- # coding=<utf8> from django.db import models # Модели для логирования действий пользователей с активами class Logging(models.Model): user = models.CharField(max_length=140) request = models.TextField(blank = True, null = True) goal = models.TextField(blank = True, null = True) d...
#%% [markdown] # # Basic of Beamforming and Source Localization with Steered response Power # ## Motivation # Beamforming is a technique to spatially filter out desired signal and surpress noise. This is applied in many different domains, like for example radar, mobile radio, hearing aids, speech enabled IoT devices. #...
import os import shutil import click from datetime import datetime, timedelta from flask import current_app as app from sqlalchemy.sql.expression import false from alexandria.settings.extensions import db __author__ = 'oclay' @click.command() @click.option('--username', prompt=True, help='The username for the admin...
#!/usr/bin/python from singularity.package import calculate_similarity from singularity.utils import check_install import pickle import sys import os pkg1 = sys.argv[1] pkg2 = sys.argv[2] output_file = sys.argv[3] # Check for Singularity installation if check_install() != True: print("You must have Singularity i...
#!/usr/bin/env python """odeint.py: Demonstrate solving an ordinary differential equation by using odeint. References: * Solving Ordinary Differential Equations (ODEs) using Python """ from scipy.integrate import odeint import numpy as np import matplotlib.pyplot as plt # pylint: disable=invalid-name # Solve y''(t...
print('-='*20) print('Analisador de Triângulos') print('-='*20) r1 = float(input('Primeiro Segmento: ')) r2 = float(input('Segundo Segmento: ')) r3 = float(input('Terceiro Segmento: ')) if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2: print('Os segmentos acima PODEM formar um triângulo.') else: print('Os segm...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This command generates cs_pb2.py and cs_pb2_grpc.py files from cs.proto. These files are necessary for the execution of gRPC client and gRPC control server. """ from subprocess import call call("python3 -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. cloud...
from .account import GroupSerializer, UserSerializer from .resource import ResourceSerializer __all__ = ["UserSerializer", "GroupSerializer", "ResourceSerializer"]
#!/usr/bin/python3.7 # Copyright 2020 Aragubas # # 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...
import sys sentence = '' with open(sys.argv[1],'r') as file: for i in file: data = i.split() if (len(data) != 0): if(data[-1] =='E'): sentence += data[0]+" " else: sentence += data[0] ...
from functools import reduce num = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828...
import numpy as np import matplotlib.pyplot as plt x = np.array([1., 2., 3., 4., 5.]) y = np.array([1., 3., 2., 3., 5.]) plt.scatter(x, y) plt.axis([0, 6, 0, 6]) plt.show() x_mean = np.mean(x) y_mean = np.mean(y) num = 0.0 d = 0.0 for x_i, y_i in zip(x, y): num += (x_i - x_mean) * (y_i - y_mean) d += (x_i - x_m...
import pika from collections import deque class Messaging(): def __init__(self, identity): self._connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) self._channel = self._connection.channel() self._queue = None self._identity = identity self._c...
#Desenvolva um gerador de tabuada n = int(input("Tabuada de que número? ")) i = 0 while i < 10: print("{} X {} = {}".format(n, i + 1, (n*(i + 1)))) i = i + 1
# Register your models here. from django.contrib import admin from .models import Photo, Metadata, Album admin.site.register(Photo) admin.site.register(Metadata) admin.site.register(Album)
t = 5 sentences = [] while t: sentences.append(input("Podaj zdanie")+"\n") t -= 1 f = open("sentence.txt", "w") for i in sentences: f.write(i) f.close() f = open("sentence.txt", "a") f.writelines(sentences) f.close() f = open("sentence.txt", "r") for line in f: print(line, end="") f.close() f = open...
import toml output_file = ".streamlit/secrets.toml" with open("project-327006-2314b3476b3a.json") as json_file: json_text = json_file.read() config = {"textkey": json_text} toml_config = toml.dumps(config) with open(output_file, "w") as target: target.write(toml_config)
from setuptools import find_packages, setup setup( name='robotframework-historic', version="0.2.9", description='Custom report to display robotframework historical execution records', long_description='Robotframework Historic is custom report to display historical execution records using MySQL ...
import numpy as np import random import math import cmath import itertools from tqdm import tqdm from PIL import Image from matplotlib import cm def log_density_map(val, max_count): brightness = math.log(val) / math.log(max_count) gamma = 3.2 #7.2 brightness = math.pow(brightness, 1...
from typing import * # extmod/modtrezorcrypto/modtrezorcrypto-bip32.h class HDNode: ''' BIP0032 HD node structure. ''' def __init__(self, depth: int, fingerprint: int, child_num: int, chain_code: bytes, private_key: b...
import django.core.management.base as djcmb import anwesende.room.models as arm import anwesende.users.models as aum class Command(djcmb.BaseCommand): help = "Silently creates group 'datenverwalter'" def handle(self, *args, **options): aum.User.get_datenverwalter_group() # so admin has it on first ...
''' English_digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] Below is marathi numbers list This program will convert the input number into english number ''' marathi_digits = ['०', '१', '२', '१', '४', '५', '६', '७', '८', '९'] a = input("Enter marathi digit: ") if a in marathi_digits: print("English Digi...
# This file is part of sner4 project governed by MIT license, see the LICENSE.txt file. """ storage hosts views """ from datatables import ColumnDT, DataTables from flask import jsonify, redirect, render_template, request, url_for from sqlalchemy import func, literal_column from sqlalchemy_filters import apply_filters...
import platform import sys class AppMapPyVerException(Exception): pass # Library code uses these, so provide intermediate # functions that can be stubbed when testing. def _get_py_version(): return sys.version_info def _get_platform_version(): return platform.python_version() def check_py_version(): ...
''' GaussGammaDistr.py Joint Gaussian-Gamma distribution: D independent Gaussian-Gamma distributions Attributes -------- m : mean for Gaussian, length D kappa : scalar precision parameter for Gaussian covariance a : parameter for Gamma, vector length D b : parameter for Gamma, vector length D ''' import numpy as n...
import torch from .defaults import get_default_config def update_config(config): if config.dataset.name in ['CIFAR10', 'CIFAR100']: dataset_dir = f'~/.torch/datasets/{config.dataset.name}' config.dataset.dataset_dir = dataset_dir config.dataset.image_size = 32 config.dataset.n_cha...
from time import sleep import logging import pytest from common.utils import resize_browser from common.asserts import assert_customer_logo, assert_customer_testimonial, assert_typography, assert_overflowing from common.svb_form import assert_required_fields_top, assert_bad_email_top, assert_non_business_email_top, ass...
# -*- coding: utf-8 -*- import glob import re import json import os import shutil from PIL import Image import numpy as np from keras.preprocessing.image import img_to_array, load_img # 画像サイズ IMAGE_SIZE = 224 # チャネル数 CHANNEL_SIZE = 3 # ラベル作成 def make_label_list(): # ディレクトリのパスを取得 dir_path_list = glob.glob('im...
from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): password1 = forms.CharField( label= ("Password"), strip=False, widget=forms.PasswordInput, ) password2 = for...
''' Created on Sep 20, 2013 @author: nshearer ''' from ConsoleYesNoQuestion import ConsoleYesNoQuestion class ConsoleActionPrompt(ConsoleYesNoQuestion): '''Present an action prompt on the console''' # def __init__(self, question): # super(ConsoleActionPrompt, self).__init__(question) ...
import sedate from datetime import timedelta, time from itertools import groupby from sqlalchemy import types from sqlalchemy.schema import Column from sqlalchemy.schema import Index from sqlalchemy.schema import UniqueConstraint from sqlalchemy.orm import object_session from sqlalchemy.orm.util import has_identity ...
from collections.abc import Mapping import shelve import random import time class ConcurrentShelf(Mapping): def __init__(self, file_name, time_out_seconds=60): self._file_name = file_name self._time_out_seconds = time_out_seconds self._locked_shelf = None shelf = self._open(write=T...
from flask import Blueprint, request, jsonify from ortools.sat.python import cp_model import numpy bp = Blueprint('optimize', __name__) @bp.route('/', methods=['POST']) def recieve_data(): model = model = cp_model.CpModel() juniors = request.get_json()[0] boat_parameters = request.get_json()[...
import os import re import datetime from mod_python import apache NOW = str(datetime.datetime.utcnow().strftime("%s")) DUMP_DIR="/var/www/html/dump" if not os.path.exists(DUMP_DIR): os.makedirs(DUMP_DIR) def index(req): if not 'file' in req.form or not req.form['file'].filename: return "Error: Please upload a fi...
# Ryan McCarthy, rbmccart@usc.edu # ITP 115, Fall 2020 # Assignment 4 # Description: # Part 1 takes a sentence from the user and counts the number of times a letter or special character appear # this info is returned to the user # Part 1: this gets the sentence sentence = input('PART 1 - Character Counter\nPlease ente...