content
stringlengths
5
1.05M
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Exception classes are located here ''' class InvalidResponseFormat(Exception): """Error when the response which was gotten from api server couldn't be deserialize""" def __init__(self, path, method, body): self.path = path self.method = method...
for i in range(1, 10): for j in range(1, 10): print(i * j, end=' ') print(end='\n')
""" LIST: REMOVE NULLS (SINGLE LIST) """ __author__ = 'Sol Amour - amoursol@gmail.com' __twitter__ = '@solamour' __version__ = '1.0.0' data = ["a", None, 17.1, 3, "C", "X", None, 4] # A mixed list of data types inclusive # of nulls (None's) results = [] # An empty container list to which we will append (...
"""generate openapi docs.""" from honeybee_schema._openapi import get_openapi from honeybee_schema.model import Model from honeybee_schema.energy.simulation import SimulationParameter import json # generate Model open api schema print('Generating Model documentation...') openapi = get_openapi( [Model], title=...
#Primero, pedimos los tres lados del triangulo lado_a = float(raw_input("Ingrese a: ")) lado_b = float(raw_input("Ingrese b: ")) lado_c = float(raw_input("Ingrese c: ")) #Luego, comprobamos la desigualdad triangular y, si aplica, el tipo de triangulo if (abs(lado_a - lado_c) < lado_b) and (lado_b < abs(lado_a + lado_c...
#!/usr/bin/env python # Add "common-apps" folder to sys.path if it exists import os, sys common_dir = os.path.join(os.path.dirname(__file__), 'common-apps') if os.path.exists(common_dir): sys.path.append(common_dir) # Initialize App Engine SDK if djangoappengine backend is installed try: from djangoappengine....
from nn_wtf.data_set_base import DataSetBase import tensorflow as tf __author__ = 'Lene Preuss <lene.preuss@gmail.com>' class NeuralNetworkGraphBase: def __init__(self, input_size, layer_sizes, output_size): """Initialize a neural network given its geometry. :param input_size: number of input ...
# -*- coding: utf-8 -*- """ author: zengbin93 email: zeng_bin8888@163.com create_dt: 2022/2/16 20:31 describe: czsc.utils 单元测试 """ from czsc import utils def test_x_round(): assert utils.x_round(100, 3) == 100 assert utils.x_round(1.000342, 3) == 1.0 assert utils.x_round(1.000342, 4) == 1.0003 assert ...
import sys import pandas as pd _, *input_files, output_file = sys.argv df_list = [] for input_file in input_files: df_list.append(pd.read_csv(input_file)) #df_list = [pd.read_hdf(f) for f in input_files] pd.concat(df_list).to_csv(output_file, index=False)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Ce module implémente une version simple du Jeu Tetris """ __version__ = "0.0.6" from tetris_game.core import Square, Line, Shape, Menu, TetrisFrame, TetrisGame from tetris_game.constantes import *
#! python3 # -*- coding: utf-8 -*- import inspect import wx from wx import aui from wx import stc import wx.lib.eventwatcher as ew from mwx.framework import FSM if wx.VERSION < (4,1,0): from wx.lib.mixins.listctrl import CheckListCtrlMixin class _ListCtrl(wx.ListCtrl, CheckListCtrlMixin): def __in...
import please2.reg_cmd as reg_cmd from ..cmd_base import Command, Match from .cmd_git_util import make_error_result, get_ws_modifs_tree, git_diff_layer_name from please2.util.args import get_positional_after class CommandGitLsDiffsWsCache(Command): def help(self): return self.key() + ' [@ <dir>]' def...
from django.contrib import admin from django.utils import timezone from django.utils.html import format_html from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from .models import ProblemReport from .utils import inform_user_problem_resolved class ProblemReportAdmin(admin.ModelAd...
from time import time import glm from itbl import Ray, Shader from itbl.accelerators import SDF, BVHAccel from itbl.cameras import TrackballCamera from itbl.shapes import Box from itbl.util import get_color, get_data from itbl.viewer import Application, Viewer from itbl.viewer.backend import * import itbl._itbl as _...
from .functions_for_in_time_compile import *
# Copyright 2020 The Backstage 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 to in...
# SPDX-FileCopyrightText: Copyright (c) 2022 Daniel Griswold # # SPDX-License-Identifier: MIT """ `sdp31` ================================================================================ CircuitPython helper library for the SDP31 differential pressure sensor * Author(s): Daniel Griswold Implementation Notes -------...
# Generated by Django 3.1.1 on 2020-09-10 17:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("autotasks", "0004_automatedtask_sync_status"), ] operations = [ migrations.AlterField( model_name="automatedtask", n...
""" Webcam library. Generally, don't access this library directly. Instead, use the video.py library. """ import cv2 import threading import time from video.abstract_cam import AbstractCam class Webcam(AbstractCam): def __init__(self, cam_id=0): self.cam_id = cam_id self.running = False se...
import mxnet as mx data_shape = (1,3,5,5) class SimpleData(object): def __init__(self, data): self.data = data data = mx.sym.Variable('data') conv = mx.sym.Convolution(data=data, kernel=(3,3), pad=(1,1), stride=(1,1), num_filter=1) mon = mx.mon.Monitor(1) mod = mx.mod.Module(conv) mod.bind(data_shapes=...
# # Part I: data collection # 1. create a database # 2. create a table # 3. insert data # # %% libraries import aux import datetime # ACTION: show the content of aux # %% create a database with a table db_filename = 'tutorial.db' aux.create_table_geometric_shapes(db_filename) # ACTION: show that the table is c...
"""A setuptools-based script for installing FauxFactory.""" # setuptools is preferred over distutils. import codecs import os from setuptools import find_packages, setup def read(*paths): """Build a file path from *paths* and return the contents.""" filename = os.path.join(*paths) with codecs.open(filena...
# gamepage.py # Author: Richard Gibson # # Renders individual game pages at /game/<game_code>, where game_code is the # game converted through util.get_code(). For each category of the game run, # a table lists the PBs for each runner, sorted by time. The tables # themselves are sorted by number of PBs. These tab...
# coding: utf-8 # /*########################################################################## # # Copyright (c) 2004-2020 European Synchrotron Radiation Facility # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to d...
# coding=utf8 import os import re import numpy as np from typing import List from overrides import overrides from nltk.corpus import stopwords from allennlp.data.tokenizers import Token from .atis.atis_entity_matcher import ATISEntityMatcher from .atis.atis_sql_entity_matcher import ATISSQLEntityMatcher from .atis.ati...
from artssat.sensor import PassiveSensor import numpy as np class ICI(PassiveSensor): """ The Ice Cloud Imager (ICI) sensor. Attributes: channels(:code:`list`): List of channels that are available from ICI nedt(:code:`list`): Noise equivalent temperature differences for the ...
from test.integration.base import DBTIntegrationTest, use_profile import hashlib import os from unittest.mock import call, ANY, patch import dbt.exceptions import dbt.version import dbt.tracking import dbt.utils class TestEventTracking(DBTIntegrationTest): maxDiff = None @property def profile_config(se...
#!/usr/bin/python # $LicenseInfo:firstyear=2014&license=mit$ # Copyright (c) 2014, Linden Research, Inc. # # 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 with...
from django.db.models import Q from django.template import Library, Node, TemplateSyntaxError, resolve_variable from farms.models import Farm, CropSeason from operator import itemgetter, attrgetter, methodcaller from sys import stdout, stderr register = Library() class ContextNode(Node): def __init__(self, func): ...
from typing import Optional from plenum.common.constants import DOMAIN_LEDGER_ID, CURRENT_PROTOCOL_VERSION from plenum.common.txn_util import reqToTxn from plenum.test.helper import sdk_random_request_objects def test_post_genesis_txn_from_catchup_added_to_ledger(looper, txnPoolNodeSet): node = txnPoolNodeSet[0]...
import s3fs class S3Client(s3fs.S3FileSystem): """ Класс-обёртка для доступа к хранилищу S3. Используется для доступа к объектам хранилища с использованием интерфейса файловой системы. """ def __init__(self, *, aws_access_key_id, aws_secret_access_key, namespace=None, endpoint_url=None, **kwa...
# Time: O(n^2) # Space: O(n) # # Given a 2D binary matrix filled with 0's and 1's, # find the largest rectangle containing all ones and return its area. # class Solution: # @param matrix, a list of lists of 1 length string # @return an integer def maximalRectangle(self, matrix): if not matrix: ...
import logging from protean.container import Element, OptionsMixin from protean.utils import DomainObjects, derive_element_class logger = logging.getLogger(__name__) class BaseApplicationService(Element, OptionsMixin): """Base ApplicationService class that all other Application services should inherit from. ...
# Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT from logging import getLogger from typing import List from hardly.handlers import DistGitMRHandler from hardly.handlers.distgit import PipelineHandler from packit_service.worker.events import ( Event, MergeRequestGitlabEvent, Pi...
import turtle t = turtle.Turtle() #Screen Configuration screen = turtle.Screen() screen.setup(width = 1.0, height = 1.0) #Turtle configuration t.pensize(10) t.pencolor("white") t.shapesize(3,3,3) t.fillcolor("blue") t.shape("turtle") #blue circle t.penup() t.pencolor("blue") t.goto(0, 0) t.pendown() t.circle(100) ...
from Wikipediapagescrapper.pagescrapper import scrapWikipediaPage
# -*- coding: utf-8 -*- """ Created on Fri Apr 23 00:23:23 2021 @author: Aditya Sarkar """ import pandas as pd import matplotlib.pyplot as plt import numpy as np df = pd.read_csv("Kuala_Lumpur_cluster.csv") names = df['Hotels'].values x = np.arange(len(names)) w = 0.3 plt.bar(x-w, df['score'].values, width=w, label=...
from .user import User, UserModel, UserSignUpModel
from Data.Scores import Scores from Models.TradingViewList import TradingViewList from Models.FileWriter import FileWriter scores_dao = Scores() result = scores_dao.get_best_oscillators() writer = FileWriter( file_dir = './tradingView_list.txt' ) tv_list = TradingViewList(result, writer) tv_list.create() print(re...
# generate the data depending on the problem structure import pandas as pd import os def read_data(datafolder): curPath = os.path.join(os.path.abspath(os.path.curdir), 'data', datafolder) # suppliers supplier_location = pd.read_csv(os.path.join(curPath, 'suppliers_location.csv'), index_col=0) supplie...
import requests import json # REFERENCE: https://developers.meethue.com/develop/get-started-2/ class HueController(object): def __init__(self): self.user = '7wl8U1CnKZlk6kE8WHPzCQatw5VqWb0oiqjZFinR' self.api_base = f'http://192.168.1.4/api/{self.user}' self.group_map = {} self.lig...
from abc import ABC, abstractmethod from dataclasses import field, dataclass from typing import List import numpy as np from dataclasses_json import dataclass_json from paiargparse import pai_dataclass from tfaip.util.enum import StrEnum from calamari_ocr.ocr.predict.params import ( Prediction, PredictionPosi...
import numpy as np from sympy import mpmath as mp from matplotlib import pyplot as plt def singular_surface_plot(f, mn=-1., mx=1., res=500, threshold=2., lip=.1): """ Plots the absolute value of a function as a surface plot """ pass def partial_fractions(p, q): """ Finds the partial fraction representatio...
from argparse import ArgumentParser import os from inference import exec_inference def main(): parser = ArgumentParser() parser.add_argument("-m", "--model-name",dest="model_name", default="resnet18",type=str) parser.add_argument("-bs", "--batch-size",dest="batch_size", default=128,type=int) parser.add...
from textwrap import dedent from tests import check_as_expected ROOT = 'superhelp.helpers.dict_help.' def test_misc(): test_conf = [ ( dedent("""\ pet = 'cat' """), { ROOT + 'dict_overview': 0, ROOT + 'mixed_key_types': 0, ...
import requests import itertools import os import names import random import string url = 'http://localhost:5000/' session = requests.session() # os.system('rm ./db.sqlite') colleges = ["Christ Church", "Exeter", "Magdalen", "St John's", "Jesus", "Wadham", "Univ", "Trinity", "Balliol"] departments = ["American Instit...
import numpy as np import scipy.optimize from util import logistic, log_likelihood, avg_log_likelihood, log_determinant, transform_to_rbf # class RBFWrapper(object): # def __init__(self, base_model, rbf_width, radial_basis=None): # self.model = base_model # self.rbf_width = rbf_width # sel...
from common import loghandler class logger(): ''' a logger class handles a log system which write logitems to stdout and/or a file stdout (bool): whether to write log to stdout writer (StreamWriter): file writer (None for no file output) showdate (bool): if you dont want to output ...
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from license_manager_simulator.config import settings engine = create_engine(settings.DATABASE_URL) session = sessionmaker(autocommit=False, autoflush=False, bind=engine, future=True) ...
#!/usr/bin/env python # coding=utf-8 from __future__ import print_function, unicode_literals import json import os import os.path import re import unicodedata # Unique identifier for the workflow WORKFLOW_UID = 'com.calebevans.youversionsuggest' # Path to the user's home directory HOME_DIR_PATH = os.path.expanduser...
import os import hashlib from scrapy.pipelines.files import FilesPipeline from scrapy.utils.python import to_bytes from six.moves.urllib.parse import urlparse """Pipeline to handle URL containing query parameters. This pipeline is a temporary parser to remove existing query parameters in a URL string. Example: - The ...
from blaze.mahimahi.server.filestore import check_cacheability from blaze.mahimahi.server.filestore import CACHE_CONTROL_HEADER, EXPIRES_HEADER, PRAGMA_HEADER, LAST_MODIFIED_HEADER class TestCheckCacheability: def test_no_headers(self): assert not check_cacheability({}) def test_not_cacheable(self): ...
from datetime import datetime from piccolo.apps.user.tables import BaseUser from piccolo.columns import Boolean, ForeignKey, Timestamp, Varchar from piccolo.table import Table class Task(Table): """ An example table. """ name = Varchar() completed = Boolean(default=False) created_at = Timest...
# -*- coding: utf-8 -*- from __future__ import division, print_function __all__ = ["Catalog"] import os import requests import pandas as pd try: from StringIO import StringIO except ImportError: from io import BytesIO as StringIO class Catalog(object): url = ("http://exoplanetarchive.ipac.caltech.edu/...
from loguru import logger from .Models import DataBase from .Models.User import User import settings #from Models.Admin import Admin #from Models.Moderator import Moderator class UserManager(): @logger.catch def __init__(self): DataBase.Init(settings.DB_CONN_STR) self._session = None def RequirePe...
def get_all_py_path(root): results = [] for dirpath, dirnames, filenames in os.walk(root): dirpath = dirpath+'\\' for filename in filenames: if filename[0]!='.': filename = dirpath+filename if filename[len(filename)-3:len(filename)]=='.py' and filename...
__title__ = 'FuelSDKWrapper' __version__ = '1.3.4' __author__ = 'Seb Angel' __license__ = 'MIT'
import os import sys DIRNAME = os.path.dirname(__file__) sys.path.insert(0, os.path.dirname(os.path.dirname(DIRNAME))) from fabdeploy import monkey; monkey.patch_all() from fabric.api import * from fabdeploy.api import *; setup_fabdeploy() @task def execute(): print env.conf.db.execute
def init_actions_(service, args): """ this needs to returns an array of actions representing the depencies between actions. Looks at ACTION_DEPS in this module for an example of what is expected """ # some default logic for simple actions return { 'test': ['install'] } def t...
# -*- coding: utf-8 -*- """Includes class to calculate the network-based features.""" import logging import multiprocessing as mp import numpy as np import pandas as pd from ppi_network_annotation.model.network import Network from ppi_network_annotation.model.neighborhood_network import NeighborhoodNetwork from igra...
# -*- coding: utf-8 -*- """ LaTeX Lexer ~~~~~~~~~~~ This module contains all classes for lexing LaTeX code, as well as general purpose base classes for incremental LaTeX decoders and encoders, which could be useful in case you are writing your own custom LaTeX codec. .. autoclass:: Token(n...
import paho.mqtt.client as mqtt #pip3 install paho-mqtt import argparse import os import sys import math import time import ntplib #pip3 install ntplib from queue import Queue DEST_FILE_PATH = 'ReceivedFiles/' REPORT_FILE_PATH = 'Report/' class Client: def __init__(self, bkr_addr, bkr_port, file, topic, qos, cou...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @Author : yanyongyu @Date : 2020-05-19 22:29:14 @LastEditors : yanyongyu @LastEditTime : 2020-05-26 14:28:58 @Description : None @GitHub : https://github.com/yanyongyu """ __author__ = "yanyongyu" import random from typing import List...
from transaction import * from user import * from extract_pk import extract_pk ts=load_transactions() us=load_users() keys={zw.nam:extract_pk(zw.key) for zw in us} print(keys) for t in ts: print(t) print(t.to_dict()) key=keys[t.fro] print(key)
import json import logging from modules.settings import settings from modules.rabbitmq import channel def log(level, msg, *args, **kwargs): channel.basic_publish( exchange='', routing_key=settings['log-event-queue'], body=json.dumps({ 'level': level, 'msg': msg, ...
import urllib3 from django import forms from service_catalog.models import Instance from service_catalog.models.instance import InstanceState from Squest.utils.squest_model_form import SquestModelForm urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) class InstanceForm(SquestModelForm): state = ...
import pygame from pygame.locals import * from OpenGL.GL import * pygame.init() screen_width = 500 screen_heigth = 500 screen = pygame.display.set_mode((screen_width, screen_heigth), DOUBLEBUF | OPENGL) pygame.display.set_caption("OpenGL in Python") done = False white = pygame.Color(255, 255, 255) whi...
## IMPORTS ## from base.equipment.dice import Dice from base.equipment.card import Card from base.equipment.board import Board from random import shuffle ## CLASS ## class Equipments(): """ Define an Equipments class """ def __init__(self, cards=[[]], dices=[], board=None): """ Default constructor tha...
from django.core.serializers.json import Serializer class LeaderboardApiSerializer(Serializer): def get_dump_object(self, obj): data = super().get_dump_object(obj) del data['model'] del data['pk'] del data['fields'] data['twitter_id'] = obj.twitter_id data['twitter...
import asyncio import pyfirmata from pyfirmata import util from grow.models import Lampada, Relay board = pyfirmata.Arduino('/dev/cu.usbmodem14301') it = pyfirmata.util.Iterator(board) it.start() sensor_lm35 = board.get_pin('a:0:i') async def smart_irrigation(pin: int, tempo: int): board.digital[pin].write(0...
from rest_framework import serializers from .models import Client from .models import Transaction class ClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = '__all__' class TransactionSerializer(serializers.ModelSerializer): class Meta: model = Transact...
# From: http://espn.go.com/nfl/schedule import logging import sys import datetime import urllib.request from django.core.management.base import BaseCommand from django.core.exceptions import ObjectDoesNotExist from django.db.models.deletion import ProtectedError from bs4 import BeautifulSoup from footballseason.model...
""" A simple Multi-User Dungeon (MUD) game. Players can talk to each other, examine their surroundings and move between rooms. Some ideas for things to try adding: * More rooms to explore * An 'emote' command e.g. 'emote laughs out loud' -> 'Mark laughs out loud' * A 'whisper' command for talking to indivi...
""" MIT License This example is based on https://github.com/eriklindernoren/Keras-GAN Copyright (c) 2017 Erik Linder-Norén Copyright (c) 2019 Ivan Vasilev 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 S...
# -*- coding: utf-8 -*- # Generated by Django 1.11.18 on 2019-03-28 14:11 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('countries', '0002_europecountry'), ('confreg', '00...
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- import sys import time import telepot class TelegramBot(telepot.Bot): _answerer = None _bot_data = None def __init__(self, *args, **kwargs): super(TelegramBot, self).__init__(*args, **kwargs) self._answerer = telepot.helper.Answerer(self) ...
from functools import wraps from models.users import UserModal import datetime import jwt # from api.bucket import app from api.bucket import * def get_token(): """ This methods gets the token from the headers""" try: token = request.headers.get('Authorization') return token except Except...
from robosuite.models.grippers import GripperTester, PR2Gripper def test_pr2(): pr2_tester(False) def pr2_tester(render, total_iters=1, test_y=True): gripper = PR2Gripper() tester = GripperTester( gripper=gripper, pos="0 0 0.3", quat="0 0 1 0", ...
#!/usr/bin/env python3 import time import argparse import numpy as np from collections import deque import gym import gym_minigrid # from scores.score_logger import ScoreLogger import random from gym_minigrid.wrappers import * from gym_minigrid.window import Window def redraw(img): if not args.agent_view: ...
"""Saves constants used for event handling""" class Enum(tuple): """Helper class to define an enum in python.""" __getattr__ = tuple.index EVENTTYPES = Enum( ['NOEVENT', 'KEYUP', 'KEYDOWN', 'KEYLEFT', 'KEYRIGHT', 'KEYENTER', 'KEYBACK', 'KEYPRESS', 'KEYMENU1', 'KEYMENU2', 'KEYMENU3', 'NFCSCANNED', ...
#!/opt/local/bin/python3.7 # ------------------------------------------------------------------------------------------------ # # fig-co2fixation.py # Calculates area and thickness of thin film in hydrogen-transport by diffusion scenario # # Farshid Salimijazi and Buz Barstow # Last updated by Buz Barstow on 2019-10-...
import os, sys import itertools as it outFilePath = sys.argv[1] parameterDict = {} for parameter in sys.argv[2:]: parameterName = parameter.split("=")[0] parameterOptions = parameter.split("=")[1].split(",") parameterDict[parameterName] = parameterOptions parameterNames = sorted(parameterDict.keys()) o...
import numpy as np import gym from gym import spaces from gym.utils import seeding from imitation.policies.base import HardCodedPolicy from .lq_game import LQFeedbackGame, AffineStrategy import imitating_games class FeedbackGameEnv(gym.Env): """ A generic, stateful wrapper that creates a `gym.Env` from a game...
import numpy as np import pytest from sklearn import datasets from sklearn.linear_model import LogisticRegression from scipy.sparse import csc_matrix from sparse_ho.models import SparseLogreg from sparse_ho.forward import get_beta_jac_iterdiff from sparse_ho.implicit_forward import get_beta_jac_fast_iterdiff from spar...
#!coding:utf8 #author:yqq #date:2019/3/4 0004 14:35 #description: 比特币地址生成算法 #author:yqq #date:2020/07/9 11:22 #description: 迁移到 python3 import hashlib import ecdsa import os from binascii import unhexlify, hexlify g_b58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' g_nMaxPri...
from multiprocessing import Process def foo(): print('hello') p = Process(target=foo) p.start()
# Copyright 2021 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, ...
#!/usr/bin/env python # we're using python 3.x style print but want it to work in python 2.x, from __future__ import print_function import os import argparse import sys import math import subprocess import shutil import tempfile import threading parser = argparse.ArgumentParser(description="This script evaluates the ...
import matplotlib as mpl font = {'family' : 'serif', 'size' : 16} mpl.rc('font', **font) import numpy as np randu = np.loadtxt("randu.txt") randu_x = randu[:,0] randu_y = randu[:,1] import matplotlib.pyplot as plt plt.figure() plt.scatter(randu_x, randu_y) plt.ylabel("$y$", fontsize=20) plt.xlabel("$x$",fon...
""" 面向对象技术简介 类(Class): 用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。 类变量:类变量在整个实例化的对象中是公用的。类变量定义在类中且在函数体之外。类变量通常不作为实例变量使用。 数据成员:类变量或者实例变量, 用于处理类及其实例对象的相关的数据。 方法重写:如果从父类继承的方法不能满足子类的需求,可以对其进行改写,这个过程叫方法的覆盖(override),也称为方法的重写。 局部变量:定义在方法中的变量,只作用于当前实例的类。 实例变量:在类的声明中,属性是用变量来表示的。这种变量就称为实例变量,是在类声明的内部但是在类的其他成员方法之外声明的。 继承...
# coding=utf-8 from OTLMOW.OTLModel.Classes.DirectioneleRelatie import DirectioneleRelatie # Generated with OTLClassCreator. To modify: extend, do not edit class IsInspectieVan(DirectioneleRelatie): """De relatie geeft aan dat er een inspectie, proef of meting gedaan kan worden op een onderdeel of installatie. De...
#pylint: disable=import-error,invalid-name,broad-except from pyrevit import revit, DB from pyrevit import script output = script.get_output() logger = script.get_logger() filt = DB.ElementCategoryFilter(DB.BuiltInCategory.OST_RoomTags) collect = DB.FilteredElementCollector(revit.doc, revit.doc.ActiveView.Id).WhereE...
#!/usr/bin/env python # Copyright 2019 Jian Wu # License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) import random import torch as th import torch.nn as nn import torch.nn.functional as tf from typing import Optional, Tuple, Union from aps.asr.base.component import OneHotEmbedding, PyTorchRNN HiddenTy...
def maxProfit(prices): start = 1 last = 0 l = len(prices) profit = 0 while start < l: if prices[last] >= prices[start]: last = start start += 1 elif prices[start] > prices[last]: cur_profit = prices[start] - prices[last] if ...
import pandas as pd import matplotlib.pyplot as plt my_dataset = pd.read_excel('Smith_glass_post_NYT_data.xlsx', sheet_name='Supp_traces') my_range = my_dataset['Zr'].max()- my_dataset['Zr'].min() print ('-------') print ('Range') print("{0:.0f}".format(my_range)) print ('-------') fig, ax = plt.subplots() ax.hist(...
import torch from model.san import san from util.complexity import get_model_complexity_info with torch.cuda.device(0): model = san(sa_type=0, layers=[2, 1, 2, 4, 1], kernels=[3, 7, 7, 7, 7], num_classes=1000) # model = san(sa_type=0, layers=[3, 2, 3, 5, 2], kernels=[3, 7, 7, 7, 7], num_classes=1000) # m...
import json from pathlib import Path from typing import Dict, Any from typing import List from typing import NamedTuple from typing import Union from yukarin.param import AcousticParam from yukarin.utility.json_utility import JSONEncoder class DatasetConfig(NamedTuple): acoustic_param: AcousticParam input_gl...
#!/usr/bin/env python import hashlib import io import json import multiprocessing import os import sys from collections import OrderedDict from unittest.mock import call, mock_open, patch import pytest import requests import wasapi_client as wc WASAPI_URL = 'http://example.com/webdata' WASAPI_TEXT = "".join("""{ ...
from ditto.store import Store from ditto.writers.json.write import Writer from ditto.readers.cyme.read import Reader as Reader_cyme from ditto.readers.opendss.read import Reader as Reader_opendss import os def update_persistence_jsons(): test_list = os.walk('data') for (dirpath, dirname, files) in test_list: ...
# -*- coding: utf-8 -*- """ Created on Mon Jul 23 22:48:24 2018 @author: ning """ import os working_dir = '' import pandas as pd pd.options.mode.chained_assignment = None import seaborn as sns import numpy as np from sklearn.model_selection import StratifiedKFold,permutation_test_score from sklearn.ensemble import Ran...