content
stringlengths
5
1.05M
# Generated by Django 3.1.3 on 2020-12-05 13:47 import django.core.validators from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Staff', ...
import numpy as np import pandas as pd import torch from PIL import Image as Im from torch.utils.data import Dataset np.random.seed(42) class CustomDataset(Dataset): def __init__(self, subset, transform): self.subset = subset self.transform = transform def __getitem__(self, idx): x, ...
# -*- coding: UTF-8 -*- from rogertalk.core import Session from rogertalk.core import BaseApi from rogertalk.api import Stream def get_session(settings): if type(settings) is dict: client_id = settings.get('ROGERTALK_CLIENT_ID', None) client_secret = settings.get('ROGERTALK_CLIENT_SECRET', None) ...
assert ord("a") == 97 assert ord("é") == 233 assert ord("🤡") == 129313 try: ord() except TypeError: pass else: assert False, "TypeError not raised when ord() is called with no argument" try: ord("") except TypeError: pass else: assert False, "TypeError not raised when ord() is called with an e...
from .base import RuleBase from jupyter_client.kernelspec import KernelSpecManager import IPython from wataru.logging import getLogger import wataru.exceptions as wtex import wataru.utils as utils import wataru.rules.templates as modtpl import os import shutil import re import copy __all__ = [ 'SetupJupyter', ]...
#!/usr/bin/env python3 from orger import Mirror from orger.inorganic import node, link from orger.common import dt_heading from my.media.youtube import watched from itertools import groupby class YoutubeView(Mirror): def get_items(self) -> Mirror.Results: by_url = lambda w: w.url by_when = lamb...
# Created by MechAviv # ID :: [910141060] # Hidden Street : The Frenzy sm.reservedEffect("Effect/Direction8.img/lightningTutorial2/Scene4") sm.sendDelay(10000) sm.setTemporarySkillSet(0) sm.setInGameDirectionMode(False, True, False, False) # Unhandled User Effect [PlaySoundWithMuteBGM] Packet: 23 11 00 4D 69 6E 69 4...
import ast class CloningNodeTransformer(ast.NodeVisitor): """ A :class:`NodeVisitor` subclass that walks the abstract syntax tree and allows modification of nodes. The `NodeTransformer` will walk the AST and use the return value of the visitor methods to replace or remove the old node. If the ret...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import logging import os import urllib3 import xmltodict from OpenSSL import crypto from datetime import datetime from time import mktime, time, gmtime from lib.enums import LoggingDefaults, LoggingLevel def configure_logger(args): """ Get the argument list from...
import time import threading from bucker.api.client import QueueClient from bucker.api.message import Message s = """<qs xmlns="http://purl.oclc.org/DEFUZE/qs" resp="1e582a22b3f82a7c9acc227b0ccb6fdec0d84e6b74dccbcb542e8d11e1b379dd" type="response"><op><push-message /></op><qid>test</qid><mid>3664f5666c2564f7fb6c16d45...
from flask import Flask from flask import url_for from flask.ext.sqlalchemy import SQLAlchemy from sched.models import Base app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sched.db' # Use Flask-SQLAlchemy for its engine and session # configuration. Load the extension, giving it the app object,...
# interface module, re-exporting stuff from cli_impl.py # see programming guide for list of supported symbols from cli_impl import \ terminal_width, terminal_height, \ set_output_radix, get_output_radix, get_output_group, \ number_str, \ iff, \ str_t, int_t, range_t, float_t, flag_t, addr_t, filename_t, obj_t, \ stri...
# Copyright (c) 2019 Microsoft Corporation # Distributed under the MIT software license import pytest from ..postprocessing import multiclass_postprocess from ....test.utils import ( synthetic_multiclass, synthetic_classification, adult_classification, iris_classification, ) from sklearn.model_selec...
from sqlalchemy.dialects.postgresql import ARRAY from sqlalchemy.sql import func from zeus.config import db from zeus.db.mixins import RepositoryBoundMixin from zeus.db.types import GUID from zeus.db.utils import model_repr from zeus.utils import timezone class Revision(RepositoryBoundMixin, db.Model): sha = db....
import sys import os import pysam from pyfaidx import Fasta _t_path = os.path.abspath(os.path.dirname(os.path.abspath(__file__))) _r_path = os.path.join(_t_path, os.pardir, 'indel_repeat_classifier') sys.path.insert(0, _r_path) from repeats_from_variants import repeats_from_variant from repeats_from_variants import cos...
from relative_performer.performer_pytorch import PerformerLM, Performer, FastAttention, SelfAttention from relative_performer.constrained_relative_encoding import RelativePerformer from relative_performer.clipped_relative_attention import ClippedRelativePerformer
# 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 # "License"); you may not u...
from mediawiki import MediaWiki def get_search(search_phrase): wikipedia = MediaWiki(user_agent='chucha-user-agent-string') open_search_result = wikipedia.search(search_phrase) return open_search_result
# HelloZigguratApiView.py # (C)2013 # Scott Ernst from ziggurat.view.api.ApiRouterView import ApiRouterView #___________________________________________________________________________________________________ HelloZigguratApiView class HelloZigguratApiView(ApiRouterView): """A class for...""" #==================...
from setuptools import setup, find_packages import os import sys import re import shutil def get_version(package): """ Return package version as listed in `__version__` in `init.py`. """ init_py = open(os.path.join(package, '__init__.py')).read() return re.search("__version__ = ['\"]([^'\"]+)['\"]...
from dataclasses import dataclass @dataclass class StructuredMessage: header: str payload: str
"""Wrapper for matplotlib. Configures image output for GUI and no GUI systems.""" import os from distutils.spawn import find_executable import matplotlib from matplotlib import rc def pyplot_display(func): """Provides decorator for `matplotlib.pyplot` plots. It only uses `show()` display or PyCharm remote ...
from django.contrib import admin from flow.models import device, flow, connection # Register your models here. admin.site.register(device) admin.site.register(flow) admin.site.register(connection)
from deepdiff import DeepDiff from marshmallow.exceptions import ValidationError import pytest def test_upgrade_1_to_2(): from swag_client.migrations.versions.v2 import upgrade, downgrade a = { "bastion": "testaccount.net", "metadata": { "s3_name": "testaccounts3", "cl...
import discord class EchidnaBot(discord.Client): async def on_ready(self): print(f'logged in as {self.user}') async def on_message(self, message): if message.author == self.user: return print(f'{message.author}: {message.content}') if message.content.startswith('$hello'): await messag...
from .model import social_stgcnn as STGCNN from .utils import TrajectoryDataset from .bridge import get_dataloader, get_latent_dim, get_model from .bridge import model_forward_pre_hook, model_forward, model_forward_post_hook from .bridge import model_loss
# Copyright (c) 2017-2018 luispenagos91@gmail.com # Distribuido bajo la licencia MIT Software Licence # Mas informacion http://www.opensource.org/licenses/mit-license.php # import de datetime nativo de python import datetime # importaciones que realiza django por defecto from django.shortcuts import render, redirect ...
""" Collection of TensorFlow math functions, wrapped to fit Ivy syntax and signature. """ # global import math import tensorflow as _tf sin = _tf.sin cos = _tf.cos tan = _tf.tan asin = _tf.asin acos = _tf.acos atan = _tf.atan atan2 = _tf.atan2 sinh = _tf.math.sinh cosh = _tf.math.cosh tanh = _tf.math.tanh asinh = _tf...
from django.conf import settings from django.core import mail from django.core.mail import EmailMessage from django.core.management.base import BaseCommand from django.template.loader import render_to_string from wagtail.wagtailcore.models import PageRevision, Site from wagtaillinkchecker.scanner import broken_link_sca...
__author__ = 'mustafa_dogan' from model import * plants = [ 'Shasta', 'Keswick', # 'Oroville', # 'Bullards Bar', # 'Englebright', 'Folsom', 'Nimbus', 'New Melones', # 'Don Pedro', # 'New Exchequer', 'Pine Flat' ] # simulation start time: year, month, day, hour, minute start...
"""Patch pyyaml for zipapp and remove native extension.""" from foreman import get_relpath, rule, to_path from templates import common from garage import scripts common.define_git_repo( repo='https://github.com/yaml/pyyaml.git', treeish='b6cbfeec35e019734263a8f4e6a3340e94fe0a4f', ) PATCHES = ( '0001-...
class NehushtanWebsocketConnectionEntity: def __init__(self, websocket): self.__local_key = f'{websocket.local_address[0]}-{websocket.local_address[1]}' self.__remote_key = f'{websocket.remote_address[0]}-{websocket.remote_address[1]}' self.__websocket = websocket def get_local_key(self...
# Author: Vishal Gaur # Created: 06-26-2021 17:45:12 import math # function to find max crossing subarray def findMaxCrossingSubarray(A, low, mid, high): sum = 0 leftSum = -math.inf maxLeft = mid for i in range(mid, low, -1): sum += A[i] if sum > leftSum: leftSum = su...
from tracardi_plugin_sdk.action_runner import ActionRunner from tracardi_plugin_sdk.domain.register import Plugin, Spec, MetaData, Form, FormGroup, FormField, FormComponent from tracardi_plugin_sdk.domain.result import Result from tracardi_string_validator.model.configuration import Configuration from tracardi_string_...
def binary_search(item_list, item): """"perform binary search list = item_list item = value in list """ #initialize index variable item_list.sort() first = 0 last = len(item_list) - 1 found = False # edge case check if all items in list are num if all(isinstance(n,(int,float)) fo...
# encoding: utf-8 from .base import APITestCase from vilya.models.user import User class FollowTest(APITestCase): def setUp(self): super(FollowTest, self).setUp() user_name1 = 'zhangchi' email = '%s@douban.com' % user_name1 self.zhangchi = User(user_name1, email) user_name2...
# -*- coding: utf-8 -*- from datetime import datetime from icalendar.parser_tools import to_unicode from icalendar.prop import vDatetime from icalendar.prop import vText from string import ascii_letters from string import digits import random class UIDGenerator(object): """If you are too lazy to create real uid'...
""" Kernel desnity estimation plots for geochemical data. """ import copy import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator import numpy as np from ...comp.codata import close from ...util.plot.density import ( plot_Z_percentiles, percentile_contour_values_from_meshz, get_axis_densi...
import base64 import getopt import sys from Crypto.Cipher import AES def usage(): print("Usage:") print("python jdCnLDecryptor.py --b64=<base64> [--jdkey=<jdkey>]") print("--b64 : base64 data to decrypt") print("--jdkey : optional jdkey. Using default JDownloader key by default") print("Showing ex...
#!/usr/bin/env python # 8 bar Audio equaliser using MCP2307 import wave from time import sleep, time from struct import unpack import numpy as np # Set up audio chunk = 2583 # Use a multiple of 8 chunk -= chunk % 7 data_in = wave.open('../music/disconnected_02.wav', 'rb') sample_rate = data_in.getframerate() no_chan...
# -*- coding: utf-8 -*- """ qiita.items ~~~~~~~~~~~ Wrapper for Qiita items. :copyright: (c) 2012 Shinya Ohyanagi, All rights reserved. :license: BSD, see LICENSE for more details. """ from .client import Client class Items(Client): def post_item(self, params): """Post new item. ...
import unittest from rx.internal.utils import adapt_call class C(object): def __init__(self, arg): self._arg = arg def __call__(self, x): return x + self._arg def method1(self, x): return x + self._arg def method2(self, x, y): return x + self._arg de...
"""Constants for the Dakuo Mosquito Dispeller integration.""" DEFAULT_NAME = "Dakuo Mosquito Dispeller" DOMAIN = "dakuo_mosquito_dispeller" DOMAINS = ["sensor", "fan"] MOSQUITO_DISPELLER_DATA = "mosquito_dispeller_data" ATTR_MODEL = "model" ATTR_PRESET_MODE = "preset mode" ATTR_FW_VER = "Firmware version" ATTR_HW_V...
import os import requests from flask import Flask from jaeger_client import Config from flask_opentracing import FlaskTracing app = Flask(__name__) config = Config( config={ 'sampler': {'type': 'const', 'param': 1}, 'logging': True, 'reporter_batch_size': 1}, service_na...
""" Settings and configuration for Aasaanjobs Elasticsearch Values will be read from the module specified by the AJELASTIC_SETTINGS_MODULE environment variable or DJANGO_SETTINGS_MODULE if a Django project (in that order). """ import importlib import os import sys from contextlib import contextmanager import lazy_obj...
import pytest @pytest.mark.skip def test_example(): print("mark skip!!!") assert 1 == 1 @pytest.mark.xfail def test_example1(): print("mark xfail!!!") assert 1 == 1 # pytest -s -v -m "slow" @pytest.mark.slow def test_example2(): print("mark slow!!!") assert 1 == 1 def test_example3(): ...
import shutil import tempfile from django.conf import settings from django.test import override_settings, TestCase from attendee.tests import attendee_testutils from speaker.models import Speaker def create_test_speaker( email='speaker@example.org', name='Test Speaker', **kwargs): user, password = atten...
import django_filters from .models import Project class ProjectFilter(django_filters.rest_framework.FilterSet): """ 项目管理 简单序过滤器 """ # 通过 lookup_expr 可进行模糊查询,其他配置可自行百度 name = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Project exclude = ('description...
#!/usr/bin/python3 def isPrime(i): if i == 1: print("1 is special") return False for x in range (2, i): if i % x == 0: print ("{} equals {} x {}".format(i, x, i // x)) return False else: print(i, "is a prime number") return True for i...
# -*- coding: utf-8 -*- # # Copyright (c) 2020, the cclib development team # # This file is part of cclib (http://cclib.github.io) and is distributed under # the terms of the BSD 3-Clause License. import unittest import numpy from cclib.bridge import cclib2pyquante from ..test_data import getdatafile from cclib.pars...
# ################################### # Utils Exceptions #TODO: make exception hierarchy class MissingSettings(Exception): pass class MissingMysqlLogs(MissingSettings): pass class MissingCommand(Exception): pass class FileNotFound(Exception): pass class RejectedConnection(Exception): def __i...
#!/usr/bin/env python ''' Allows transparent stdin usage via pipe into the program when optparser is used. Input parameters are e.g. "-i -" in which "-" defines the usage of stdin. E.g: parser = optparse.OptionParser('usage: python %prog') parser.add_option('-i', '--ifile', dest='ifile', help='Name of the file', defau...
# encoding: utf-8 import os import sys import site import subprocess __author__ = u'Oli Davis' __copyright__ = u'Copyright (C) 2016 Oli Davis' def open_folder(path): try: if sys.platform == 'darwin': subprocess.check_call(['open', '--', path]) elif sys.platform == 'linux2': ...
""" BluePrint for all of the Admin Routs and Functioality Multiple checks to verify that only Admins can access these pages All logic Written by Alex Kohanim, if anythin needs clarifing, please contact """ from flask import Blueprint, render_template, session, request, abort, redirect import gatorProduct as produc...
import copy import hashlib import io import json import os import tempfile import threading from datetime import datetime, timedelta from typing import Optional from blockchyp import crypto from blockchyp.util import from_iso_timestamp class TerminalRouteCache: """The terminal route cache speeds up transactions ...
# ------------------------------------------------------------------------------ # # Helper functionality to interact with the file system # # Author: Stefan Heule <stefanheule@gmail.com> # # ------------------------------------------------------------------------------ def write(f, s): """ print a string to a fil...
""" Question: Best Time to Buy and Sell Stock with Transaction Fee Difficulty: Medium Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/ Ref: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/ You are given an array prices where ...
"""Module for lemmatizing Middle High German """ __author__ = ['Clément Besnier <clemsciences@aol.com>', ] __license__ = 'MIT License. See LICENSE.' import os from typing import List from cltk.lemmatize.backoff import IdentityLemmatizer, DictLemmatizer from cltk.utils.file_operations import open_pickle class Back...
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from common.dependency import Dependency from crash import parse_util from crash.type_enums import CallStackFormatType, CallStackLanguageType from testing_u...
from configparser import ConfigParser class Config(object): instance = None @staticmethod def get_instance(): if Config.instance is None: Config.instance = ConfigParser() return Config.instance else: return Config.instance
# -*- coding: UTF-8 -*- # vim: set expandtab sw=4 ts=4 sts=4: # # phpMyAdmin web site # # Copyright (C) 2008 - 2016 Michal Cihar <michal@cihar.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundati...
from flask import current_app, render_template, request from wlanpi_webui.speedtest import bp @bp.route("/") @bp.route("/speedtest") def speedtest(): spt_port = "8080" base = request.host.split(":")[0] iframe = f"http://{base}:{spt_port}/speedtest.html" return render_template( "/public/speedt...
# encoding: utf-8 """ @author: xyliao @contact: xyliao1993@qq.com """ import os import numpy as np import torch from PIL import Image from mxtorch import transforms as tfs def read_images(root, train): txt_fname = os.path.join(root, 'ImageSets/Segmentation/') + ('train.txt' if train else 'val.txt') with open...
from collections import deque import numpy as np from dvmvs.utils import is_pose_available, pose_distance class KeyframeBuffer: def __init__(self, buffer_size, keyframe_pose_distance, optimal_t_score, optimal_R_score, store_return_indices): self.buffer = deque([], maxlen=buffer_size) self.keyfra...
#! /usr/bin/env python # -*- coding: utf-8 -*- # # graph_tool -- a general graph manipulation python module # # Copyright (C) 2006-2015 Tiago de Paula Peixoto <tiago@skewed.de> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by...
""" sentry.plugins.base.manager ~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import, print_function __all__ = ('PluginManager', ) import sys import os import six import logging ...
#! /usr/bin/env python3 from functools import reduce def operations(func): """ Laboration 1a omgjord till lambda funktioner. """ print(reduce(func,range(1,513))) #lambda for adding two numbers together plus = lambda x1, x2: x1 + x2 #lambda for multiplying two numbers multiply = lambda x1, x2: x1 ...
from bs4 import BeautifulSoup from selenium import webdriver import pandas as pd from utils import * def find_next_button(browser, table_id): next_button = browser.find_element_by_id(table_id + "_next") return next_button def is_next_page_available(browser, table_id): next_button = find_next_button(b...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/ads/googleads_v5/proto/resources/ad_group_simulation.proto from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from...
''' Multi Layer Perceptron Programmed partially or completely by Gautam Sharma and partial code taken from official sklearn documentation We start by importing appropriate libraries Wherever 1,2,3,4,5 is written it means it represents number of features ''' import pandas as pd import numpy as np import sklearn f...
#/usr/bin/python import sys,os import HAConf initial_sequence=sys.argv[1] scan_residues=sys.argv[2] starting_point = os.getcwd() for i in range(len(initial_sequence)): if i+len(scan_residues) > len(initial_sequence): continue mutant = initial_sequence[:i] + scan_residues + initial_sequence[(i+len(scan_residues)):]...
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import cStringIO import logging import os import sys import textwrap import unittest ROOT_DIR = os.path.dirname(os.path.dirname(os...
import Model.DataClass as DataClass import toml import os import typing def parseHeaderConfig(toml_contents : str) -> DataClass.HeaderConfig: toml_data = toml.loads(toml_contents) header_config = DataClass.HeaderConfig(toml_data["path"], toml_data["header"], toml_data["footer"]) return header_config def p...
import pytest from enum import Enum from functools import partial from datetime import datetime, date, timezone from dhampyr.failures import ValidationFailure, CompositeValidationFailure from dhampyr.context import ValidationContext from dhampyr.api import v, converter, verifier, analyze_specifier class Test...
import cv2 import time import pygame import numpy as np import mediapipe as mp from PIL import Image import matplotlib.pyplot as plt # Initialize the mediapipe hands class. mp_hands = mp.solutions.hands # Set up the Hands functions for images and videos. #hands = mp_hands.Hands(static_image_mode=True, max...
import subprocess import sys if len(sys.argv) < 2: print("No file provided") exit() fileName = sys.argv[1] flashAddress = "0x08000000" testString = ( "device STM32F769NI\n" "JTAGConf -1 -1\n" "speed 4000\n" "r\n" "loadbin " + fileName + " " + flashAddress + "\n" "r\n" "g\n" "q...
from travertino.size import at_least from toga_winforms.libs import WinForms, SystemColors from .base import Widget class MultilineTextInput(Widget): def create(self): # because https://stackoverflow.com/a/612234 self.native = WinForms.RichTextBox() self.native.Multiline = True s...
import uuid from spantools import convert_params_headers class TestConvertHeadersParams: def test_basic(self): id_value = uuid.uuid4() incoming = {"int": 10, "id": id_value, "string": "value"} convert_params_headers(incoming) assert incoming["int"] == "10" assert incomi...
from cam_util.cam_ctrl_util import PMDCam from pmd_dust_test.distribution import normal_distribution as nd from dependencies.display_util.string_display_util import print_notification, print_warning from dependencies.archive_util.data_recording import TabDelimText import matplotlib.pyplot as plt import matplotlib impo...
import torch.nn.functional as F import torch def _max(x, target): pass def f1(x, labels): x = F.softmax(x, dim=1) return 1.0-F.cross_entropy(x, labels) def f2(x, labels): pass def f4(x, labels): x = F.softmax(x, dim=1) return torch.clamp(0.5 - F.cross_entropy(x, labels), min=0.0) def f5(...
import argparse import csv import glob import numpy as np import matplotlib.pyplot as plt from matplotlib.pyplot import figure figure(num=None, figsize=(12, 8), dpi=80, facecolor='w', edgecolor='k') def main(): # print("/home/efe/git/trpo/"+args.log_dir+"*.csv") for log_dir in ["log/td/value_iter/_100","log...
from zero import ZeroServer, ZeroClient, AsyncZeroClient client = ZeroClient("localhost", 7777) async_client = AsyncZeroClient("localhost", 7777) def echo(msg: str) -> str: return client.call("echo", msg) def hello() -> str: return client.call("hello", None) async def async_echo(msg: str) -> str: re...
# -*- coding: utf-8 -*- u"""Public functions from sirepo Use this to call sirepo from other packages or Python notebooks. :copyright: Copyright (c) 2020 RadiaSoft LLC. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function f...
# -*- coding: utf-8 -*- from __future__ import absolute_import from dp_tornado.engine.helper import Helper as dpHelper import datetime as abs_datetime class DateHelper(dpHelper): def now(self, timezone=None): return self.from_datetime(datetime=self.helper.datetime.now(timezone=timezone)) def from_...
import sys import time import numpy as np import scipy as sp from scipy.sparse import csr_matrix import pandas as pd import math import warnings from sklearn.pipeline import make_pipeline from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline, FeatureUnion from sklearn.base import BaseEstim...
"""Unittest""" import unittest import player class testPlayerClass(unittest.TestCase): """Testing the Player class""" def test_init_default_object(self): #Making an abject of player class with the name Mike player_object = player.Player("Mike") #Testing with the appropr...
import os from keras.datasets import cifar10 from model import * from uilt import * from loss import * from keras.optimizers import Adam import albumentations as albu from albumentations import (HorizontalFlip, VerticalFlip, ShiftScaleRotate, CLAHE , GridDistortion,GaussNoise) #list of images train_x=read('tra...
import os import shutil import subprocess import re import pprint import pandas as pd import numpy as np import cv2 from functools import reduce class Consolodator: input_directory = None output_directory = None extensions = None def __init__(self, input_directory, output_direct...
""" 词法分析 """ import re import os class Error: """ 错误 """ def __init__(self, error_info): """ 构造 :param error_info: 错误信息 """ self.info = error_info class LexicalError(Error): """ 词法错误 """ def __init__(self, error_info, error_line,error_value=None):...
import datetime from maroma.lab.stockdatastore import StockDataStore from examples.eventstudy.exampleeventmatrix import ExampleEventMatrix from maroma.lab.calculator import Calculator from maroma.lab.plotter import Plotter def main(): # Define the symbols to study #symbols = ['S1', 'S2', 'S3'] symbols = ...
import os import unittest from pymosa_mimosa26_interpreter import data_interpreter from pymosa_mimosa26_interpreter.testing.tools.test_tools import compare_h5_files class TestRawChunkSize(unittest.TestCase): @classmethod def setUpClass(cls): cls.temp_output_files = [] @classmethod def tearD...
from app import app from flask import render_template, request, redirect, url_for, session import requests import json import statistics from device_detector import SoftwareDetector @app.route("/", methods=['GET', 'POST']) @app.route("/index/", methods=['GET', 'POST']) def index(): if request.method == 'POST': ...
import random from django.contrib.gis.db import models from django.core.serializers.json import DjangoJSONEncoder from django.forms.widgets import HiddenInput from django.utils.text import slugify from django.utils.translation import ugettext_lazy as _ from ordered_model.models import OrderedModel from .formfields im...
"""yamllint test runner.""" # filename contains underscore to prevent namespace collision import glob import logging import os import sys import tempfile from typing import Dict, Any, List # pylint: disable=unused-import from runway.tests.handlers.base import TestHandler from runway.tests.handlers.script import Scrip...
# BSD 3-Clause License # # Copyright (C) 2021 THL A29 Limited, a Tencent company. 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 copyrig...
#!/usr/bin/env python from azuremodules import * def RunTest(): UpdateState("TestRunning") cdsoutput = Run("cat /etc/yum.repos.d/rhui-load-balancers") RunLog.info("All CDS server name:" + cdsoutput) if(YumPackageInstall("nmap")): outputlist = re.split("\n", cdsoutput) RunLog.info("First CD...
'''Exercício Python 045: Crie um programa que faça o computador jogar Jokenpô com você.''' from time import sleep import random print('=+=+=+=+=+=+=+=+='*3) print('''Sua opcões: [0] PEDRA [1] PAPEL [2] TESOURA''') jogada = int(input('Qual é a sua jogada: ')) if jogada == 0: jogador = str('PEDRA') elif jogada == 1:...
"""Test echo RPC command functionality.""" # Standard imports import argparse import asyncio import logging # Local package imports from lhrhost.messaging import ( MessagingStack, add_argparser_transport_selector, parse_argparser_transport_selector ) from lhrhost.messaging.presentation import MessagePrinter fr...
class UMGrid: """ Interpolate the ocean mask onto the UM grid. Creates the land fraction and mask, later used as an input to the UM. """ def __init__(self, um_restart, num_lon_points, num_lat_points, mom_grid, output_dir): self.SOUTHERN_EXTENT = -89.995002746582031 ...
from components import StudentLoader import rpyc conn=rpyc.classic.connect("localhost") comps=conn.modules.components comps.load_default_config() class StudentLoader(object): def __init__(self, obj): self.loader=comps.StudentLoader(obj) def load(self): print ("REMOTE LOAD") return self...