text
stringlengths
2
999k
class Enemy: def __init__(self, health, attack, defense): self.attack = attack self.defense = defense self.health = health def give(self, attack): self.attack def take(self, defense, health): self.defense self.health class Player(Enemy): def give(self, attack): return a...
""" twtxt.config ~~~~~~~~~~~~ This module implements the config file parser/writer. :copyright: (c) 2016 by buckket. :license: MIT, see LICENSE for more details. """ import click import configparser import logging import os from twtxt.types import Source logger = logging.getLogger(__name__) ...
# -*- coding: utf-8 -*- # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Unittests for chromite.lib.patch.""" from __future__ import print_function import copy import contextlib import itertools...
#!/usr/bin/env python # -*- coding:utf-8 -*- import pickle #dump(object,file),将对象存储到文件里面序列化 group1=("bajiu","wen","qingtian") f1=file('1.pk1','wb') #创建文件1.pk1并以写的方式打开 pickle.dump(group1, f1, True) #使用dump序列化元组并存储在文件中,最后需要添加True才可以保证dump函数执行完成 f1.close() #关闭文件 #load(object,file)将dump()存储在文件里的数据恢复 f2=file('1.pk1','rb')...
from django.contrib.auth import get_user_model,authenticate from django.utils.translation import ugettext as _ from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): """User Object serializer""" class Meta: model = get_user_model() fields = ('email', 'passwo...
__author__ = 'rotem' from setuptools import setup, find_packages setup(name='Probe', entry_points={ 'console_scripts': ['probe=console:main'], }, packages=find_packages(), version='0.1', author='rotem@everything.me', description='Probe - Android Benchmark', install_...
from django.conf import settings from django.conf.urls import include, patterns, url import mkt from . import views def fireplace_route(path, name=None): """ Helper function for building Fireplace URLs. `path` is the URL route, and `name` (if specified) is the name given to the route. """ kwargs ...
""" ASGI config for testproj project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETT...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from django.utils.html import format_html from django.urls import reverse from .models import Post, Category, Tag # Register your models here.@ from typeidea.custom_site import custom_site from .adminforms import PostAdmin...
# Generated by Django 2.2.3 on 2019-08-28 00:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('reporting', '0004_report_delivered'), ] operations = [ migrations.AddField( model_name='reportfindinglink', name='fi...
# Copyright (c) 2016 OpenStack Foundation # # 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 i...
from collections import OrderedDict from typing import Any, Dict, OrderedDict as OrderedDictType from robustbench.model_zoo.cifar10 import cifar_10_models from robustbench.model_zoo.cifar100 import cifar_100_models from robustbench.model_zoo.enums import BenchmarkDataset, ThreatModel ModelsDict = OrderedDictType[str,...
import os.path import shlex from ..generators.bash_script import BashScriptGenerator from .._util import get_appdir_path from . import BuilderBase class AutotoolsBuilder(BuilderBase): _script_filename = "build-autotools.sh" def _get_configure_extra_variables(self) -> list: default_params = [ ...
import os import h5py import numpy as np import matplotlib.pyplot as plt import datetime as dt import collections import librosa import sys path = sys.argv[1] data = np.load(path, allow_pickle=True) x = data['x'] y = data['y'] fig_1 = plt.figure(figsize=(12, 6)) plt.plot(x[100, ...].ravel()) plt.title("EEG Epoch") ...
from utilities import assign_next_frame ,get_data import pandas as pd import numpy as np import matplotlib.pyplot as plt from PIL import Image as PILImage from PIL import ImageFont, ImageDraw from tqdm import tqdm_notebook as tqdm import cv2 from datetime import datetime from yolo import YOLO from resnet_occupancy ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Usage: %(scriptName) <feature_files_prefix> Requires results of save_normalized_fold_dataframes.py """ import os import sys import shutil import numpy as np from skopt import * from train_utils import load_data_folds, eprint feature_columns = ['f1', 'f2', 'f3', 'f...
from flask import Flask, jsonify, request from game2048.displays import Display def get_flask_app(game, agent): app = Flask(__name__) @app.route("/") def index(): return app.send_static_file('board.html') @app.route("/board", methods=['GET', 'POST']) def get_board(): direction = ...
"""Python package description.""" import os from importlib.util import module_from_spec, spec_from_file_location from setuptools import find_packages, setup def readme(): """Load the readme file.""" with open("README.md") as readme_file: return readme_file.read() def get_version_and_cmdclass(packag...
import multiprocessing # noqa from setuptools import find_packages, setup requirements = [] with open("requirements.txt", "r") as in_: requirements = in_.readlines() setup( name="myfitnesspal", version="1.16.5", url="http://github.com/coddingtonbear/python-myfitnesspal/", description="Access hea...
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-04-09 19:16 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_depende...
############################################################################### # PyDial: Multi-domain Statistical Spoken Dialogue System Software ############################################################################### # # Copyright 2015 - 2017 # Cambridge University Engineering Department Dialogue Systems Grou...
""" Module containing helper classes and routines for serialization. """ import aizynthfinder.chem class MoleculeSerializer: """ Utility class for serializing molecules The id of the molecule to be serialized can be obtained with: .. code-block:: serializer = MoleculeSerializer() mo...
import os import subprocess from src.utils.logging import INFO # configure_list = [ # "./unittest/configs/test_transformer.yaml" # ] def get_model_name(path): return os.path.basename(path).strip().split(".")[0] def clean_tmp_dir(path): subprocess.run("rm -rf {0}/*".format(path), shell=True) def rm_tm...
# coding: utf-8 import os import re import shutil import time import pickle import torch import torchvision import numpy as np import matplotlib.pyplot as plt import dataset from dataset import color_attrs, direction_attrs, type_attrs from copy import deepcopy from PIL import Image from torchvision....
# -*- coding: utf-8 -*- from ics import Calendar import requests import arrow from kivy.uix.scrollview import ScrollView from kivymd.uix.label import MDIcon from kivymd.uix.list import MDList, OneLineIconListItem, ILeftBody class GarbageIcon(ILeftBody, MDIcon): def __init__(self, **kwargs): super(GarbageI...
# Copyright 2014 The Oppia 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 applicable ...
from .model import * from .modeling_bart import *
import os file_name = os.path.dirname(os.path.abspath(__file__)) + '/lexicon.csv' fo = open(file_name, 'r', encoding='utf-8') lines = fo.readlines() fo.close() sentiment_dict = {} for line in lines: senti_word, senti_score = line.strip().split(',') sentiment_dict[senti_word] = senti_score def sentiment(word...
# __main__.py import argparse import os import sys from ait.commons.util.settings import DEFAULT_PROFILE, DEBUG_MODE, NAME, VERSION, DIR_SUPPORT from ait.commons.util.common import is_valid_project_name, is_valid_area_name, is_valid_uuid, INGEST_UPLOAD_AREA_PREFIX from ait.commons.util.cmd import Cmd from ait.commons...
from typing import Iterator from allennlp.data import Instance from allennlp.data.dataset_readers import DatasetReader import pandas as pd from ikernels_core.readers.base.instance_generator import InstanceGenerator import logging logger = logging.getLogger(__name__) from ikernels_core.readers.fever.kgat_reading_utils ...
"""Simple program to demo how to use meshtastic library. To run: python examples/pub_sub_example.py """ import sys from pubsub import pub import meshtastic import meshtastic.tcp_interface # simple arg check if len(sys.argv) < 2: print(f"usage: {sys.argv[0]} host") sys.exit(1) def onConnection(interface, ...
import json import pandas as pd import plotly.express as px def load_json(filename): with open(filename, encoding='utf-8') as f: return json.load(f) def load_json_df(filename): j = load_json(filename)["benchmarks"] df = pd.DataFrame(j) df['real_time_micros'] = df['real_time'] / 1000 df[...
# ---------------------------------------------------------------- # Copyright 2016 Cisco Systems # # 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/LICENS...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import io import os import re import sys from setuptools import setup, find_packages try: from semantic_release import setup_hook setup_hook(sys.argv) except ImportError: pass here = os.path.abspath(os.path.dirname(__file__)) with io.open(os.path.join(her...
# A Glob operator is like a like operator but it is case sensitive and does not have any escape operators. import sqlite3 db = sqlite3.connect("assets/Student_records.db") cursor = db.cursor() query = """SELECT NAMES FROM Student_Records where NAMES GLOB 'A*' """ # If you used a*, you can notice that it returns noth...
"""test of pure diffusion Robert A McDougal March 2013 - June 2014 """ from neuron import h, crxd as rxd from matplotlib import pyplot import numpy import __main__ name = __main__.__file__ if name[-3 :] == '.py': name = name[: -3] h.load_file('stdrun.hoc') dend = h.Section() dend.diam = 2 dend.nseg = 101 dend....
# -*- coding: utf-8 -*- # Copyright (c) 2020, Ganga Manoj and Contributors # See license.txt from __future__ import unicode_literals # import frappe import unittest class TestCart(unittest.TestCase): pass
""" Copyright (c) 2018 iCyP Released under the MIT license https://opensource.org/licenses/mit-license.php """ import collections import contextlib import datetime import json import os import re import secrets import string import struct import traceback from collections import OrderedDict from math import floor from...
#!/usr/bin/env python import random import socket import unittest from framework import VppTestCase, VppTestRunner from vpp_sub_interface import VppSubInterface, VppDot1QSubint, VppDot1ADSubint from vpp_ip_route import VppIpRoute, VppRoutePath, VppIpMRoute, \ VppMRoutePath, MRouteItfFlags, MRouteEntryFlags, VppMpl...
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2007 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistribu...
from flask import Flask,render_template app = Flask(__name__) @app.route('/') def index(): return render_template("index.html") @app.route('/layout') def layout(): return render_template("layout.html") @app.route('/dashboard') def dashboard(): return render_template("dashboard.html") if __name__ == '_...
import glob import os import random import sys import random import math import json from collections import defaultdict from cv2 import cv2 from PIL import Image, ImageDraw import numpy as np from scipy.ndimage.filters import rank_filter def dilate(ary, N, iterations): """Dilate using an NxN '+' sign shape. ar...
# Copyright 2020 Google, LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
# -*- coding: utf-8 -*- # pylint: disable=C0103,W0622 ''' Sphinx documentation for Salt ''' import sys import os import types from sphinx.directives import TocTree # pylint: disable=R0903 class Mock(object): ''' Mock out specified imports This allows autodoc to do it's thing without having oodles of req...
class QuecklinkParser: def parse(self): return "quecklink parser"
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Meta data for pyppeteer.""" import logging import os try: # noinspection PyCompatibility from importlib.metadata import version except ModuleNotFoundError: # noinspection PyUnresolvedReferences # <3.8 backport from importlib_metadata import versio...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os sys.path.insert(0, "externals") from csg.core import CSG from itertools import combinations from collections import namedtuple def read_swc_to_edge_list(filename): """Read in a SWC file from Neuromorpho Keywords arguments: filename -- ...
# Copyright 2018 The Exoplanet ML Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else [] PROJECT_CATKIN_DEPENDS = "roscpp;std_msgs".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "-lsubpub".split(';') if "-lsubpub" != "" else [] PROJECT_NAME = "subpub...
# coding: utf-8 # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from collections import defaultdict from typing import Dict, List, Iterable import numpy as np from . import BaseRecursiveDriver from .helper import pb2array, array2pb from ..excepts import NoExplicitMessage from .....
from decimal import Decimal from django.core.exceptions import ValidationError from django.db import transaction from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers from pretix.api.serializers.i18n import I18nAwareModelSerializer from pretix.base.models import ( Item, It...
''' General utilities to sort data structures @author: Thomas Wanderer ''' # Imports from functools import reduce from typing import Dict, Set, Text, List # Types Module = Text Dependency = Set[Module] # Define custom Exception class CyclicReference(Exception): """An exception thrown when items define a cyclic ...
# The MIT License (MIT) # # Copyright (c) 2018 ladyada for adafruit industries # # 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 #...
from project.server import db db.create_all()
from .errors import InvalidFormatError class Contact(object): """ Contains API routes for querying and manipulating contacts. https://devdocs.drift.com/docs/contact-model """ CONTACT_URL_BASE = 'https://driftapi.com/contacts' def __init__(self, client): self.client = client def ...
import torch from yolov3.utils import convert2cpu def parse_cfg(cfgfile): blocks = [] fp = open(cfgfile, 'r') block = None line = fp.readline() while line != '': line = line.rstrip() if line == '' or line[0] == '#': line = fp.readline() continue ...
# Code by Jeff Levy (jlevy@urban.org), 2016-2017 class ValidateFull(): """ Methods for validating EINs from IRS form 990 Full. Each method called by validate_full represents the validation of one column, and comes with the kwarg fixer_display=False, which when set to True will return only a string rep...
""" Wavelet transfroms as provided by GSL """ from pygsl._transform import daubechies, haar, bspline from pygsl._transform import daubechies_centered, haar_centered, bspline_centered from pygsl._transform import wavelet_workspace workspace = wavelet_workspace
import pygame import math from enemies.enemy import Enemy class Shot: def __init__(self, x, y, damage): self.x = x self.y = y self.target = None self.imgs = [] self.animation_count = 0 self.timer = 0 self.speed = 5 self.damage = damage self.mo...
from io import StringIO import numpy as np import os import pandas as pd import json from transformers import AutoTokenizer, AutoModelForSequenceClassification import torch from typing import Any, Dict, List def model_fn(model_dir: str) -> Dict[str, Any]: """ Load the model for inference """ model_pat...
import miepy import numpy as np class interface: def __init__(self, material, z=0): self.material = material self.z = z def get_relative_index(self, wavelength, medium): eps_m = medium.eps(wavelength) eps = self.material.eps(wavelength) return np.sqrt(complex(eps/eps_m)...
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoEcommerce.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: rais...
# Copyright (c) 2012, GPy authors (see AUTHORS.txt). # Licensed under the BSD 3-clause license (see LICENSE.txt) import numpy as np from scipy import integrate from .kern import Kern from ...core.parameterization import Param from ...util.linalg import tdot from ... import util from ...util.config import config # for...
from abc import ABC, abstractmethod from collections import Callable from typing import Set class ParameterBuilder(ABC): def __init__(self): pass @abstractmethod def imports(self) -> Set[str]: pass @abstractmethod def variable_from_input( self, parameter_name: str, variab...
# coding: utf-8 """ Isilon SDK Isilon SDK - Language bindings for the OneFS API # noqa: E501 OpenAPI spec version: 7 Contact: sdk@isilon.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import isi_sdk_8_2_0 from i...
# Copyright 2014 - Mirantis, Inc. # Copyright 2015 - StackStorm, Inc. # Copyright 2016 - Brocade Communications Systems, 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 # # ...
# -*- coding: utf-8 -*- # (C) Datadog, Inc. 2018-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import json from collections import OrderedDict from typing import Any import mock import pytest from six import PY3 from datadog_checks.base import AgentCheck from datadog_check...
# coding: utf-8 """ SQE API No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: v1 Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import re # noqa: F4...
from functools import partial from keras.callbacks import EarlyStopping from modAL.uncertainty import entropy_sampling from experiments.datasets import get_categorical_mnist from modAL import KerasActiveLearner import numpy as np import experiments.al_experiment as exp from examples.models.mnist_models import get_qbc...
import re """saca numero de telefono que empiesa con 7, 8 o 9 y de diez digitos imprime si si el numero es valido y no si no, sin comillas""" # usuario ingrsa los numeros """ asi, import valida_num_telefono 2 9874561232 4567894562 """ phone_numbers = [input() for _ in range(int(input())) ] # this w...
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2019, John McNamara, jmcnamara@cpan.org # import unittest from ...compatibility import StringIO from ..helperfunctions import _xml_to_list from ...worksheet import Worksheet class TestAss...
""" The various models. These all have a common API (except for __init__ which may have extra parameters) and are basically wrappers around the Keras models. """ from collections import OrderedDict import numpy as np import time from batch_cube import BatchCube, position_permutations, color_permutations, action_permut...
import sys MOD = 10**4 + 7 tribonacci = [None] * 10**6 tribonacci[0], tribonacci[1], tribonacci[2] = 0, 0, 1 for i in range(3, 10**6): tribonacci[i] = sum(tribonacci[i - 3 : i]) % MOD n = int(sys.stdin.readline().rstrip()) def main(): ans = tribonacci[n - 1] print(ans) if __name__ ==...
import requests def test_register_new_user(live_server, mailoutbox): """ Registering a new user should send them a verification email. """ data = { "email": "test@example.com", "name": "Test User", "password": "SuperS3curePassword", } response = requests.post(f"{live_se...
#!/usr/bin/env python3 """Generate an updated requirements_all.txt.""" import difflib import importlib import os from pathlib import Path import pkgutil import re import sys from homeassistant.util.yaml.loader import load_yaml from script.hassfest.model import Integration COMMENT_REQUIREMENTS = ( "Adafruit_BBIO",...
""" Operations with addresses """ # pylint: disable=inconsistent-return-statements import hashlib import logging from binascii import hexlify, unhexlify from struct import pack, unpack logger = logging.getLogger('default') ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" def encodeBase58(num...
import sys import os import platform import subprocess import time import mailer import datetime import config import logging from urllib2 import urlopen ip_address = None hosts_list = {} any_device = True plat = platform.system() conf = config.Configuration() logging.basicConfig(filename='app.log',level=logging.DEBU...
# # Copyright (c) 2018 nexB Inc. and others. All rights reserved. # http://nexb.com and https://github.com/nexB/scancode-toolkit/ # The ScanCode software is licensed under the Apache License version 2.0. # Data generated with ScanCode require an acknowledgment. # ScanCode is a trademark of nexB Inc. # # You may not use...
from flask import Flask app = Flask(__name__) app.secret_key ="kajdflajdlfiahiefilaekfilawehfaleflajwiefawmefaiwefilaweflaiwefiaweifjalwef" # this is a random secret key import webApp.required.views
# 2. 编写程序,生成包含20个随机数的列表,然后将前10个元素升序排列,后10个元素降序排列,并输出结果。 rand_list = [random.randint(0, 100) for i in range(20)] sorted_list = [] sorted_list.extend(sorted(rand_list[:10])) sorted_list.extend(sorted(rand_list[10:], reverse=True)) sorted_list """ [9, 12, 34, 38, 43, 57, 85, 98, 98, 100, 92, 89, 65, 60, 52, 51, 31, 20, ...
########################################################################## # # pgAdmin 4 - PostgreSQL Tools # # Copyright (C) 2013 - 2020, The pgAdmin Development Team # This software is released under the PostgreSQL Licence # ########################################################################## import json impo...
import os import unittest from checkov.kubernetes.checks.resource.k8s.EtcdClientCertAuth import check from checkov.kubernetes.runner import Runner from checkov.runner_filter import RunnerFilter class TestEtcdClientCertAuth(unittest.TestCase): def test_summary(self): runner = Runner() current_dir...
""" Django settings for lectures_project project. Generated by 'django-admin startproject' using Django 1.11.29. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ ...
# -*- coding: utf-8 -*- # Exercícios by Nick Parlante (CodingBat) # J. alarm_clock # day: 0=domingo, 1=segunda, 2=terça, ..., 6=sábado # vacation = True caso você esteja de férias # o retorno é uma string que diz quando o despertador tocará # dias da semana '07:00' # finais de semana '10:00' # a menos que você esteja ...
"""Defines VehiclesManager class ---------------------------------------------------------------------------------------------------------- This file is part of Sim-ATAV project and licensed under MIT license. Copyright (c) 2018 Cumhur Erkan Tuncali, Georgios Fainekos, Danil Prokhorov, Hisahiro Ito, James Kapinski. For...
from django.contrib.auth import get_user_model from django.utils.translation import gettext_lazy as _ from rest_framework import permissions class ReadSelf(permissions.BasePermission): """Permits access to the (user)model instance if the user corresponds to the instance""" message = _("You may only view your...
import unittest import numpy as np from scipy import sparse from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_false from sklearn.utils.testing import assert_true from sklearn.pre...
"""Sub-classes and wrappers for vtk.vtkPointSet.""" import pathlib import logging import os import warnings import numpy as np import vtk from vtk import (VTK_HEXAHEDRON, VTK_PYRAMID, VTK_QUAD, VTK_QUADRATIC_HEXAHEDRON, VTK_QUADRATIC_PYRAMID, VTK_QUADRATIC_QUAD, VTK_QUADRATIC_TETRA, ...
import os import sys __dir__ = os.path.dirname(os.path.abspath(__file__)) sys.path.append(__dir__) sys.path.append(os.path.abspath(os.path.join(__dir__, '../..'))) from PIL import Image import cv2 import numpy as np import math import time import torch from pytorchocr.base_ocr_v20 import BaseOCRV20 import tools.infer....
""" ASGI config for foo project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_...
import clinica.pipelines.engine as cpe class SpatialSVM(cpe.Pipeline): """SpatialSVM - Prepare input data for SVM with spatial and anatomical regularization. Returns: A clinica pipeline object containing the SpatialSVM pipeline. """ def check_pipeline_parameters(self): """Check pipel...
import os import time from visualdl import LogReader import matplotlib.pyplot as plt # reader = None # 开启visualDL_log才能输出可视化图像 [!请修改] file_dir = "../PaddleRec/models/rank/deepfm/visualDL_log/" now_time = time.strftime('%Y-%m-%d',time.localtime(time.time())) os.makedirs(f"./Visualize/img/{now_time}/") # 获取最新文件 def ...
import os import numpy as np from skmultiflow.data.regression_generator import RegressionGenerator def test_regression_generator(test_path): stream = RegressionGenerator(n_samples=100, n_features=20, n_targets=4, n_informative=6, random_state=0) assert stream.n_remaining_samples() == 100 expected_names ...
print('='*50) print('Seja bem vindo ao caixa eletrônico 24 horas!') print('='*50) valor = int(input('Qual o valor que você gostaria de sacar? R$\n')) total = valor céd = 50 totcéd = 0 while True: if total >= céd: total -= céd total += 1 else: if totcéd > 0: print(f'Tota...
''' Wrapper for face detection model ''' import cv2 import mxnet as mx import numpy as np from . import config class FaceDetector: ''' Interface for face detection model. Must implement the predict() method. predict() must accept an image (np.ndarray) as argument. ''' def __init__(self): ...
import urllib.request, json from .models import Quote base_url = 'http://quotes.stormconsultancy.co.uk/random.json' def get_quote(): get_quote_url = base_url.format() with urllib.request.urlopen(get_quote_url) as url: quote_details_data = url.read() quote_details_response = json.loads(quote_d...
''' Original implementation: https://github.com/pytorch/vision/blob/main/references/segmentation/transforms.py https://medium.com/mlearning-ai/understanding-torchvision-functionalities-for-pytorch-part-2-transforms-886b60d5c23a ''' import random import numpy as np import torch from torchvision import transform...
#!/usr/bin/env python3 import socket import binascii from urllib.parse import urlparse class Mssql_Weakpwd_BaseVerify: def __init__(self, url): self.info = { 'name': 'Mssql 弱口令漏洞', 'description': 'Mssql 弱口令漏洞', 'date': '', 'exptype': 'check', 'ty...