text stringlengths 38 1.54M |
|---|
"""
Tests for quaternion class
"""
# The MIT License (MIT)
#
# Copyright (c) 2016 GTRC.
#
# 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 th... |
'''
20. Valid Parentheses
Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty strin... |
# -*- coding: utf-8 -*-
import re
import datetime
from utils import fix_case, AELF_SITE
def postprocess_holly_saturday(version, mode, data):
text = """<p>
Le Samedi Saint est un jour spécial. C'est le jour de l'attente de la résurrection
du Christ. Il n'y a pas de messe ce jour là. Si vous cherchez la Vei... |
from PyQt4.Qt import *
from ui.scanning_complete_install_now import Ui_ScanningCompleteInstallNow
from widgets.constants import WizardPage
import logging
logger = logging.getLogger(__name__)
class ScanningCompleteInstallNowWidget(QWizardPage):
def __init__(self):
super(ScanningCompleteInstallNowWidget, self).__ini... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
# CODE 1: INITIAL PREPROCESSING WITH CSV FILES
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#import seaborn as sns
from scipy import signal
import os
#fold_name=['dws_1','dws_2','dws_11','ups_3','ups_4','ups_12'... |
"""
Pay to m of n direct
This puzzle program is like p2_delegated_puzzle except instead of one public key,
it includes N public keys, any M of which needs to sign the delegated puzzle.
"""
from src.types.blockchain_format.program import Program
from .load_clvm import load_clvm
MOD = load_clvm("p2_m_of_n_delegate_d... |
# Copyright 2020-2023 OpenDR European Project
#
# 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 agree... |
def fibonacci(n):
if n==0:
return 0
elif n==1:
return 1
else:
return fibonacci(n-1)+fibonacci(n-2)
def F():
a,b=0,1
yield a
yield b
while True:
a,b=b,a+b
yield b
def fibRange(start,end):
for cur in F():
if cur>end: return
if cur>=start: yield cur
n=10
for i in range(n):
... |
class Colors ():
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
@staticmethod
def getShade (intensity, color):
if intensity > 1 or intensity < 0:
print ("ERROR: COLOR INTENSITY OUT OF RANGE")
else:
return (color [0] * intensit... |
from Layer import Layer
from neurons.InnerNeuron import InnerNeuron
from neurons.InputNeuron import InputNeuron
from statistic_functions.Sigmoid import Sigmoid
class NeuralNetClassifier:
def __init__(self, input_space_dim, output_space_dim):
self.input_space_dim = input_space_dim
self.output_space_... |
# coding=utf-8
import turtle
import time
# 同时设置pencolor="red", fillcolor="yellow"
turtle.color("red", "yellow")
# 开始填充
turtle.begin_fill()
for _ in range(50): # 循环50次, 从0到49
turtle.forward(200) # 前行200
turtle.left(170) # 左转170°
# 结束填充
turtle.end_fill()
# 不会退出, 而是等待
turtle.mainloop() |
ryberg_path = "/data/users/kgruber/other-data"
results_path = "/data/users/kgruber/results"
data_path = "/data/users/kgruber/other-data" |
# 使用递归函数计算阶乘
import numpy
def factorial(n):
if n == 1:
return 1
else:
return n*factorial(n-1)
a = factorial(3)
print(a)
a = numpy.arange(0, 60, 10).reshape(-1, 1)+numpy.arange(6)
print(a)
|
import sys, time, json, io, os
from flask import Blueprint, Response, request, send_file
from flask_restful import Api, Resource
from app import config, logger
from app.api.file_watcher import FileWatcher
mod = Blueprint('api', __name__)
api = Api(mod)
# initialize file watcher to WATCH_FOLDER
file_watc... |
import json
class Channel:
def __init__(self, var, is_value):
if is_value:
self.value = var
else:
self.value = 0
self.pin = var
class Room:
def __init__(self, room, is_value):
if isinstance(room, basestring):
room = json.loads(room)
... |
# Class containing all the Enums and constants
from enum import Enum
# Constants
ICON_SIZE = 20
# In percentages
ICON_RIM_SIZE = 40
ICON_RADIUS = 25
ANIMATION_STEPS = 10
# Enums
class GeometryAnchor(Enum):
CENTER = 1
TOP_LEFT = 2
TOP_CENTER = 3
TOP_RIGHT = 4
RIGHT_CENTER = 5
LEFT_CENTER = 6... |
# Students should not edit this file, since changes here will _only_
# affect how your code runs locally. It will not change how your code
# executes in the cloud.
from ArchLab.Runner import LabSpec
import functools
import unittest
import subprocess
import parameterized
from gradescope_utils.autograder_utils.decorator... |
try:
from public_config import *
except ImportError:
pass
HOST = '0.0.0.0'
PORT = 9038
SERVICE_NAME = 'jobs'
SERVER_ENV = 'prod'
SQLALCHEMY_POOL_SIZE = 10
SQLALCHEMY_POOL_RECYCLE = 3600
JOBS = [
{ # 任务 信用积分每日检查, 每周一到每周五 早上 10:30 分运行
# 检查每个设备的借用日期是否超时 :发送提醒邮件,扣除信用分 1分
'id': 'credit-check... |
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator, RegexValidator
from django.db import models
from django.dispatch import receiver
from gemah_ripah.models import CharUpperCaseField
from merchants.models import Merchant
from products.models import Product
class Purchase... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-12-26 19:23
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('TOFI', '0028_auto_20161226_2122'),
]
operations = [
migrations.AddField(
... |
from conans import ConanFile
import os
class AdvancedVisualStudioGeneratorTestConan(ConanFile):
settings = 'os', 'compiler', 'build_type', 'arch'
generators = 'AdvancedVisualStudio'
def build(self):
pass
def test(self):
pass
|
from django.db import models
# make migration - creat changes and store in a file
# migrate - apply the pending changes created by make migrations
# Create your models here.
class Contact(models.Model):
name = models.CharField(max_length=50)
email = models.CharField(max_length=50)
phone = models.CharField(... |
X = [0 for i in range(10)]
for i in range(10):
x = int(input())
if (x <= 0):
x = 1
X[i] = x
for i in range(10):
print('X[{}] = {}'.format(i,X[i]))
|
"""
This module contains classes and methods related to invitations to new users
to be registered in Mangiato API
"""
from flask import request, g
from flask_restplus import Resource
from mangiato.api.restplus import API
from mangiato.constants import (API_VERSION, CODE_CONFLICT, RESPONSES_CATALOG,
... |
# Чтение из файла
inf = open('file.txt', 'r') # open('file.txt'), 'r' - параметр указывающий, что открываем для чтения
s1 = inf.readline() # readline - чтение 1-ой строки
s2 = inf.readline()
inf.close # закрытие файла
# Конструкция для чтения из файла, закрытие файла уже предусмотрено
with open('text.txt') as... |
#Authors: Dustin Matt & Dakota Fuller
#Date: 6/18/2012
'''This program takes a plain text message and xors it against a hex formatted string in a \x00\x11\x22 format'''
run= True
while run == True:
key = input("Input password or key: ")
crypt = input("Input xor encryption: ")
result =[]
asc_key=[]
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2018-03-01 02:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0011_auto_20180227_2353'),
]
operations = [
migrations.RemoveField(
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
#Bad Youtube Search - Python 3
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser
from gdata import *
from badgui import *
#from badsort import *
from YOURAPIKEY import APIKEY
import sys
im... |
# 推导式
def list_compre():
result = [i for i in range(30) if i % 2 == 0]
print(type(result))
print(result)
def dict_compre():
result = {v: k for k, v in {'a': 30, 'b': 40}.items()}
print(type(result))
print(result)
pass
def set_compre():
result = {x for x in range(50) if x % 5 == 0}
... |
#var
#cod: str
#preco, maiorpreco, mediapreco: float
mediapreco=0
maiorpreco=0
for i in range (1,16,1):
cod=input("Insira o código do produto: ")
preco=float(input("Insira o valor do produto: "))
mediapreco=mediapreco+preco
if preco>maiorpreco:
maiorpreco=preco
mediapreco=mediapreco/(i)
... |
"""
Created on Oct 20, 2013
@author: Ofra
"""
from action import Action
from actionLayer import ActionLayer
from util import Pair
from proposition import Proposition
from propositionLayer import PropositionLayer
from itertools import combinations
class PlanGraphLevel(object):
"""
A class for represe... |
point1 = 1, 2
print(type(point1))
point2 = 1,
print(type(point2))
point3 = point1 + point2
print(type(point3))
group = (1, 2) * 3
print(group)
my_list = [1, 2]
my_tuple = tuple([my_list])
triplet = (1, 2, 3)
x, y, z = triplet
if 2 in triplet:
print("exists")
|
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter
import pickle as pkl
import random
try:
import pydot #pour l'affichage graphique d'arbres
except ImportError:
print("Pydot non disponible pour l'affichage graphique, allez sur http://www.webgraphviz.com/ pour generer un apercu d... |
import bpy
from bpy import data as D
from bpy import context as C
from mathutils import *
from math import *
# bpy.ops.mesh.primitive_grid_add(
# x_subdivisions=10, y_subdivisions=10,
# radius=1, view_align=False, enter_editmode=False,
# location=(0, 0, 0), rotation=(0, 0, 0))
def new_grid(name='Grid',
... |
#!/usr/bin/env python
import dircache
import os
import re
import sys
from optparse import OptionParser
def number(new):
if options.num_len == 0:
return new
match = num_at_end.match(new)
if not match:
return new
parts = match.groups()
if len(parts[1]) == 0 and not options.renumber:
return ne... |
"""
Create, sign, and submit a transaction using Python Stellar SDK.
Assumes that you have the following items:
1. Secret key of a funded account to be the source account
2. Public key of an existing account as a recipient
These two keys can be created and funded by the friendbot at
https://www.stellar.org/lab... |
'''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
"""
Inside the `recursive_count_th` directory you'll find the `count_t... |
from Models.pydantic_models import User_Pydantic, UserIn_Pydantic, Token, TokenData
from Models.models import Users
from datetime import datetime, timedelta
from passlib.context import CryptContext
from typing import Optional, List
from jose import JWTError, jwt
from fastapi.security import OAuth2PasswordBearer, OAut... |
# Generated by Django 2.2.6 on 2019-11-25 08:37
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('work', '0041_auto_20191125_0813'),
]
operations = [
migrations.RenameModel(
old_name='Headline',
new_name='Resolution',
... |
import sys
from baseline_racer import BaselineRacer
from utils import to_airsim_vector, to_airsim_vectors
import airsimneurips as airsim
import argparse
import numpy as np
import time
import datetime
import math
import threading
import os
import random
import matplotlib
class BaselineRacerEnv(BaselineRacer):
def ... |
import collections, time, functools
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
class Arrow3D(FancyArrowPatch):
"""
Arrow used in the plotting of 3D vecotrs
ex.
a = Arrow3D([0, 1], [0, 1], [0, 1], mutation_scale=20,
lw=1, arrowstyle="-|>", color=... |
from flask import request
from flask_restful import Resource
from flask_restful import marshal, fields
from app import db
from sqlalchemy.sql.expression import func
from models.games_model import Games
price_fields = {
'date':fields.DateTime,
'price':fields.Integer
}
games_fields = {
'permalink': fields... |
from django import forms
from core.models import Slider
from stack.models import Team, Event
from users.models import User
class TeamCreationForm(forms.ModelForm):
class Meta:
model = Team
fields = ('name',)
error_messages = {
'name': {
'required': "Please ente... |
'''Dime un numero al azar del 1 al 10 y lo adivino'''
def adivino ():
numero = input("Dime un numero del 1 al 10: ")
guess = input("Que numero crees que es?")
while guess!=numero:
if guess>numero:
print("Demasiado Alto")
if guess<numero:
print("Demasiado bajo"... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_protect
from django.contrib.sessions.models import Session
from datetime import datetime
impo... |
# Copyright 2015 Jason Owen <jason.a.owen@gmail.com>
#
# This file is part of matrix-chain-multiplication.
#
# matrix-chain-multiplication is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of th... |
# This code is used for classifying images.
# classes: floorplan, inDoor, outDoor, else
# usage:
# 1. in python evironment
# import RECG_CNN2_InOutDoor_refine2 as recg
# train: recg.train(continueTrain=False, startEpoch=1, nEpoch=epochs)
# test: recg.test(modelPath)
# testFile: recg.testFile(... |
from collections import namedtuple
import pytest
class FakeClient:
def __init__(self, **kwargs):
self.messages = self.MessageFactory()
class MessageFactory:
@staticmethod
def create(**kwargs):
Message = namedtuple("Message", ["sid"])
message = Message(sid="SM8... |
# multi-label for 1 instance
# problem transformation: (1) increase classes (2) one binary classifier for each class
# performance metrics
import numpy as np
from sklearn.metrics import hamming_loss, jaccard_similarity_score
predicted = np.array([[0, 1], [1, 1]])
true = np.array([[0, 1], [1, 1]])
print('haming_loss = ... |
#! /usr/bin/env python
#code will generate random configurations of two ORCA optimized molecules, calculate single point energies of them, dump the structures in the structure input directory for orca geometry optimizations
import subprocess
import readline
import numpy as np
from re import sub
import shutil
import ti... |
import codecs
import json
import os
from collections import Counter
from os import path
from pathlib import Path
from pprint import pprint
import arabic_reshaper
import numpy as np
from bidi.algorithm import get_display
from hazm import *
from PIL import Image
from tqdm import tqdm
from wordcloud import WordCloud
# g... |
import random
from django.contrib.admin.utils import flatten
from django.core.management import BaseCommand
from rooms.models import Amenity
from django_seed import Seed
from rooms.models import Room, RoomType, Photo, Amenity, Facility, HouseRule
from users.models import User
class Command(BaseCommand):
help = "... |
import cv2
import numpy as np
cam = cv2.VideoCapture(0)
while True:
ret, frame = cam.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, np.array([0, 0, 0]), np.array([180, 255, 46]))
circles = cv2.HoughCircles(mask, method=cv2.HOUGH_GRADIENT, dp=1, minDist=200, param1=100, ... |
from __future__ import print_function
import tensorflow as tf
from tensorflow.contrib import rnn
import numpy as np
import os
import matplotlib.pyplot as plt
def import_mnist(limit=10000):
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
... |
PLAYER_MOVES = "*"
RABBIT_HOLE = "R"
TEA_BAGS_TO_COLLECT = 10
def get_field(row_count):
matrix = []
for row in range(row_count):
row = input().split()
matrix.append(row)
return matrix
def get_alice_position(matrix):
matrix_size = len(matrix)
for r in range(matrix_size):
f... |
import cv2
import fnmatch
import itertools
import csv
from glob import glob
import multiprocessing
import random
import sys
import traceback
import matplotlib.pyplot as plt
import numpy as np
from scipy.fftpack import rfft
def accumulate(acc, row):
for i, j in enumerate(row):
acc[i] += float(j)
retur... |
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
img=cv.imshow('/home/ai31/Desktop/common/ML/Day12/faces.jpg')
img1=cv.imshow('dst',img)
cv.waitKey(0)
|
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import numpy as np
import os
import importlib
import random
from helper.data_processing import *
from my_model import evaluate_classifier
from tqdm import tqdm
import gzip
import pickle
import shutil
LABEL_MAP = {'... |
def sum_to(n):
soma = 0
for i in range (1,n+1):
soma = soma + i
return soma
print(sum_to(10)) |
#!/usr/bin/env python3
import json
from foundation.logger import Logger
from distribution.service import buildingservice, routeservice, hiveservice, distributionservice
logger = Logger(__name__)
def update_demand(message):
decoded_message = message.decode("utf-8")
loaded_message = json.loads(decoded_message)
logge... |
from django.contrib.auth.models import User, Group
from django.shortcuts import render, redirect
from django.http import HttpResponse
def allow_users(authorized_users=[]):
def decorator(view_func):
def wrapper_func(request, *args, **kwargs):
if request.user.groups.exists:
gro... |
import numpy as np
import chess
import chess.pgn
import random
import itertools
import pickle
pieces = {
'p': 1,
'P': -1,
'n': 2,
'N': -2,
'b': 3,
'B': -3,
'r': 4,
'R': -4,
'q': 5,
'Q': -5,
'k': 6,
'K': -6
}
def shortenString(s):
s = s[:s.rfind(" ")]
return s;
def beautifyFEN(f):
for i in range(4):
... |
import numpy as np
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go
import utils.AlphaVantageUtils as av
import utils.PostgresUtils as pg
import utils.ModelUtils as mdl
name = pg.get_symbol_name(av._TIC_MICROSOFT)
df_prices = pg.get_prices(av._TIC_... |
#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-
from collections import namedtuple
from ..system.check import check
from bes.version.semantic_version import semantic_version
from bes.property.cached_property import cached_property
from .python_error import python_error
cla... |
import OpenSSL
from hfbssisdk.src.hfbssi.didFromPK import didFromPK
from hfbssisdk.src.hfbssi.getEntity import requestGetEntity
from hfbssisdk.src.hfbssi.getEntity import payloadToGetEntity
def channelVerificationClient(cert, keyfile, did_wallet_path):
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE... |
#Creator: Aaron Oatley
#Date: 2020.06.29
#Assignment 9-1
#set environment and import packages
import matplotlib.pyplot as plt
import pandas as pd
#load data and create data frame
dict_sal = {'Year':['2002', '2002', '2003', '2003', '2004', '2004', '2005', '2005'],
'Name':['Tom', 'Joe',... |
from .base.model_DF import Encoder, Decoder
import torch
import torch.nn as nn
from pathlib import Path
import os
class PredicterBase(object):
def __init__(self, input_size=(256, 256), output_size=(256, 256),
model_parameters_name="Basic_Autoencoder.tar", device="cpu"):
super().__init__(... |
import sys
N, M = map(int, sys.stdin.readline().split())
check = [False for i in range(N+1)]
result = [0 for i in range(M)]
def backtracking(index, n, m):
if index == m:
print(*result, sep=' ')
return
for i in range(1, n+1):
if check[i] == False:
check[i] = True
... |
# coding: utf-8
# ## Predicting Boston Housing Prices
#
#
# **Project Description**
#
#
# You want to be the best real estate agent out there. In order to compete with other agents in your area, you decide to use machine learning. You are going to use various statistical analysis tools to build the best model to ... |
import numpy as np
from cleverhans.attacks import FastGradientMethod
from tools.cleverhans.adversarial_attack import AdversarialAttack
class FGMAttack(AdversarialAttack):
def __init__(self, model, targeted=False, step_size=0.3, norm_order=np.inf, clip_min=None, clip_max=None,
sanity_checks=True)... |
Number = raw_input("Please enter the number.")
Number = int(Number)
x = 1
while x < 11:
print Number * x
x = x + 1 |
from abc import ABCMeta, abstractmethod
from enum import Enum, IntEnum
from .Commands.CommandManager import CEditorCommandManager
from .ToolBar.ToolBarService import CToolBarService
from ..QToolWindowManager.IEditorClassFactory import CClassFactory
class EEditorNotifyEvent ( Enum ):
Notify_OnInit = 'OnInit'
Notify... |
# import indicoio
# indicoio.config.api_key = 'd58464ed4f71c725f4d0b4ed0a1ac04c'
# from sentiments.models import Post
# def indicoioInit():
# print("\nInitializing Sentiment Analysis")
# allentries = Post.objects.all()
# print(allentries[0])
# count = 0
# for one_entry in allentries:
# one_entry.value = i... |
class Solution:
def validTicTacToe(self, board: List[str]) -> bool:
X = O = n_win = 0
def check_win_by_row(board, player):
for row in board:
if ''.join(row) == player*3:
return True
return False
def check_win_by_diagonal(board, play... |
from collections import Counter
class Solution:
def numTilePossibilities(self, tiles):
if not tiles or len(tiles) == 0:
return 0
words = {c for c in tiles}
for l in range(2, len(tiles)+1):
new_words = []
for word in words:
if len(word) ==... |
def solution(N, P, Q):
prime_table = [False]*2+[True]*(N-1)
prime = []
semi_prime = [0]*(N+1)
result = []
idx = 2
while idx**2 <= N:
i = 2
while idx * i <= N:
prime_table[idx*i] = False
i += 1
idx += 1
for idx in range(len(p... |
import re
def find_bags_containing(to_find, lines):
containers = set()
for line in lines:
if to_find in line and not line.startswith(to_find):
found = line.split("bags")[0][:-1]
containers |= {found} | find_bags_containing(found, lines)
return containers
def f... |
n1 = int(input('Digite um número: '))
if n1 % 3 == 0 and n1 % 5 == 0:
print('FizzBuzz')
else:
print(n1) |
import math
def my_f(x):
return 4.0 / (1 + x ** 2)
soma = 0
n = 100000000
m = 1.0/n
j=0
for i in range(n):
j += m
soma += my_f(j)
soma *= m
print(soma) |
# ----------------- State Codes ----------------
# 0 - not found
# 1 - X centered
# 2 - Y centered
# 3 - move left
# 4 - move right
# 5 - move up
# 6 - move down
# 7 - target lost
import random
import skynet
import messageboard
arm = skynet.robotArm()
arm.ready()
mb = messageboard.MessageBoard('arm')
baseRot = 20
r... |
import numpy as np
def nonlin(x, deriv=False):
if deriv:
return x * (1 - x)
return 1/(1 + np.exp(-x))
# The training features
X = np.array([ [0, 1, 0],
[1, 1, 0],
[1, 0, 1],
[0, 1, 1],
[1, 0, 0],
[0, 0, 0],
[1, 1, 1] ])
# The labels
y = np.array([[0, 0, 1, 1, 1, 0, 0]]).T
bias = np.one... |
from .load_autograd import (container_mateclass,nondiff_methods,diff_methods,
Container_,Container,numpy,container, VJPNode, _np,
defjvp,defvjp,vspace, primitive, is_container, no_grad,
using_config, test_mode,to_container
)
|
from bs4 import BeautifulSoup
from protodefs.ranks import t10ranks
from startup.login import enICEObject, jpICEObject
from datetime import datetime
from pytz import timezone
import discord, asyncio, time
def parseHTML(driver):
html = driver.page_source
soup = BeautifulSoup(html)
parsedHTML = soup.find_all(... |
class Solution:
def generateParenthesis(self, n: int):
remaining = n-1
stack = 1
total_list = []
list = ['(',]
def auxiliary_func(remaining, stack, is_push, list):
list = list.copy()
if is_push:
list.append('(')
... |
from gpiozero import OutputDevice
import time
import threading
class DrinkMachine:
def __init__(self, pump_one_pin, pump_two_pin, flow_rate):
self.__pump_one = OutputDevice(pump_one_pin)
self.__pump_two = OutputDevice(pump_two_pin)
self.__flow_rate = flow_rate
self.__current_drink ... |
import random
from django.test import TestCase
from .models import User, Company
class UserModelTests(TestCase):
def setUp(self):
self.users = [
{
"username": "batman",
"first_name": "Bruce",
"last_name": "Wayne",
"email": "the... |
# _*_coding:utf-8_*_
"""
单隐层BP神经网络,激活函数都采用sigmoid;模型中的参数名称参照西瓜书BP
Author: Lingren Kong
Created Time: 2020/6/4 21:33
"""
import numpy as np
class BP():
def __init__(self, hidden, fit='standard', randomState = 0, tol = 1e-6, maxiter=200,eta=0.1):
"""
Parameters
----------
hidden : 隐藏... |
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 13 17:03:44 2018
@author: Admin
"""
if (5>6):
print("yes")
#eilf():
#eilf():
else:
print("NO")
# and or ! used for logical operator
x=None
bool(x)
n=0
while (n<10):
print(n)
n=n+1
#List
empty_list=[1,2,3,4,5,2.3,"hi"]
#em... |
from app import db, bcrypt
import app
class ApplicationForm(db.Model):
__tablename__ = 'application_form'
id = db.Column(db.Integer(), primary_key=True)
event_id = db.Column(db.Integer(), db.ForeignKey('event.id'), nullable=False)
is_open = db.Column(db.Boolean(), nullable=False)
event = db.rela... |
import util.browser_data_transform as bro
import util.constant as constant
import datetime
def get_browser_action(data):
res = []
for item in data:
if constant.OperatorType.id_to_category(item[constant.OperatorType.NAME]) == 'browser':
if item['type'] == 'url' and item['url'] == 'chrome://n... |
#RetroPiCam - A Gif tweeting camera for a Box Brownie by Oliver Quinlan
#setup libraries
from gpiozero import LED, Button, Buzzer
from time import sleep
from picamera import PiCamera
from datetime import datetime
import os
#variables
length = 8
resolution = "640, 480"
#Twython setup
### You will need to setup a twi... |
# -*- coding: ascii -*-
import sys, os
parent_path = os.path.split(os.path.abspath("."))[0]
if parent_path not in sys.path:
sys.path.insert(0, parent_path)
from pyspec import *
from pyspec.embedded import *
from pyspec.embedded.dbc import *
class Weight(DbCobject):
convert_table = {"kg":1.0, "kan":3.75, "pou... |
"""
Keyring Chainer - iterates over other viable backends to
discover passwords in each.
"""
from .. import backend
from .._compat import properties
from . import fail
class ChainerBackend(backend.KeyringBackend):
"""
>>> ChainerBackend()
<keyring.backends.chainer.ChainerBackend object at ...>
"""
... |
from inc import inc, incrementer
import unittest
class IncTest(unittest.TestCase):
def test_controller(self):
i = inc([1, 2, 3])
self.assertEqual(i.controller(), [1, 2, 4])
i = inc([1, 2, 0])
self.assertEqual(i.controller(), [1, 2, 1])
i = inc([1, 9, 9])
self.assertE... |
from flask import flash
from flask_babel import gettext
def write_errors_to_flash(form):
for field, errors in form.errors.items():
for error in errors:
flash(gettext('Error in the %(field_name) field - %(error)',
field_name=getattr(form, field).label.text,
... |
from django.shortcuts import render
from django.views.generic import ListView, View
from main_news.models import NewsPost
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse, JsonRespons... |
import collections
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPen
from PyQt5.QtWidgets import QApplication, QGraphicsView
ZOOM_FACTOR = 0.1
class CustomGraphicsView(QGraphicsView):
def __init__(self, parent):
super().__init__(parent)
self.pen = QPen(Qt.green, 3, join=Qt.MiterJoin)
... |
import sys
STDERR = sys.stderr
STDOUT = sys.stdout
account_email = "emailbox@hostname"
account_password = "************"
def gold_repr(value):
rep = ""
is_negative = (value < 0)
try:
positive_value = abs(int(value))
except:
return "Non gold value ("+str(value)+")"
copper = positi... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
## this program is an imitation of the game of war app in the app store
## Author: Tim Tripp
## Date: 6/16/2016
## imports
import time
import random
## Global lists
def givenspace():
for i in range(3):
print('\n')
healthlv = []
healthcostf = []
healthcostf.append(20000)
healthcosts = []
healthcosts.append(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.