text
stringlengths
38
1.54M
class Packet: def __init__(self, content): self.var1 = 12 self.var2 = 34 self._content = content def _getContent(self): return self._content content = property(_getContent)
from django.http import JsonResponse, HttpResponse from rest_framework import status from rest_framework.authentication import SessionAuthentication from rest_framework.generics import DestroyAPIView, RetrieveUpdateAPIView, CreateAPIView from rest_framework.permissions import IsAuthenticated from rest_framework.respons...
# coding=utf-8 from django.db import models from flowmeter.config.const import STATE_CHAR_LEN, UNIQUE_FLAG_CHAR_LEN from flowmeter.config.db.log_table import AlarmLog from flowmeter.config.db.user_table import User class AlarmLogReader(models.Model): """ 记录警报通知给了哪些用户 """ user = models.For...
from . import models from ._builtin import Page, WaitPage from otree.api import Currency as c, currency_range from .models import Constants class IntWaitPage(WaitPage): body_text = "You are waiting for other participants to make their choice." class PlayerChoosePage(Page): form_model = 'player' form_field...
from django.core.management.base import BaseCommand, CommandError from helper.credits import * from account.models import BasicUser ######################################################### ##### Updates Credits for Every User ################### ######################################################### class Comman...
#!/usr/bin/env python import argparse import csv import logging import logging.handlers import re import struct # DD/MM HH:mm:ss TIMESTAMP = r'[0-3][0-9]\/[01][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9]' METHOD_EVENT = r'Method = [\da-f]+|Event = [\da-f]+' # Ignore the second timestamp HEADER = r'^(?P<timestamp>{}) \(.+\...
#!/usr/bin/env python3 import os import json import shutil def main(): with open('config.json') as config_file: config_data = json.load(config_file) source_directory = config_data['source_directory'] target_directory = config_data['target_directory'] for item in os.listdir(source_directory): ...
#!/usr/bin/python import rospy from std_msgs.msg import UInt8MultiArray, UInt16MultiArray, Int16MultiArray, String import time import sys import os import numpy as np # messages larger than this will be dropped by the receiver MAX_STREAM_MSG_SIZE = (4096 - 48) # amount to keep the buffer stuffed - larger numbers mea...
# coding: utf-8 """ Shoppers OpenAPI This is a Shoppers Catalogue server. [Learn about Swagger](http://swagger.io) or join the IRC channel `#swagger` on irc.freenode.net. For this sample, you can use the api key `special-key` to test the authorization filters OpenAPI spec version: 1.0.0 Gener...
import os import sys import time import typing import logging import signal import traceback import multiprocessing as mp from multiprocessing.connection import wait from . exceptions import TaskInterrupt, WorkerInterrupt, BrokerError from . exceptions import WarmShutdown, ColdShutdown from . interfaces import App, Wor...
import cv2 import os import numpy as np import random import pickle import matplotlib.pyplot as plt from tqdm import tqdm import tensorflow as tf from tensorflow import keras from keras.models import Sequential from keras.layers import Activation, Dense, Dropout, Flatten, Conv2D, MaxPooling2D from keras.callbacks impo...
#!/usr/bin/env python #-*-coding: utf-8-*- '''校验请求参数是否合法''' def checkParamType(param): '''校验type参数是否合法 Args: param: {'type': '<type值>', ...} Returns: ('<type值>', {'status': '<错误状态>', 'message': '<错误描述>'}) ''' if not param.has_key('type'): return (None, {'status': 'lost_pa...
#!c:\projects\development\hos_cash\new_env\scripts\python.exe from django.core import management if __name__ == "__main__": management.execute_from_command_line()
import tensorflow as tf from ..utils.activations import get_activation from ..utils.dropouts import get_dropout from ..utils.initializations import get_init from ..utils.optimizers import get_optimizer from ..registry import register from ..utils import model_utils from ..utils import dropouts from ...training import ...
import logging import pytz import datetime from importlib import import_module from nameko.standalone.events import event_dispatcher from django.core.management.base import BaseCommand from django.conf import settings from django.core import serializers from microframework.utils import sort_models_by_relations from mic...
from django.conf.urls import url from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.registration), url(r'^validate/$', views.check_user, name="url_validate_user"), ]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This script should automatically annotate entities based on simple rules (e.g. assign 'I' pronoun to the current speaker) @author: Sharleyne Lefevre """ msg = 'This script should automatically annotate entities based on simple rules\n ' \ 'However it is not cle...
# -*- coding: utf-8 -*- """Unit tests for Token model.""" from __future__ import absolute_import, division, print_function, unicode_literals from datetime import datetime, timedelta import pytest from xl_auth.oauth.token.models import Token from ..factories import TokenFactory @pytest.mark.usefixtures('db', 'use...
import pytest from RegonAPI.validators import _re_is_digit_string from RegonAPI.validators import is_valid_regon8 from RegonAPI.validators import is_valid_regon9 from RegonAPI.validators import is_valid_regon13 from RegonAPI.validators import is_valid_regon14 testing = { "REGON9": "492707333", "REGON14": "123...
import tensorflow as tf import numpy as np import sys, re import os, json sys.path.append('/home/chzze/bitbucket/Rotator_loc') from tensorflow.contrib.framework import arg_scope from tensorflow.contrib import layers def get_info(data_path, key): with open(os.path.join(data_path, '.info'), 'r') as f: inf...
"""Elif (else if) branch instruction implementations. """ from apysc.branch.if_base import IfBase class Elif(IfBase): def _append_enter_expression(self) -> None: """ Append else if branch instruction start expression to file. Raises ------ ValueError ...
import os import pickle def getValue(): if os.path.isfile('pickle_abc'): with open('pickle_abc', 'rb') as f: try: return (pickle.load(f)) except Exception: pass with open('pickle_abc', 'wb') as f: pickle.dump(0, f) return (pickle....
class Solution: def sortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]: graph_i, graph_g = collections.defaultdict(list), collections.defaultdict(list) degree_i, degree_g = collections.defaultdict(int), collections.defaultdict(int) group_dict = colle...
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from filer.models import Folder class MainExplorerFolder(models.Model): class Meta: verbose_name = "Folder glowny przegladarki" verbose_name_plural = "Folder glowny przegladarki" name = models.CharField("Folder główny...
from flask_restplus import Api from apis.comparator.resources import ns api = Api( version='1.0', title='translator', description='Rest API for translation comparator app', ) api.add_namespace(ns)
#! /usr/bin/python # -*-coding:utf-8 -*- from appium import webdriver from time import sleep class DS(object): # 测试脚本与appium服务器进行连接的参数数据 d = { "device": "android", "platformName": "Android", "platformVersion": "8.1.0", "deviceName": "3634c4cc", "appPackage": "com.qk.bu...
from attendance import get_data from attendance import student_info from attendance import string_functions from attendance import handle_query from db import find_DB try: user = student_info.Student() except get_data.InvalidCredentials as e: print e.message exit(1) except get_data.LoginError as e: pr...
""" CompMod Exercise_2 Symplectic Euler time integration of a particle moving in a 3D Morse Potential Produces plots of the position of the particle and its energy, both as function of time. Also saves both to file. """ import sys import math import numpy as np import matplotlib.pyplot as pyplot from Particle3D imp...
from find_prime_factorization import get_prime_factors from find_prime_factorization import prime_sieve import time def direct_totient_function(k): p = 1 for l in get_prime_factors(k, prime_list): p *= (1 - 1./l[0]) return int(k * p) def check_permutation(a, b): a = str(a) b = str(b) ...
print "Mary had a little lamb." print "Its fleece was white as %s." % 'snow' print "And everywhere that Mary went." print "." * 10 # This gives us 10 dots. end1 = "C" end2 = "h" end3 = "e" end4 = "e" end5 = "s" end6 = "e" end7 = "B" end8 = "u" end9 = "r" end10 = "g" end11 = "e" end12 = "r" # The comma at the end con...
import pprint import boto3 from datetime import datetime client = boto3.client('cloudwatch') instID = 'i-000f5' start_time = datetime(2019,4,16,18,00,00) end_time = datetime(2019,4,17,10,00,00) response = client.get_metric_statistics(\ Namespace='AWS/EC2', MetricName='CPUUtilization', Dimensions=[ ...
""" Copyright (c) 2004-Present Pivotal Software, Inc. This program and the accompanying materials are made available under the terms of the 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....
from django.db import models class Contact(models.Model): name = models.CharField('name', max_length=50) sur_name = models.CharField('surname', max_length=50) email = models.EmailField('email') phone = models.IntegerField('phone') def __str__(self): return self.name class Meta: ...
import pandas as pd import numpy as np import matplotlib.pyplot as plt def build_data(): train = np.load('./data/train.npy') test = np.load('./data/test.npy') return train, test def distance(v1, v2): """ :param v1: array :param v2: array :return: dist """ dist = np.sqrt(np.sum(np...
import numpy as np import pandas as pd import matplotlib import numpy as np import pandas as pd import pickle from sklearn_crfsuite import metrics from collections import OrderedDict import matplotlib.pyplot as plt from keras.preprocessing.sequence import pad_sequences from keras.utils import to_categorical from sklea...
import smtplib server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login("zeng.warlon@gmail.com", "7183596771aA") msg = "HI!" server.sendmail("zeng.warlon@gmail.com", "zeng.warlon@gmail.com", msg) server.quit()
import requests import json endpoint_url = "https://api.spotify.com/v1/recommendations?" access_token = "ENTER_ACCESS_TOKEN_HERE" # OUR FILTERS limit: int = 10 seed_genres: str = "pop" market: str = "AU" query: str = f"{endpoint_url}?limit={limit}&seed_genres={seed_genres}&market={market}" response = requests.get(qu...
#------------------------------------------------------------------------------------------------- #Name :Lyrics Downloader #Author : Vijetha PV #Description :Just double click on the lyric.py , enter the name and artist of the song #and automatically saves the lyrics in the file you specify #Requirement Python 2.7.x d...
from django.contrib import admin from .models import Cookie, Club, ClubFundraiser # Register your models here. admin.site.register(Cookie) admin.site.register(Club) admin.site.register(ClubFundraiser)
# -*- coding: utf-8 -*- """ Created on Thu Jun 28 17:18:56 2018 @author: Shubham """ import os import numpy as np import torch import torchvision.datasets as dset import torch.nn as nn import torchvision.transforms as transforms import pyro import pyro.distributions as dist from pyro.infer import SVI, Trace_ELBO fro...
# Generated by Django 2.1.1 on 2020-07-21 05:45 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('secctions', '0008_comment_score'), ] operations = [ migrations.AddField( model_name='secction', name...
from django.shortcuts import render, get_object_or_404, redirect, reverse, Http404 from django.http import JsonResponse from django.contrib.auth import authenticate, login, logout from django.contrib.auth.forms import UserCreationForm from .models import Post, Comment, Category def index(request): return render(r...
#!/usr/bin/env python """ Created on Mon 2 Dec 2013 Kort eksempel som viser flerdimensjonale lister og arrayer. @author Benedicte Emilie Braekken """ from numpy import * # Ren python liste min_liste = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print min_liste # Indeksering print 'Matrise som liste:', min_liste[0] print 'T...
from PyQt5.QtCore import QThread, pyqtSignal from google_speech import googleSpeechHandler class SpeechThread(QThread): new_message = pyqtSignal(str) def __init__(self): QThread.__init__(self) self.gsh = None def __del__(self): self.wait() def gshCallback(self, message): ...
#!/usr/bin/env python3 import getpass import sys import telnetlib import time # host ip HOST = "10.122.163.64" # auth method if needed user = raw_input("Enter your remote account: ") password = getpass.getpass(prompt='Password: ') enable = getpass.getpass(prompt='Enable: ') # test vlans should be added in following...
''' # -*- coding:utf8 -*- # Auther : Mark # File : # Date : # Des : 工程介绍:http://blog.csdn.net/jerr__y/article/details/61195257 TensorFlow命令介绍:https://wenku.baidu.com/view/7b416358a9114431b90d6c85ec3a87c240288ac1.html ''' import tensorflow as tf import numpy as np from tensorflow.contrib imp...
import numpy as np import matplotlib.pyplot as plt import LatticeDefinitions as ld import GeometryFunctions as gf import GeneralLattice as gl import LAMMPSTool as LT import sys from mpl_toolkits.mplot3d import Axes3D import copy as cp strDirectory = str(sys.argv[1]) intSigma = int(sys.argv[2]) fig = plt.figure(figs...
# Generated by Django 2.1.1 on 2018-10-11 11:37 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('Auction', '0003_auto_20181011_0854'), ] operatio...
__author__ = 'newtonis' def gPingText(value): value = float(int(value*10)) value /= 10.0 if value < 10: return " " + str(value) + " ms" elif value < 100: return " " + str(value) + " ms" elif value < 1000: return " " +str(value) + " ms" elif value < 10000: retu...
# -*- coding: utf-8 -*- """ WallyAI @author: Jorge Calvo """ from matplotlib import pyplot as plt import os import numpy as np import sys import tensorflow as tf from object_detection.utils import label_map_util from object_detection.utils import visualization_utils as vis_util from flask_socketio impor...
#!/usr/bin/python # coding=utf-8 from selenium.webdriver.common.by import By from base import Base from selenium import webdriver import os import unittest class WebDemo(unittest.TestCase): """ai test """ @classmethod def setUpClass(cls) -> None: print(cls.docs) driver_path = os.path.join...
notas = [['José', 5.0, 6.5, 3.4], ['Carlos', 3.5, 6.7, 7.7], ['Rui', 4.4, 9.5, 9.5]] print('Mostrando todos os valores:') for linha in range(len(notas)): # note a diferença deste "for" para o que vem na linha abaixo for coluna in range(len(notas[linha])): print(f'A linha {linha}, coluna {coluna} possui o v...
# -*- coding: utf-8 -*- """ Created on Mon Mar 13 13:09:17 2017 @author: USER """ from PyQt4.QtGui import * import sys import StudentTable class XDialog(QDialog, StudentTable.Ui_MyDialog): def __init__(self): QDialog.__init__(self) # setupUi() 메서드는 화면에 다이얼로그 보여줌 self.setupUi(self) ...
import rpg_classes import random import rpg_file_def import rpg_items import pygame, sys from pygame import * import rpg_animations import rpg_items import rpg_class_select map_height=700 map_width=1000 boundary_width=20 DISPLAYSURF = pygame.display.set_mode((map_width,map_height)) font=pygame.font.SysFont('monospace'...
def sumDigit(): global num global summ while num > 0: summ += num % 10 num = int(num / 10) number=int(input("Enter the number:")) num=number summ = 0 sumDigit() print("The sum of the digits in",number," is",summ)
from django.db import models class SavedFormData(models.Model): form_name = models.CharField(max_length=15) # this is the original form data form_data = models.TextField() #this is the form data with the other fields only form_data_mod = models.TextField() # # this is the extracted fields of ...
# Copyright (c) 2014, Salesforce.com, Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # - Redistributions of source code must retain the above copyright # notice, this list of conditions...
#!/usr/bin/env python # coding: utf-8 # # Mosquito Larvae in my Country # Under the GLOBE project, citizen scientists around the world have been monitoring mosquitoes. In particular, they have been counting larvae and attempting to identify the specific genera involved. This data is available from the GLOBE API. T...
"""messages._utils tests.""" import builtins import re import pytest import messages._utils from messages._utils import credential_property from messages._utils import validate_property from messages._utils import validate_input from messages._utils import check_valid from messages._utils import validate_email from ...
from iniciativa.app import db class MastersVessel(db.Model): __tablename__ = 'master_vessels' __bind_key__='datalake' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), nullable=True) imo = db.Column(db.String(80), nullable=True) tp_id = db.Column(db.Integer(), ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test context-sensitive Parser registry. """ from os import pardir from os.path import join from unittest import main, TestCase #logging.basicConfig(level=logging.DEBUG) from module_test import * from sneakylang import * from sneakylang.document import DocumentNode ...
import oci import time from datetime import datetime, timedelta from datetime import date import argparse from oci.config import from_file from oci.config import validate_config # Args parser configuration parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter, description="Cre...
"""Data generator with matching histogram.""" import numpy as np from matchzoo.processor_units import MatchingHistogramUnit from matchzoo.data_pack import DataPack from matchzoo.data_generator import DataGenerator from matchzoo.data_generator import PairDataGenerator def trunc_text(input_text: list, length: list) -...
import pandas as pd from textblob import TextBlob #importing the data ds=pd.read_csv("CEH_exam_negative_reviews.csv") ds #converting the csv file to string format dataset=ds.to_string(index=False) type(dataset) dataset blob = TextBlob(dataset) print(blob.sentiment) #data cleaning import re data...
import os class DevelopmentConfig(object): SQLALCHEMY_DATABASE_URI = "postgresql://postgres:postgres@localhost:5432/realm" DEBUG = True SECRET_KEY = "77a61869bc93b509efe6db6b282b19f6"
# fname = raw_input("Filename: ") fname = 'mbox-short.txt' try: fh = open(fname) except: print 'File cannot be opened:', fname exit() count = 0 for line in fh: if line.startswith('From: '): email = line.split()[1] count += 1 print email print "There were", count, "lines in the file with From as th...
import time import requests from app import config from app import pyppeteer from app import sanitize from app import storage from app import urls from app.logger import logger def authenticate_current_session(term, unique_session_id, cookies): """Make a POST request that will authenticate the user with this JS...
def rotate(state, wheel): x, a = [0, 0, 1, 5, 6][int(wheel)], list(state) a[x],a[2+x],a[3+x],a[5+x]=a[2+x],a[5+x],a[x],a[3+x] return tuple(a) def puzzle88(state): queue, history = [('', state)], set() while len(queue): rotations, wheel_state = queue.pop(0) if wh...
from django.db import models from django.contrib.auth import get_user_model from django.contrib.auth.models import AbstractUser from django.db.models.signals import pre_save, post_save from core.signals import send_account_verification from alfheimproject.settings import SECRETS User = get_user_model() # class Mas...
from uuid import uuid4 from django.utils.text import camel_case_to_spaces from git_orm.models.fields import TextField, CreatedAtField, UpdatedAtField from django.db.models.options import Options as DjangoOptions class Options(DjangoOptions): def __init__(self, meta, app_label=None): super(Options, self...
from gensim.models import LdaMulticore as LDA import os import argparse parser = argparse.ArgumentParser(description='View generated topics') parser.add_argument('--n_topics', help='Number of Topics') parser.add_argument('--gram', help='unigram or both') args = parser.parse_args() model=LDA.load(os.getcwd() +"/LDA ...
print("""She said, "My name is... Julia." """) print("Hello, world!") print() print("""I said, "I love Python." """)
import logging from datetime import datetime from flask import make_response, abort logging.basicConfig(filename='todo.log',level=logging.INFO) def get_timestamp(): return datetime.now().strftime(("%Y-%m-%d %H:%M:%S")) # Data to serve with our API TODO = { "Clean": { "title": "Clean", ...
from Base import Base from sqlalchemy import Column, Integer, String class Studiengang(Base): """ Klasse zur Darstellung eines Studiengangs Zu jedem Studiengang gehören mehrere Semestergruppe Bsp. Informatik/Softwaretechnik -> Inf1 - Inf6 """ __tablename__ = 'studiengang' ...
import os import torch from model.imsi_model_builder import ModelBuilder from utils.load_model import load_pretrain from tracker.IMSiamTracker import IMSiamTracker import cv2 from glob import glob import numpy as np from utils.load_text import load_text from config import cfg torch.set_num_threads(1) def get_frames(...
from __future__ import print_function import numpy import theano import theano.tensor as T from theano.tensor.shared_randomstreams import RandomStreams import timeit import os import climin import climin.util import climin.initialize import sys from PIL import Image from math import sqrt from dA import dA from data i...
#!/usr/bin/python import requests import json import sys def pollItemInformation(): # OFFICIAL_ITEM_API_URL = "http://services.runescape.com/m=itemdb_oldschool/api/catalogue/detail.json?item=" OSBUDDY_ITEM_SUMMARY_API_URL = "https://rsbuddy.com/exchange/summary.json" # official_item = requests.get(OFFICIA...
''' Definition A dictionary is a collection of key/value pairs, very similar to lists except you use keys instead of indexes to access the values in it. Syntax: d = { key1: val1, key2: val2, ... } A key can be of any immutable data type. ''' #d = { [1,2] : True } #print(d) d = { (1,2) : True } print(d) emails...
from argparse import ArgumentParser, Namespace name: str = "CLIME" authors: list = [ "Nicholas M. Synovic", "Matthew Hyatt", "Sohini Thota", "George K. Thiruvathukal", ] def mainArgs() -> Namespace: parser: ArgumentParser = ArgumentParser( prog=f"{name} Issue Density", description...
import math r=float(input()) area= math.pi*(r**2) v=(4/3)*(math.pi)*(r**3) print(round(area,3)) print(round(v,3))
from prowler.providers.azure.lib.audit_info.models import ( Azure_Audit_Info, Azure_Identity_Info, ) azure_audit_info = Azure_Audit_Info( credentials=None, identity=Azure_Identity_Info(), audit_metadata=None )
import asyncio import discord from discord.ext import commands from discord.ext.commands.errors import CommandNotFound, MissingRequiredArgument class Manager(commands.Cog): """Management commands""" def __init__(self,bot): self.bot = bot #Console event to know if the bot is online @comma...
#!/usr/bin/env python3 """ This script identifies flag chains in bvDSL programs. For each adds flag v e0 e1; or adcs flag v e0 e1 flag' it checks if the value of flag is always zero. If so, it prints add v e0 e1; mov flag 0 or adc v e0 e1 flag'; mov flag 0 Otherwise, it prints the original instruction. Let VE...
"""Wrapper for constants in edf_data.h""" def invert_dict(d): new_dict = {} for k, v in d.items(): new_dict[v] = k return new_dict event_codes = invert_dict(dict( NO_ITEMS = 0, STARTPARSE = 1, ENDPARSE = 2, STARTBLINK = 3, ENDBLINK = 4, STARTSACC...
#-*- coding:utf-8 -*- from PIL import Image import os import glob os.chdir('.')#图片所在的文件夹 for file_names in glob.glob('*.png'):#找出所有的后缀为bmp的格式的图片 print(file_names) file_path = file_names#拼接出图片的完整url print(file_path) out_path = os.path.splitext(file_path)[0]+'.jpg' im = Image.open(file_path) ...
# Modify this function to return a list of strings as defined above def list_benefits(): return "More organized code", "More readable code", "Easier reuse of code", "Allows programmers to share code and connect it together" # Modify this function to concatenate to each benefit - " is a benefit of functions!" def b...
""" >>> import numpy as np >>> import scipy >>> id(scipy.dot) == id(np.dot) True >>> A = scipy.sparse.csr_matrix([[1, 2, 0], [0, 0, 3], [4, 0, 5]]) >>> v = scipy.sparse.csr_matrix([[1], [0], [-1]]) >>> A.dot(v) <3x1 sparse matrix of type '<class 'numpy.int64'>' with 3 stored elements in Compressed Sparse Row format...
import requests import os import errno from bs4 import BeautifulSoup path = "/Torrents/" os.makedirs(os.path.dirname(path), exist_ok=True) def download(url, file_name): with open(path + file_name.replace('\n', '') + '.torrent', "wb") as file: #get request response = requests.get(url) file.write(respons...
from django.http import HttpResponse from django.shortcuts import render, redirect from comment.forms import NewComment from comment.models import Comment from CSSA_ROOT.util.authority_decorators import * from news.models import News, NewsTopic @admin def delete_comment(request): cmt_id = request.GET['id'] C...
from functools import reduce from operator import mul import torch import numpy as np from utils_dynamics import * device = torch.device('cpu') class TrackerDyn_all_distances: def __init__(self, T0, W=1, t=0, noise=0.0001, metric=1, not_GT=True): self.T0 = T0 self.t = t self.noise = noise...
from rest_framework import serializers from games.models import ROFR_model, JUDO_model,Company_Merger_model,Price_War_model class ROFR_Serializer(serializers.ModelSerializer): class Meta: model = ROFR_model # fields = '__all__' fields = ('id', 'CBS_price_1', 'CBS_price_2', 'NBC_price_1', '...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('iwmiproject', '0097_remove_waterliftingcalibration_plot'), ] operations = [ migrations.CreateModel( name='Consum...
import functools import re from dataclasses import field from typing import Callable, Dict, Iterable, Union from pheasant.core.base import Base SURROUND_TAG = re.compile( r"^([^<]*)<(?P<tag>(span|div))(.*)</(?P=tag)>([^>]*)$", re.DOTALL ) class Decorator(Base): decorates: Dict[str, Callable[..., None]] = fi...
import numpy as np import bitstring import time from numba import njit class FileReader: def __init__(self, **kargs): super().__init__() def read_example(self, filename): raise Exception("This function is not implemented.\n" "You are directly using the FileReader abs...
# Copyright (c) OpenMMLab. All rights reserved. import copy import numpy as np import torch from mmcv import ConfigDict from mmcv.cnn import ConvModule, xavier_init from mmcv.cnn.bricks.transformer import (build_positional_encoding, build_transformer_layer) from mmcv.ops import...
#! /usr/bin/env python # -*- coding: utf-8 -*- '''python challenge level 8 question url: http://www.pythonchallenge.com/pc/def/integrity.html answer url: http://www.pythonchallenge.com/pcc/return/good.html:huge:file ''' import bz2 un = 'BZh91AY&SYA\xaf\x82\r\x00\x00\x01\x01\x80\x02\xc0\x02\x00 \x00!\x9ah3M\x07<]\xc9\...
# -*- encoding:utf-8 -*- import xadmin from .models import CityDict, CourseOrg, Teacher, Blog, BlogContent __author__ = 'Amos' __date__ = '2017/6/20 11:48' class CityDictAdmin(object): """ 注册CityDict的管理器 """ list_display = ['name', 'desc', 'add_time'] list_filter = ['name', 'desc', 'add_time'] ...
# -*- coding:UTF-8 -*- # Author:Tiny Snow # Date: Sat, 20 Feb 2021, 20:13 # Project Euler # 031 Coin sums #=======================================Solution ways = 0 coins = [200, 100, 50, 20, 10, 5, 2, 1] def way(money, coin): if coin == 7: global ways ways += 1 return i = 0 while i...
import torch from torch import nn from torch.nn import functional as F class Generator(nn.Module): def __init__(self, z_size, d=128, channels=1): super(Generator, self).__init__() self.deconv1_1 = nn.ConvTranspose2d(z_size, d*2, 4, 1, 0) self.deconv1_1_bn = nn.BatchNorm2d(d*2) sel...
# -*- encoding:utf-8 -*- """ 波士顿房价 """ from sklearn.datasets import load_boston from sklearn.linear_model import LinearRegression, SGDRegressor from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import mean_squared_error # 获取数据 data = load_boston...