content
stringlengths
5
1.05M
# -*- coding: utf-8 -*- """ Created on Fri Nov 16 00:13:05 2018 @author: Gireesh Sundaram """ import pandas as pd import numpy as np import seaborn as sns from sklearn.preprocessing import OneHotEncoder, LabelEncoder from sklearn.cross_validation import train_test_split from sklearn.neighbors import KNe...
# # Copyright (c) 2020 Xilinx, Inc. All rights reserved. # SPDX-License-Identifier: MIT # platform = "microblaze" procs = ["microblaze"] serial_port = "serial" arch = "microblaze" linux_compiler = "microblazeel-xilinx-linux-gnu-" dtb_loadaddr = 0x81E00000 dtb_arch = "microblaze" dtb_dtg = "microblaze-generic" dtb_de...
# -*- coding: utf-8 -*- from terminaltables import AsciiTable from colorclass import Color class CostAnalysis: def __init__(self, db): self.db = db def draw(self, market, symbol, args): if len(args) != 0: raise Exception('no argument required for {}'.format(CostAnalysis.__name__)...
# Size of program memory (bytes) MAX_PGM_MEM = 4096 # Size of context memory (bytes) MAX_DATA_MEM = 2048 # Max stack size (bytes) MAX_STACK = 512 # Number of registers MAX_REGS = 11 # Default output indentation for some debug messages IND = " " * 8 # Maximum values for various unsigned integers MAX_UINT8 = 0xff MAX...
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutStrings(Koan): # https://docs.python.org/3/library/stdtypes.html#textseq # https://docs.python.org/3/library/unittest.html#assert-methods # https://docs.python.org/3/library/functions.html#isinstance def test_double_...
# Mount RPC client -- RFC 1094 (NFS), Appendix A # This module demonstrates how to write your own RPC client in Python. # When this example was written, there was no RPC compiler for # Python. Without such a compiler, you must first create classes # derived from Packer and Unpacker to handle the data types for the # s...
import os import librosa import numpy as np import pandas as pd from pandas import DataFrame from sklearn.preprocessing import LabelEncoder # def get_feature_label(row, directory): def get_feature_label(row, directory): file_name = os.path.join(directory, str(row.ID) + '.wav') # file_name = os.path.join("da...
from urllib.parse import urlencode,parse_qs,unquote def stringify(d,u=False): qs = urlencode(d) if u: qs = unquote(qs) return qs def parse(url): d = dict( (k, v if len(v)>1 else v[0] ) for k, v in parse_qs(url).items() ) return d
#!/usr/bin/python #coding:utf-8 import json import copy import time import os endpoint = "bind9" name_stats_path = "/var/named/data/named_stats.txt" def main(): if os.path.isfile(name_stats_path): os.remove(name_stats_path) os.system("rndc stats") ts = int(time.time()) payload = [] data = {"endpoint":endpoint...
from plugins.database import db class BaseModel: def save(self): try: db.session.add(self) db.session.commit() return True except: return False
"""Creates a custom kinematics body with two links and one joint """ from openravepy import * from numpy import eye, array, zeros env = Environment() # create openrave environment env.SetViewer('qtcoin') # attach viewer (optional) with env: robot=RaveCreateRobot(env,'') robot.SetName('camera') linkinfo=Ki...
import itertools from surprise import accuracy from collections import defaultdict class RecommenderMetrics: def mae(predictions): return accuracy.mae(predictions, verbose=False) def rmse(predictions): return accuracy.rmse(predictions, verbose=False)
from setuptools import setup install_requires = ( 'beautifulsoup4==4.6.3', ) tests_require = ( 'pytest', 'pytest-cov', 'mock', ) setup_requires = ( 'pytest-runner', 'flake8', ) setup( name='tracking-id-injector', version='1.0.1', url='https://github.com/msufa/tracking-id-injector...
import argparse import time import math import numpy as np import sklearn.metrics as sk import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F import data import model from utils_lm import batchify, get_batch, repackage_hidden # go through rigamaroo to do ..utils.displ...
from typing import Optional from openslides_backend.action.actions.user.user_scope_permission_check_mixin import ( UserScope, ) from openslides_backend.permissions.management_levels import ( CommitteeManagementLevel, OrganizationManagementLevel, ) from openslides_backend.permissions.permissions import Perm...
""" GUI layout that allows free positioning of children. @author Ben Giacalone """ from tools.envedit.gui.gui_layout import GUILayout class GUIFreeLayout(GUILayout): def __init__(self): GUILayout.__init__(self) self.children = [] # Adds a child to the layout def add_child(self, child): ...
#!/bin/python # # File: test-all.py # Authors: Leonid Shamis (leonid.shamis@gmail.com) # Keith Schwarz (htiek@cs.stanford.edu) # # A test harness that automatically runs your compiler on all of the tests # in the 'samples' directory. This should help you diagnose errors in your # compiler and will help you ga...
number_1 = int(input('Enter your first number:')) number_2 = int(input('Enter your second number:')) operator = str(input('Enter your operator')) if operator=='+': print(number_1 + number_2) elif operator=='-': print(number_1 - number_2) elif operator=='*': print(number_1 * number_2) elif operator=='/': ...
# Winston Peng # SoftDev1 pd9 # K10 -- Jinja Tuning # 2019-9-23 from flask import Flask, render_template import static.script as script app = Flask(__name__) @app.route('/occupyflaskst') def occupations(): return render_template( 'occ.html', team = 'Connor Oh, Nahi Khan, Winston Peng -- T...
#!/usr/bin/env python # macro_avg.py v1.0 9-19-2012 Jeff Doak jeff.w.doak@gmail.com from chargedensity import * import numpy as np import sys if len(sys.argv) > 1: if str(sys.argv[1]) == "CHG": a = ChargeDensity(str(sys.argv[1]),format_="chgcar") else: a = ChargeDensity(str(sys.argv[1])) else...
""" A python module to communicate with Elecrolux Connectivity Platform """ __all__ = [ 'Error', 'LoginError', 'RequestError', 'ResponseError', 'Session' ] from .Session import ( Error, LoginError, RequestError, ResponseError, Session )
from enum import Enum class Transition(Enum): """ Enumeration of the transitions a job can go through. """ ACQUIRE = 0 RELEASE = 1 START = 2 PROGRESS = 3 FINISH = 4 ERROR = 5 RESET = 6 ABORT = 7 CANCEL = 8 @property def json_property_name(self) -> str: ...
from ..models.box_daily_square import BoxDailySquare class BoxDailySquareManager(object): def create_box(self, data): box, created = BoxDailySquare.objects.get_or_create( user=data['user'], office=data['office'] ) return box
import os import shutil import subprocess CONNECT_REPORTS_REPO_URL = 'https://github.com/cloudblue/connect-reports.git' BASE_DIR = os.path.abspath( os.path.normpath( os.path.join( os.path.dirname(__file__), '..', ), ), ) REPO_EMBED_DIR = os.path.join( BASE_DIR, ...
from scipy import integrate def integrand(x0, x1, x2): return x2 * x1**2 + x0 x2_lim = (0.0, 0.5) x1_lim = lambda x2:(0.0, 1.0-2.0*x2) x0_lim = lambda x1,x2:(-1.0, 1.0+2.0*x2-x1) # int_{x2=0}^{0.5} int_{x1=0}^{1-2x2} int_{x0=-1}^{1+2x2-x1} (x2 x1**2 + x0) dx0 dx1 dx2 integral,error = integrate.nquad(integrand, [x0_...
#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Da...
"""Dyson new v2 pure Hot+Cool device.""" import logging from .const import HeatMode from .dyson_pure_cool import DysonPureCool from .utils import printable_fields _LOGGER = logging.getLogger(__name__) class DysonPureHotCool(DysonPureCool): """Dyson new Pure Hot+Cool device.""" def _parse_command_args(self...
from .data import COVID19India from .mongo_db import get_data, upload_data from .data_processing import get_daily_data, get_state_daily, get_interval_data from .inshorts_news import InshortsNews
from .csr import skeleton_to_csgraph, branch_statistics, summarize, Skeleton __version__ = '0.10.0-dev' __all__ = ['skeleton_to_csgraph', 'branch_statistics', 'summarize', 'Skeleton']
class NumMatrix: def __init__(self, matrix: List[List[int]]): if len(matrix) == 0: self.dp = [] return width, height = len(matrix[0]), len(matrix) self.dp = [[0] * (width + 1) for _ in range(height + 1)] for i in range(1, height+1): for...
# ############################################################################ # Copyright (c) 2017 Huawei Technologies Co.,Ltd and others. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, ...
import os, sys, re, time import urllib, urllib2 from BeautifulSoup import BeautifulSoup #import beautifulsoup4 import gzip from StringIO import StringIO import MySQLdb import simplejson as json import datetime import pandas as pd import pymongo #from cassandra.cluster import Cluster import conf.config as config from cr...
n = input('Digite algo: ') print('O timpo primitivo do que foi digitado é: {}'.format(type(n))) print('Ele é numérico? {}'.format(n.isnumeric())) # Compara se é um numero, se sim envia a mensagem True print('Ele é um texto? {}'.format(n.isalpha())) # Compara se é Letra, se sim envia a mensagem Tru...
import sys from rpython.tool.pairtype import pairtype from rpython.flowspace.model import Constant from rpython.rtyper.rdict import AbstractDictRepr, AbstractDictIteratorRepr from rpython.rtyper.lltypesystem import lltype, llmemory, rffi from rpython.rlib import objectmodel, jit, rgc, types from rpython.rlib.signature ...
import numpy as np i8 = np.int64() i4 = np.int32() u8 = np.uint64() b_ = np.bool_() i = int() f8 = np.float64() b_ >> f8 # E: No overload variant i8 << f8 # E: No overload variant i | f8 # E: Unsupported operand types i8 ^ f8 # E: No overload variant u8 & f8 # E: No overload variant ~f8 # E: Unsupported operan...
# -*- coding: utf-8 -*- import datetime, json, logging, os, subprocess from fast_reconcile_app import settings_app from django.conf import settings # from django.core.urlresolvers import reverse log = logging.getLogger(__name__) def get_commit(): """ Returns commit-string. Called by views.info() """ ...
# Copyright 2019-2021 Foreseeti AB <https://foreseeti.com> # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
# # Copyright 2016 The BigDL 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 ...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ This module contains collection of classes which implement collate functionalities for various tasks. Collaters should know wh...
# coding: utf-8 import clinica.engine as ce class PetSurfaceLongitudinalCLI(ce.CmdParser): def define_name(self): """Define the sub-command name to run this pipeline.""" self._name = "pet-surface-longitudinal" def define_description(self): """Define a description of this pipeline."""...
import time from threading import Thread from cassandra import ConsistencyLevel from ccmlib.node import ToolError from dtest import Tester, debug from tools import insert_c1c2, query_c1c2, since class TestRebuild(Tester): def __init__(self, *args, **kwargs): kwargs['cluster_options'] = {'start_rpc': 't...
from django.core.management.base import BaseCommand from schedule import models from django.utils import timezone from django.conf import settings import requests import requests.auth import logging logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): sch...
###################################### # # Nikolai Rozanov (C) 2017-Present # # nikolai.rozanov@gmail.com # ##################################### import numpy as np # # This file is a way of learning the Kernel and performing a hypothesis test, by computin the test statistics # class TEST(object): ''' main...
import os from PIL import Image import tensorflow as tf from Fishnet import FishNets import numpy as np import json def onehot(label): n_sample = len(label) # n_class=max(label)+1 onehot_labels = np.zeros((n_sample, 6)) onehot_labels[np.arange(n_sample), label] = 1 return onehot_labels def read(file_list): ...
from numpy import dot, diag, ones, zeros, sqrt from openopt.kernel.ooMisc import norm def amsg2p(f, df, x0, epsilon, f_opt, gamma, callback = lambda x, f: False): # returns optim point and iteration number f0 = f(x0) if f0 - f_opt <= epsilon: return x0, 0 x, n = x0.copy(), x0.size df0 = df(x0) ...
import torch as t import torch.nn as nn import torch.nn.functional as f from config import config from torch.optim import Adam, SGD, Adagrad from torch.autograd import Variable from data_utils import batch_by_num from base_model import BaseModel, BaseModule import logging import os class RotatEModule(BaseMo...
import math import numpy as np from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F import logging from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence from src.datasets.utility import find_sub_list from src.scripts.tools.utility import get_device class Em...
# run tests to check coverage import os import asyncio import discord as dpy import prettify_exceptions prettify_exceptions.hook() import viper from viper.exts import discord basic_test = os.path.join("tests", "test_script.vp") discordpy_test = os.path.join("tests", "discordpy_script_test.vp") loop = asyncio.get_ev...
from flask import Flask from flask_sslify import SSLify app = Flask(__name__) app.config.from_object('config') sslify = SSLify(app) from jawfish import views
""" A script that processes the Qualitivity XML files and creates CSV files of extracted data. """ import argparse import os import sys from xml.etree import ElementTree import numpy as np import pandas as pd # data frame columns columns = ['Record ID', 'Segment ID', 'Total pause duration_300', 'Pause count_300', ...
# -*- coding: utf-8 -*- import cv2 import pytesseract pytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe' from tkinter import filedialog from tkinter import * root = Tk() root.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg file...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Feb 14 18:00:19 2021 @author: dipu """ from rico import * from utils import * from moka import * from datasets import * from scipy.optimize import linear_sum_assignment import os import time import sys import shutil import random ...
import numpy as np import os import cv2 def make_image_noisy(image, noise_typ): if noise_typ == "gauss": row, col, ch = image.shape mean = 0 var = 40 sigma = var**0.5 gauss = np.random.normal(mean, sigma, (row, col, ch)) gauss = gauss.reshape((row, col, ch)) ...
# -*- coding: utf-8 -*- from django.apps import AppConfig import urllib, requests, json from timetable.models import Course from ngram import NGram class SearchConfig(AppConfig): name = 'curso' class SearchOb(object): """docstring for SearchOb""" def __init__(self, uri=None): from pymongo impo...
#!/usr/bin/env python """The setup script.""" try: from setuptools import find_packages, setup except ImportError: from distutils.core import find_packages, setup setup(name='hyperscan-python', version='0.1', description='Simple Python bindings for the Hyperscan project.', author='Andreas Moser'...
def test_geoadd(judge_command): judge_command( 'GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania"', { "command": "GEOADD", "key": "Sicily", "longitude": "15.087269", "latitude": "37.502669", "member": '"Catania"', ...
import jpype jpype.startJVM() from asposecells.api import Workbook, PdfSaveOptions, ImageOrPrintOptions, SheetRender import cv2 import numpy as np DEBUG_MODE = False def excel2imgs(excel_path): workbook = Workbook(excel_path) ''' Excel to PDF ''' # pdfOptions = PdfSaveOptions() # pdfOptions.setOneP...
# -*- coding: UTF-8 -*- import cv2 as cv import os import argparse import numpy as np import pandas as pd import time from utils import choose_run_mode, load_pretrain_model, set_video_writer from Pose.pose_visualizer import TfPoseVisualizer from Action.recognizer import load_action_premodel, framewise_recogniz...
from typing import Optional, List from reconbot.notificationprinters.embedformat import EmbedFormat class NotificationFormat(object): def __init__(self, content: Optional[str], embeds: Optional[List[EmbedFormat]] = None): self.content = content if embeds is None: self.embeds = [] ...
from typing import List, Dict, Union from sse_starlette.sse import EventSourceResponse from fastapi import Depends, FastAPI, Request from fastapi_users import FastAPIUsers, BaseUserManager from fastapi_users.authentication import JWTAuthentication from sqlalchemy.orm import Session from . import crud, schemas from .a...
# -*- coding: UTF-8 -*- # Copyright 2015-2020 Rumma & Ko Ltd # License: BSD (see file COPYING for details) """Same as :mod:`lino_book.projects.noi1e`, but using :ref:`react` as front end. This uses :ref:`hosting.multiple_frontends`. .. autosummary:: :toctree: settings tests """
from mongoengine import signals __author__ = 'Enis Simsar' import json import re import threading from datetime import datetime from decouple import config from tweepy import OAuthHandler from tweepy import Stream from tweepy.streaming import StreamListener from models.Tweet import Tweet from models.Topic import Top...
#!/usr/bin/env python3 import argparse, os """ Trenco Module for arguments """ def txn_args(parser): parser.add_argument('--annotation-file', dest = 'annotfname', default = '', help="Genode annotations file in gtf format (overwrites --annota...
#!/usr/bin/env python3 import argparse import json import sys from datetime import datetime from time import sleep from splinter import Browser from tvlist_loader import xlparser from tvlist_loader import scraper from tvlist_loader import projects_parser as pp def main(): # Parse cli arguments parser = argp...
import matplotlib.pyplot as plt import numpy as np import os import seaborn as sns import shutil # =========== HYPERPARAMETERS ========== UNIVARIATE_DISTRIBUTIONS = ['chi_square_9', 'exp_9'] NUM_SAMPLES = 20000 NUM_TRIALS = 5 # ========== OUTPUT DIRECTORIES ========== OUTPUT_DIR = 'examples/power_analyses/univariate...
import scrapy import re from locations.items import GeojsonPointItem DAY_MAPPING = { "Mon": "Mo", "Tues": "Tu", "Wed": "We", "Thur": "Th", "Fri": "Fr", "Sat": "Sa", "Sun": "Su" } class KoppsSpider(scrapy.Spider): name = "kopps" item_attributes = { 'brand': "Kopps" } allowed_doma...
import smtplib from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email import encoders from user import User from mail import Mail class ImportantUser(User): ''' ImportantUser class inherits from User class. It is more complex version of it. It let's user add attachm...
/Users/NikhilArora/anaconda3/lib/python3.6/imp.py
# coding: utf-8 """Everythong related to parsing tracker responses""" import urlparse from lxml import etree class BaseParser(object): """Abstract base class for tracker response parser""" def parse_index(self, html): """Parse index html and return list of dicts""" raise NotImplementedError() ...
from compas.datastructures import Network def test_add_vertex(): network = Network() assert network.add_vertex() == 0 assert network.add_vertex(x=0, y=0, z=0) == 1 assert network.add_vertex(key=2) == 2 assert network.add_vertex(key=0, x=1) == 0
#!/usr/bin/python """ %prog [options] pair_1.fastq pair_2.fastq filter reads from paired fastq so that no unmatching reads remain. output files are pair_1.fastq.trim and pair_2.fastq.trim see: http://hackmap.blogspot.com/2010/09/filtering-paired-end-reads-high.html """ __version__ = "0.1.0" from subprocess import Pop...
#!/usr/bin/env python3 # # debris.db -- database-related operations for debris import sqlite3 import time from . import common from .common import run_process from .common import getconfig from .common import log class DebrisDB(object): """Object that can represent the database connection. We are using sql...
#AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"extract_tag": "om2.ipynb", "contains_tag": "om2.ipynb", "is_nbx": "om2.ipynb", "is_nbx_cell": "om2.ipynb", "is_magic_or_shell": "om2.ipynb", "": "om2.ipynb", ...
#Создай собственный Шутер! from pygame import * from random import randint from time import time as timer mixer.init() mixer.music.load('Fonk.ogg') mixer.music.play(-1) mixer.music.set_volume(0.2) fire_sound = mixer.Sound('blaster.ogg') fire_sound.set_volume(0.1) font.init() font1 = font.SysFont('Arial',80) win = fon...
#!/usr/bin/env python3 # # kcri.bap.shims.cgMLSTFinder - service shim to the cgMLSTFinder backend # import os, json, tempfile, logging from pico.workflow.executor import Task from pico.jobcontrol.job import JobSpec, Job from .base import ServiceExecution, UserException from .versions import BACKEND_VERSIONS # Our ser...
import time import pytest import examples import progressbar import original_examples def test_examples(monkeypatch): for example in examples.examples: try: example() except ValueError: pass @pytest.mark.filterwarnings('ignore:.*maxval.*:DeprecationWarning') @pytest.mark...
from .default import Config class DevelopmentConfig(Config): """ Configurations for Development. """ DEBUG = True TESTING = True SECRET = "DevelopSecret123!!" # pragma: allowlist secret
import numpy as np NUM_EXP = 1 def evaluate(job_id, params): np.random.seed(NUM_EXP) x = params['X'] y = params['Y'] z = params['Z'] a = params['A'] #print 'Evaluating at (%f, %f, %f, %f)' % (x, y, z, a) obj1 = float(1.10471 * np.power(x,2.0) * z + 0.04811 * a * y * (14.0+z)) + np.rand...
class Config: HOST_URL = "https://www.mirrativ.com" USER_AGENT = "MR_APP/8.67.0/Android/GA00747-UK/5.1.1" USER_ME = "/api/user/me" PROFILE_EDIT = "/api/user/profile_edit" FOLLOW = "/api/graph/follow" COMMENT = "/api/live/live_comment" LIVE = "/api/live/live" EDIT_LIVE = "/api/li...
import os import torch import numpy as np import pickle from utils import * def hook_fn(m, i, o): try: visualisation[m] = o.cpu().numpy() except AttributeError: visualisation[m] = o[0].cpu().numpy() if __name__=='__main__': with open('./results/cka/act_std.pkl', 'rb') as file: ...
# https://leetcode.com/problems/subsets-ii/description/ # # algorithms # Medium (40.24%) # Total Accepted: 173.2K # Total Submissions: 430.4K # beats 100.0% of python submissions class Solution(object): def subsetsWithDup(self, nums): """ :type nums: List[int] :rtype: List[List[int]] ...
""" retrieve environment variables and resolve references to AWS Parameter Store Parameters. """ from typing import Dict import os import boto3 def get(name: str, session: boto3.session.Session) -> str: """ gets the environment variable value specified by `name`. if the `value` starts with ssm://, it will...
""" A repository of typed entities, retrievable by their external reference Entity object API: entity.entity_type --> string used for groupung entity.external_ref --> lookup name entity.origin --> one-time settable parameter, set by the entity store entity.validate() --> must return True [for valid enti...
import bpy from bpy.props import * from ..node_socket import RenderNodeSocket, SocketBase, RenderNodeSocketmixin, RenderNodeSocketInterface from ..node_socket import update_node class RenderNodeSocketInterfaceRenderList(RenderNodeSocketmixin, RenderNodeSocketInterface, bpy.ty...
import ocaml assert(ocaml.Result.get_ok(ocaml.Result.Ok(True)) == True)
from opera.parser.yaml.node import Node from ..entity import Entity from ..path import Path from ..string import String class ImportDefinition(Entity): ATTRS = dict( file=Path, repository=String, namespace_prefix=String, namespace_uri=String, ) DEPRECATED = { "name...
#online = mongodb_online() #print('mongodb-online: ', online) #TODO: cron docker para mongo
# -*- coding: utf-8 -*- import json from django.db.models import Q from rest_framework.exceptions import PermissionDenied from rest_framework.generics import ( CreateAPIView, ListCreateAPIView, RetrieveAPIView, RetrieveUpdateDestroyAPIView ) from rest_framework.permissions import ( AllowAny, I...
from django.contrib import admin # Register your models here. from reg.models import UserProfile from .models import * class BookAuthorAdmin(admin.ModelAdmin): list_display = ('author_last_name', 'author_first_name', 'author_middle_name') search_fields = ('author_last_name', 'author_first_name', 'author_middle_name...
import numpy as np class ArgMaxPolicy(object): def __init__(self, critic): self.critic = critic def get_action(self, obs): if len(obs.shape) > 3: observation = obs else: observation = obs[None] ## TODO return the action that maxinmizes the Q-v...
# coding: utf-8 """ DocuSign REST API The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. OpenAPI spec version: v2 Contact: devcenter@docusign.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from ppr...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import sys import json import argparse from modules.FIC_Core import FICCore from modules.config import DEFAULT_DAYS, REP...
from django import forms from django.contrib.admin import widgets import os CHOICE = { ('0','キュート'), ('1','クール'), ('2','パッション'), } form SampleForm(forms.Form): select = forms.ChoiceField(label='属性', widget=forms.RadioSelect, choices= CHOICE, initial=0)
L=[[[*map(int,v.split(','))]for v in l.split('->')]for l in open("inputday5")] r,m=lambda n,x,y:x<=n<=y or y<=n<=x,max(max(max(p)for p in l)for l in L)+1 c=lambda a,b,f,s,w:(r(a,f[0],s[0])and r(b,f[1],s[1])and(f[0]==s[0]or f[1]==s[1]or(w and abs(f[0]-a)==abs(f[1]-b)))) print(*(sum(a)for a in((sum(c(i,j,f,s,b)for f,s in...
# Filename: HCm_UV_v5.0.py ##################### ###### IMPORTS ###### ##################### import string import numpy as np import sys #sys.stderr = open('errorlog.txt', 'w') import warnings warnings.filterwarnings("ignore") ####################### ###### FUNCTIONS ###### ####################### #Function for int...
__all__ = [ 'apply', 'applyCSS', 'change', 'changeCSS', 'delete', 'forwarddelete', 'insert', 'queryEnabled', 'queryIndeterm', 'queryState', 'querySupported', 'queryValue', 'selection', 'unapply', 'unapplyCSS' ]
# Copyright 1999-2020 Alibaba Group Holding Ltd. # # 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 a...
from Application import Application if __name__ == '__main__': app = Application()
# determines whether a matrix is orthogonal. A square matrix is orthogonal, # if its columns and rows are orthogonal unit vectors, # which is equivalent to: MT M = I import numpy as np def check_orthogonal(M): # make sure the input is a matrix if len(np.shape(M)) !=2: print("error: input is not a mat...
""" 抽象工厂 代码实例 Abstract Factory Code Demo 家具工厂 """ from __future__ import annotations from abc import ABC, abstractmethod class Chair(ABC): """ product interface 1: Chair """ @abstractmethod def sit_on(self) -> str: pass class Sofa(ABC): """ product interface 2: Sofa """ ...