text stringlengths 38 1.54M |
|---|
# coding=utf-8
'''
Created on 2016-7-26
@author: Jennifer
Project:编写Web测试用例
'''
import unittest
from test import test_baidu
from test import test_youdao
from test import test_json
#构造测试集
suite = unittest.TestSuite()
suite.addTest(test_baidu.BaiduTest('test_baidu'))
suite.addTest(test_youdao.YoudaoTest('test_youdao'))
s... |
s = 0
for i in range(3,118):
if i%15 == 0:
s = s + 15
elif i%5 == 0:
s = s + 5
elif i%3 == 0:
s = s + 3
else:
s = s + 1
print s
|
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
from plotly.subplots import make_subplots
import plotly.graph_objects as go
from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
import base64
st.set_page_config(page... |
import FWCore.ParameterSet.Config as cms
from RecoHI.HiEgammaAlgos.HiIsolationCommonParameters_cff import *
isoC1 = cms.EDProducer("HiEgammaIsolationProducer",
isolationInputParameters,
mode = cms.string("noBackgroundSubtracted"),
iso = cms.string("Cx"),
x = cms.double(1),
y = cms.double(0),
)... |
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
try:
url = "http://suninjuly.github.io/registration1.html"
browser = webdriver.Firefox()
browser.get(url)
# Filling out fields
first_name = browser.find_element_by_tag_name("input")
first_name.send_keys("Iv... |
"""
Your task is to create functionisDivideBy
(or is_divide_by) to check if an integer
number is divisible by each out of two arguments.
A few cases:
(-12, 2, -6) -> true
(-12, 2, -5) -> false
(45, 1, 6) -> false
(45, 5, 15) -> true
(4, 1, 4) -> true
(15, -5, 3) -> true
"""
def is... |
from myblog.models import BlogPost
from django.contrib import admin
class BlogAdmin(admin.ModelAdmin):
list_display=['title','timestamp','blog_type']
fieldsets=[
(None,{'fields':['title','timestamp','blog_type']}),
(None,{'fields':['body']}),
]
admin.site.register(BlogPost,BlogAdmin) |
import gdalnumeric
# name of our source image
src = "FalseColor.tif"
# load the source image into an array
arr = gdalnumeric.LoadFile(src)
print arr.flat
# swap bands 1 and 2 for a natural color image.
# We will use numpy "advanced slicing" to reorder the bands.
# Using the source image
# gdalnumeric.SaveArray(arr[[... |
#1, -3, 5, -6, -10, 13
res = 0
sum_sq = 0
while True:
n = int(input())
res += n
sum_sq += n ** 2
if res == 0:
break
print(sum_sq)
|
"""
Main entry point
"""
from pyramid.config import Configurator
def main(global_config, **settings):
"""Basic settings, including route prefix and database access"""
config = Configurator(settings=settings)
config.route_prefix = 'v1'
config.include('cornice')
config.include('builddb_rest.couch_... |
users = [{"name": "aptrinsic_id",
"type": "varchar(256)"},
{"name": "identify_id",
"type": "varchar(256)"},
{"name": "type",
"type": "varchar(256)"},
{"name": "gender",
"type": "varchar(256)"},
{"name": "email",
"type": "varchar(256)"... |
# -*- coding: utf-8 -*-
def IOU(Reframe,GTframe):
"""
计算两矩形 IOU,传入为均为矩形对角线,(x,y) 坐标。
"""
x1 = Reframe[0]
y1 = Reframe[1]
width1 = Reframe[2]-Reframe[0]
height1 = Reframe[3]-Reframe[1]
x2 = GTframe[0]
y2 = GTframe[1]
width2 = GTframe[2]-GTframe[0]
height2 = ... |
#Question 7
#Write a Python program to remove duplicates from a list.
my_list = ["a","list","of","duplicates","a",123,56,123,"of",123]
no_dup = []
for item in my_list:
if item not in no_dup:
no_dup.append(item)
print("List without duplicates", no_dup)
#Alternate
my_list = list(set(my_list))
print("List w... |
from django.conf.urls import url
from django.urls import path
from first_app import views
app_name = 'first_app'
urlpatterns=[
## calling a class based view
path('', views.IndexView.as_view(), name='index'),
path('add_musician/', views.AddMusician.as_view(), name='add_musician'),
path('musician_detail... |
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 14 22:14:12 2019
@author: Ananye
"""
import numpy as np
import random
import matplotlib.pyplot as plt
import pycuda.driver as cuda
import pycuda.autoinit
from pycuda import compiler, gpuarray, tools
import time
"""
###################################... |
from rest_framework import serializers
from users.models import User
from courses.models import Course, Membership, Assignment, Environment, CourseCreationRequest
class CourseMembersSerializer(serializers.ModelSerializer):
email = serializers.EmailField(source='user.email')
user_id = serializers.IntegerField... |
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404
from account.decorators import manager_required
from care_point.forms import ContractForm, WorksheetForm
from care_point.models import Contract, Caregiver
from care_point.view import caregiver
@... |
import json
import os
with open("stars.json") as g:
stars = json.load(g)
path =os.getcwd() + '/star_files/'
for i in range(len(stars)):
with open(path + 'star_'+ str(i) + '.json', 'w') as h:
json.dump(stars[i], h, indent=4)
|
# -*- coding:utf8 -*-
from MysqlHelper import MysqlHelper
sql='delete from users where id=9'
h=MysqlHelper('localhost',3306,'guanxi','root','Nmamtf@013')
res=h.cud(sql, [])
#res=h.cud(sql) # no
|
# coding=utf-8
import json
from collections import defaultdict
from elasticsearch import Elasticsearch
from elasticsearch.client import CatClient, IndicesClient, NodesClient
client = Elasticsearch('54.222.177.58:9200')
# client = Elasticsearch('54.223.226.77:9200')
cat_client = CatClient(client)
ind_client = IndicesC... |
# DESCRIPTION: This file implements an SVD-based kernel ridge regression model. For each user, the V matrix from SVD is fed to the ridge regression as features and the observed ratings as targets. The V matrix is normalized for each item. exp(2(xi.T*xj+1)) is used as the kernel.
# USAGE: To tarin the model, run "pytho... |
import sublime
def get_plugin_settings():
setting_name = 'sublime_jedi.sublime-settings'
plugin_settings = sublime.load_settings(setting_name)
return plugin_settings
def get_settings_param(view, param_name, default=None):
plugin_settings = get_plugin_settings()
project_settings = view.settings()... |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_iris
from base.model import *
class Agent(BaseSLModel):
def __init__(self, x_space, y_space, x_train, y_train, x_test, y_test, **options):
super(Agent, self).__init__(x_s... |
class Solution(object):
def numSplits(self, s):
"""
:type s: str
:rtype: int
"""
goodSplit = 0
left = [0] * 26
right = [0] * 26
for i in range(len(s)): # assign all char frequency in right
idx = ord(s[i]) - 97
right[idx] = righ... |
import os
from foodkm import config
from elasticsearch import Elasticsearch
from flask import Flask, jsonify, request
from flask_cors import CORS
import logging
from foodkm.geo_utils import get_latitude_longitude_google_api
app = Flask(__name__)
CORS(app)
es = Elasticsearch(
[os.environ['FOODKM_ES_HOST']],
... |
board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
def displayBoard(board):
print(" 1 2 3")
for x in range(0, 3):
print('{} {} | {} | {}'.format(chr(x+65), board[x][0], board[x][1], board[x][2]))
if x < 2:
print(' ____________')
def getRowCol():
while True:
... |
#import GPy
import GPyOpt
from numpy.random import seed
def myf(x):
return (2*x)**2
bounds = [{'name': 'var_1', 'type': 'continuous', 'domain': (-1,1)}]
max_iter = 15
myProblem = GPyOpt.methods.BayesianOptimization(myf,bounds)
myProblem.run_optimization(max_iter)
print (myProblem.x_opt)
print (myProblem.fx_opt... |
import zmq
import random
import sys
import time
import os
import json
from optparse import OptionParser
import base64
import time
import numpy as np
import matplotlib
import hashlib
import matplotlib.pyplot as plt
from jsonschema import validate, ValidationError
def leashsend(socket, mparts):
socket.send_multipa... |
from torchvision import models
import torch.nn as nn
import pretrainedmodels
from efficientnet_pytorch import EfficientNet
class models_select:
def __init__(self,class_num=2,pretrained=False):
self.class_num=class_num
self.pretrained=pretrained
def net(self,net):
if net=="ResNet50":
... |
import uuid
import os
from django.db import models
from django.core.validators import RegexValidator, FileExtensionValidator
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
def user_directory_path(instance, filename):
ext = filename.split('.')[-1]
filename = '{}.{}'... |
import pandas as pd
import numpy as np
import math
#it's in pip
import unidecode as uni
teams = pd.read_csv('fifa_team.csv', header=None)[2].drop_duplicates().dropna().to_numpy()
players = pd.read_csv('fifa_player.csv')['Club'].drop_duplicates().dropna().to_numpy()
# team team : player team
mapping = {}
for player_te... |
from mi.instrument.seabird.sbe54tps.driver import SBE54PlusInstrumentDriver
class InstrumentDriver(SBE54PlusInstrumentDriver):
"""
Specialization for this version of the 54 driver
"""
|
#introduction Class
# context
# class ClassName:
# def __init__(self):
# self.Attribute = 0
# def AnotherFunction(self):
# Action(s)
# Primera forma
class Team:
def __init__(self):
self.TeamName = "NaN"
self.TeamOrigin = "NaN"
def DefineTeamName(self,Name):
se... |
import numpy as np
a = [1,2,3,4,5,6]
print(type(a))
b = (np.array(a))
print(type(b))
print(a) # There are commas in list
print(b) |
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
# --------------------------------------------------------
Key = enum("JUMP", "GRAB", "CN", "CU", "CD", "CF", "CB", "VN", "VU", "VD", "VF", "VB")
# -----------------------------------... |
#!/usr/bin/env python
import time
import requests
from bs4 import BeautifulSoup
from entities import Route, Itinerary, Trajectory
from parsing import get_routes, get_itineraries, get_active_itinerary, \
get_company, get_price, get_info, \
get_coming_trajectory, get_going_trajectory
ROUTES_URL = 'http... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-12-08 14:48
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Creat... |
class Area:
sqmm, sqcm, sqdm, sqm, sqdam, sqhm, sqkm, sqM, sqyd, sqft, sqinch, ha, acre = [0] * 13
class AreaConverter:
def __init__(self):
self.area = Area()
self.area_conversion_value_table = {
'sqmm': 1, 'sqcm': 100, 'sqdm': 1000, 'sqm': 1e+6, 'sqdam... |
from django.shortcuts import render,redirect,get_object_or_404
from django.urls import reverse_lazy
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import ListVi... |
from __future__ import annotations
from typing import Optional
from jsonclasses import jsonclass, types
@jsonclass
class TransformName:
name: Optional[str] = types.str.transform(lambda s: s + 'q')
@jsonclass
class CTransformName:
name: Optional[str] = types.str.transform(lambda s, c: s + c.val)
|
from django.urls import path, include
from .import views
from rest_framework import routers
from ReservaBarberia.views import RegistrarBarbero, RegistrarCliente, reserva_delete, reserva_edit, reserva_list, reserva_view
from ReservaBarberia import views
routers = routers.DefaultRouter()
routers.register('ReservaBarber... |
# -*- coding: utf-8 -*-
"""
@author: Manuel
"""
import time
reading_waiting_time = 0
def read_data_from_sensor():
hour = '10:00' # Hour
temperature = '18.00' # Temperature
humidity = '75.00' # Humidity
time.sleep(reading_waiting_time)
return (hour, temperature, humidity)
|
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.status import (
HTTP_400_BAD_REQUEST,
HTTP_404_NOT_FOUND,
HTTP_200_OK
)
from django.contrib.auth import authenticate
from rest_framework.authtoken.models import Token
from django.views.decorators.csrf import... |
#傑卡德相似係數 Jaccard Similarity Coefficient
import numpy as np
import scipy.spatial.distance as dist
mat1 = [1,1,0,1,0,1,0,0,1]
mat2 = [0,1,1,0,0,0,1,1,1]
mat3 = [1,1,0,1,0,1,0,0,1] #the same as mat1
mat4 = [0,0,1,0,1,0,1,1,0] #invert of mat1
matV = np.mat([mat1,mat4])
print('dist.jaccard : ')
print(dist.pdist(matV, ... |
# coding: utf-8
# impares_1
# raquel ambrozio
for numeros in range(1, 101, 2):
if numeros % 3 == 0 or numeros % 5 == 0:
numeros = "*"
print numeros
|
# Generated by Django 2.2.4 on 2021-06-11 03:02
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Hotel',
... |
#! /usr/bin/python
# Copyright (c) 2010-2016 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
import os
import chess
import chess.engine
import chess.pgn
from Interface import interface
import chess.svg
import time
engine = chess.engine.SimpleEngine.popen_uci("/usr/games/stockfish")
cwd_addr = os.getcwd()
game_file = open(cwd_addr+"/Database/MagnusCarlsen/2017/3/6.pgn", 'r')
game = chess.pgn.read_game(game_fi... |
import unittest
from collections import Counter
# 97
def checkOneOff(shortWord, longWord):
lenShort, lenLong = 0, 0
oneOff = False
while lenShort < len(shortWord) and lenLong < len(longWord):
if shortWord[lenShort] != longWord[lenLong]:
if oneOff:
return False
... |
sentences = [
'Taki mamy klimat',
'Wszędzie dobrze ale w domu najlepiej',
'Wyskoczył jak Filip z konopii',
'Gdzie kucharek sześć tam nie ma co jeść',
'Nie ma to jak w domu',
'Konduktorze łaskawy zabierz nas do Warszawy',
'Jeżeli nie zjesz obiadu to nie dostaniesz deseru',
'Bez pracy nie... |
#!usr/bin/python3
import sys
import requests
import threading
import os
import tempfile
from urllib.request import urlretrieve
import bs4 as bs
from PIL import Image
from time import sleep
import re
def extract_values(pretty_soup):
list_args = pretty_soup.splitlines()
for i in range(0, 4):
list_args.... |
import os
import csv
from logger import *
# need to rewrite this to log some graphs into one graphs
# just say how to name them in graph = algorithm_list[]
# and give their csv path to csv_list[] ]
log_dir = './results/'
log_dir_dqn = './results/doudizhu_dqn_result'
log_dir_ddqn = './results/doudizhu_ddqn_result'
log_... |
# -*- coding: utf-8 -*-
# Copyright (c) 2014 Raphaël Barrois
# This software is distributed under the two-clause BSD license.
import logging
import json
from django.db import transaction
from django import http
from . import models
logger = logging.getLogger(__name__)
def log_exceptions(view):
"""Simple decor... |
import pytest
from ..models import Wishlist, WishlistItem
def test_remove_only_variant_also_removes_wishlist_item(customer_wishlist_item):
assert customer_wishlist_item.variants.count() == 1
variant = customer_wishlist_item.variants.first()
wishlist = customer_wishlist_item.wishlist
assert wishlist.i... |
"""
Distributed under the terms of the BSD 3-Clause License.
The full license is in the file LICENSE, distributed with this software.
Author: Jun Zhu <jun.zhu@xfel.eu>
Copyright (C) European X-Ray Free-Electron Laser Facility GmbH.
All rights reserved.
"""
from PyQt5.QtCore import Qt, pyqtSlot
from PyQt5.QtWidgets im... |
#!/usr/bin/py
# Head ends here
def lonelyinteger(b):
b = list(b)
for item in b:
if b.count(item) == 1:
return item
return None
# Tail starts here
if __name__ == '__main__':
a = int(input())
b = map(int, input().strip().split(" "))
print(lonelyinteger(b))
|
import subprocess
subprocess.call('python setup.py sdist')
subprocess.call('python setup.py sdist bdist_wheel upload')
|
def divide(a, b):
try:
result = a / b
return result
except (ZeroDivisionError):
return "Cannot divide by zero brother"
print(divide(1, 0)) |
import sys
import argparse
import numpy as np
import pandas as pd
import csv
import json
from numpy import percentile
from sequence_model.estimate_gru_ae import LSTMAutoEncoder
from sklearn.utils import shuffle
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from sklearn.metrics import f1_score, precis... |
from . import files
from . import error_logs
from . import runtime
modules = [files, error_logs, runtime]
|
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql
class JobsSpiderPipeline(object):
def __init__(self):
self.conn = pymysql.connect(host='192.168.33.... |
import cx_Oracle
connection = cx_Oracle.connect('xndb', 'L6vz5vFwcWur', '10.15.14.89:1521/xndev')
# pprint(connection)
apply_id = '30260'
cursor = connection.cursor()
cursor.execute(
"SELECT * FROM HOUSE_COMMON_LOAN_INFO WHERE APPLY_ID=" + apply_id
)
# cursor.execute(
# "UPDATE house_common_loan_info t... |
import re
import math
def check_float(text):
match = re.fullmatch(r'[-+]?(?:\d+(?:\.\d*)?|\.\d+)', text)
return bool(match)
def func(x):
return math.cos(x) - x
def autofill(filename):
file = open(filename, 'w')
for i in range(-10, 10, 1):
file.write(str(i/10) + " " + str(func(i/10)) + ... |
import paho.mqtt.client as mqtt
# get the localhost IP by using "hostname -I" in terminal
broker_ip = "10.128.0.3"
# 1883 is a default port that is unencrypted
broker_port = 1883
def imitation_bme():
bme_data = ""
return bme_data
if __name__ == '__main__':
client = mqtt.Client()
client.connect(broke... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
# Register your models here.
from .models import Registration
from .models import Student
from .models import Parent
from .models import Staff
from .models import Staff_Position... |
import numpy as np
import copy
cubes = list(input())
cubes = np.array(list(map(int, cubes)))
zeroNum = 0
oneNum = 0
for i in range(0, len(cubes)):
if cubes[i] == 0:
zeroNum += 1
else :
oneNum += 1
print(min(zeroNum, oneNum) * 2)
|
# Generated by Django 3.0.2 on 2020-04-17 02:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0038_auto_20200416_2145'),
]
operations = [
migrations.AddField(
model_name='statements',
name='Net_Prof... |
class Solution:
def romanToInt(self, s: str) -> int:
conv = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
nums = 0
for i in range(len(s)-1):
if conv[s[i]] < conv[s[i + 1]]:
nums -= conv[s[i]]
else:
nums += conv[s[i]]
nums... |
'''
File name: reconstructImg.py
Author:
Date created:
'''
import numpy as np
def reconstructImg(indexes, red, green, blue, targetImg):
# Enter Your Code Here
resultImg = targetImg
for j in range(0,targetImg.shape[0]):
for i in range(0,targetImg.shape[1]):
if indexes[j... |
# -*- coding: UTF-8 -*-
# The source code contained in this file is licensed under the MIT license.
# See LICENSE.txt in the main project directory, for more information.
# For the exact contribution history, see the git revision log.
import math
import re
import warnings
from libkne.controlrecord import ControlRecor... |
import scrapy
import json
import random
import re
import time
import os
import pymongo
from urllib import parse
AGENTS = [
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.75 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1... |
#!/usr/bin/env python
# coding: utf-8
import cgi
form = cgi.FieldStorage()
html_body = u"""
<html><head>
<meta http-equiv="content-type" content ="text/html;charset=utf-8">
</head>
<body>
%s
</body>
</html>"""
body_line = []
body = form.getvalue('body','N/A')
body = unicode(body,'utf-8','ignore')
for cnt in range(0,... |
# -*- coding: utf-8 -*-
import io
import os
from jinja2 import Environment, FileSystemLoader, select_autoescape
import html_checker
from html_checker.export.render import ExporterRenderer
from html_checker.export.jinja_filters import highlight_html_filter
class JinjaExport(ExporterRenderer):
"""
Exporter wi... |
import os
xml_version = "3.8"
results_path = "" # Location of analysed results
db_path = "" # Point to final location of Excel database
db_name = "" # Set to final name for Excel database
xsd = "" # Set to where on shared drives this will be
xml_location = "" # Set to base location on shared drives for sending xm... |
#!/usr/bin/python3
"""0-lookup.py
"""
def lookup(obj):
"""eturns the list of available attributes and methods of an objec
Args:
obj: Object
"""
return dir(obj)
|
import math
from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor
import requests
from bs4 import BeautifulSoup
import re
last_film = {}
imdb_links = {}
TOKEN = '633998206:AAG_wQi0DWwUJIGwrZmg-XOubPXu707Z3Dk'
bot = Bot(token=TOKEN)
dp = Dispatcher(bot)
def get... |
import boto3
import os
s3 = boto3.resource(
service_name='s3',
region_name='us-east-1',
aws_access_key_id=os.environ['AWS_ACCESS_KEY_ID'],
aws_secret_access_key=os.environ['AWS_SECRET_KEY_ID']
)
s3_resource = boto3.resource('s3')
bucket = s3.Bucket('pkxd-gsn')
for obj in bucket.objects.filter(Prefix='... |
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2020 James
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, co... |
import autocomplete_light
from django import forms
from apps.posto import models
class PostoCreateForm(autocomplete_light.ModelForm):
class Meta:
model = models.Posto
fields = '__all__'
class PostoUpdateForm(forms.ModelForm):
class Meta:
model = models.Posto
fields = '__all__'... |
from flask import Flask, request, redirect, render_template, session, flash, url_for
from mysqlconnection import MySQLConnector
import re
app = Flask(__name__)
mysql = MySQLConnector(app, 'email')
app.secret_key = 'dfkndf.cdfsd.sd.dsv.sdv.sd.d.ds.v.v.v.!!'
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[... |
import types
from graphene.types.field import Field
from graphene.types.unmountedtype import UnmountedType
from .hints import OptimizationHints
def field(field_type, *args, **kwargs):
if isinstance(field_type, UnmountedType):
field_type = Field.mounted(field_type)
optimization_hints = OptimizationHi... |
from . import utils
import torch
def tensor_shape(tsr, words=None):
if words is not None:
print(words)
print(utils.tensor_shape(tsr))
def count_tensor(tsr, words=None):
if words is not None:
print(words)
print(utils.count_tensor(tsr))
def peek_tensor(tsr):
assert isinstance(tsr, t... |
class Device:
def __init__(self, name, conected_by):
self.name = name
self.conected_by = conected_by
self.connected = True
def __str__(self):
return f"Device {self.name} ({self.conected_by})"
def disconnected(self):
self.connected = False
print("Disconnected... |
from django.db import models
from userprofile.models import Perfil
from reservas.models import ReservaArticulo
from reservas.models import ReservaEspacio
class PrestamoArticulo(models.Model):
reserva = models.ForeignKey(ReservaArticulo, on_delete=models.CASCADE)
administrador = models.ForeignKey(Perfil, on_del... |
from django.shortcuts import (
render,
redirect,
HttpResponseRedirect
)
from members.forms import (
RegistrationForm,
EditProfileForm,
)
from django.urls import reverse
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
def register(re... |
"""To run the following script, do the following
1) python
2) %run corrsin.py
"""
from __future__ import division
import numpy as np
pi = np.pi
from scipy.integrate import quadrature
from scipy.integrate import quad
from scipy.interpolate import splrep, splev
import matplotlib as mpl
mpl.rcParams['lines.linewidth'] = ... |
# -*- coding: utf-8 -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2021 Philippe Faist
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation t... |
from flask import Flask, render_template, request
from flask_debug import Debug
from sqlalchemy.orm import sessionmaker
import numpy as np
import pickle
import pandas as pd
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/analysis")
de... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 15 15:02:48 2019
@author: S80240
"""
import telemetroly
from tqdm import tqdm
import datetime
def last_day_of_month(any_day):
next_month = any_day.replace(day=28) + datetime.timedelta(days=4) # this will never fail
return next_month - datetime.tim... |
from sqlalchemy import Column, ForeignKey, Integer, String, Boolean, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import UniqueConstraint
Base = declarative_base()
class userSkillProgressPlan(Base):
__tablename__ = 'userSkillProgressPlan'
# here we'll define what skill... |
#!/usr/bin/env python
import sys
import os
curdir = os.path.dirname(os.path.realpath(__file__))
sdir = os.path.join(curdir,"../")
sys.path.append(sdir)
from multiprocessing import Pool
from fastqtools.fastqReader.fastqReader import fastqReader
from fastqtools.fastqReader.fastqWriter import fastqWriter
from fastqtools.... |
# coding:utf-8
import theano
import theano.tensor as T
import numpy as np
class Optimizer_SGD_my(object):
def __init__(self, lr=0.1, momentum=0.5, decay=0.01, nesterov=False):
super(Optimizer_SGD_my, self).__init__()
self.lr = theano.shared(lr)
self.momentum = theano.shared(momentum)
... |
from flask import jsonify
from app import create_app, socket_io
from app.config import Config
from Exceptions import NotFound, MethodNotAllowed, \
Forbiden, InternalServerError, ExistingResource,\
BadRequest, AuthError, UnAuthorized
config = Config()
app = create_app(config)
@app.errorhandler(NotFound)
@app... |
# 3.4.2 3層ニューラルネットワークの計算
# 2=>3=>2 のニューラルネットワーク
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
print('------1層目------------------------------------')
X = np.array([1.0, 0.5])
W1 = np.array( [[ 0.1, 0.3, 0.5 ], [ 0.2, 0.4, 0.6 ]] ) # 2,3format
B1 = np.array( [0.1, 0.2, 0.3] )
print( W1.shape ... |
# -*- coding: utf-8 -*-
'''
* @Author : bpf
* @Date : 2020-09-20 18:51:37
* @Description : 生成算式
* @LastEditTime : 2020-09-21 09:35:06
'''
import datetime
import os
from formula import OPT, GeneralFormular, ComputeFormular
def getInput():
'''
* 获取输入参数
'''
print("{:^1... |
# Receba um número inteiro na entrada e imprima Fizz se o número for divisível por 3. Caso contrário, imprima o mesmo número que foi dado na entrada.
n = int(input("Digite um número inteiro: "))
if n % 3 == 0:
print("Fizz")
else:
print(n) |
import scipy as sp
import numpy as np
from scipy.sparse import diags
from scipy.sparse.linalg import spsolve
from scipy.linalg import det, eigh, eigvalsh
import time
# python 3 imports
from suftware.src import utils
from suftware.src import supplements
from suftware.src import maxent
# Import error handling
from suft... |
import numpy as np
import pandas as pd
from viterbi import viterbi
def dishonest_casino():
# Stati nascosti e osservabili
S = np.array(["F", "L"])
SY = np.arange(1,7)
# Matrice transizione
M = pd.DataFrame([[0.95, 0.05], [0.1, 0.9]], columns = S, index = S)
# Matrice probabilita' di emissio... |
import requests
from PythonApi.jotihunt.Base import Response, NIEUWS, OPDRACHT, NIEUWSLIJST,\
HINTS, HINT, OPDRACHTEN, SCORELIJST, VOSSEN
_base_url = "http://www.jotihunt.net/api/1.0/"
def get_nieuws(nieuws_id):
url = _base_url + "nieuws/" + str(nieuws_id)
r = requests.get(url)
json = r.json()
r... |
import torch
from torch.utils.data import DataLoader, TensorDataset
from torch.autograd import Variable
from torch import optim
import torch.nn as nn
# 构建模型
class Sequential(nn.Module):
batch_size = 1
num_workers = 1
shuffle = True
layer_num = 0
def __init__(self):
super(Sequential, self).... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.