text stringlengths 38 1.54M |
|---|
import flow_api
def handler(system: flow_api.System, this: flow_api.Execution):
# create a secret
this.connect(
connector_type='VAULT',
host='https://my-vault-host:port',
secret_path='my-secret',
data={
'secret-key': 'secret-value',
},
token='my-vault... |
# -*- coding: utf-8 -*-
from ua_parser import user_agent_parser
PLATFORM_WORDS = ['X11',
'Macintosh',
'Windows',
'compatible',
'Android',
'BlackBerry',
'Windows Phone',
'iPhone',
... |
import math
def c(n):
if n == 0:
return 1
else:
return (4*(n-1)+2)*c(n-1)/(n+1)
b = 0
while c(b)<1000000000:
print c(b)
b+=1
|
#!/usr/bin/python3.6
"""Defines commands used for the Memers server."""
import json
import random
import asyncio
import discord
from discord.ext import commands
import config
MAX_VOTES = 10
def check_votes(user):
"""Checks if a user is banned from submitting."""
with open(f"./resources/votes.json", "r+") as v... |
import sympy as sp
def homotopia(F, x0, N, tol):
var = list(F.free_symbols)
n = len(var)
H = 1./N
JF = F.jacobian(var)
print('JF(x): ')
print(JF, end="\n\n")
JFi = JF.inv()
print('[JF(x)]^{-1}: ')
print(JFi, end="\n\n")
h = ('i',) + tuple('x_%i^{(i)}'%(i+1) for i ... |
from unittest import TestCase
from numpy import isscalar
from loguniform import LogUniform as dist
class test_constructor(TestCase):
def test1(self):
with self.assertRaises(TypeError):
dist(a=1)
with self.assertRaises(TypeError):
dist(b=1000)
def test2(self):
... |
import time
from selenium import webdriver
import os
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.common.keys import Keys
def xpath(add):
try:
time.sleep(5)
element = driver.find_element_by_xpath... |
from sklearn import datasets
import numpy as np
def create_linearly_separable_two_class():
"""
Generates a linearly separable dataset, with classes 0 or 1.
Note that the dataset is not generated randomly.
Returns
--------
X : array-like, shape [n_samples,n_features]
All a... |
import hashlib
# Function to generate hash value of files
def getHashFromName(fileName):
md5hash = hashlib.sha256()
with open(fileName, "rb") as f:
md5hash.update(f.read())
return md5hash.hexdigest()
# Function to generate hash value of files
def getHashFromData(fileData):
m... |
nums = [-4,-1,0,3,10]
for i in range(len(nums)):
nums[i] = nums[i]*nums[i]
nums.sort()
print(nums) |
from rest_framework import serializers
from rest_framework.fields import CurrentUserDefault
from datetime import datetime
from wishlist.models import Wishlist, WishlistItem
from product.serializers.product import ProductListSerializer
class WishlistItemSerializer(serializers.ModelSerializer):
product = ProductLi... |
import pdb
from models.artist import Artist
from models.album import Album
import repositories.artist_repository as artist_repository
import repositories.album_repository as album_repository
artist_repository.delete_all()
album_repository.delete_all()
artist_1 = Artist("Artist 1")
artist_repository.save(artist_1)
ar... |
# Generated by Django 3.2.4 on 2021-06-18 18:35
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pros', '0023_alter_acceptoffer_meeting_time'),
]
operations = [
migrations.AddField(
model_name='acceptoffer',
... |
# coding=utf-8
# @author: zwa❤lqp
# @time: 2021/2/27 17:47
import os,re
# a = 0
# b = 1
# n = 10
#
# for i in range(n):
# a,b = b,a+b
# print(a)
# def fib_yield_while(max):
# a, b = 0, 1
# while max > 0:
# a, b = b, a + b
# max -= 1
# yield a
#
#
# def fib_yield_for(n):
# a, b = ... |
# (применяем функцию .get() из библиотеки requests)
import requests
r = requests.get(
'https://baconipsum.com/api/?type=all-meat¶s=3&start-with-lorem=1&format=html') # делаем запрос на сервер по переданному адресу
print(r.content)
print(r.status_code) # узнаем статус полученного ответа
# Получить ответ в фо... |
from django.db import models
import datetime
from django.utils import timezone
class Season(models.Model):
start_date=models.DateTimeField('Season start date')
end_date=models.DateTimeField('Season end date')
name=models.CharField(max_length=200)
last_modified=models.DateTimeField(default=timez... |
from random import choice, random
import os
current_version = 11
run_path = os.environ["HOME"]+'/mat'+str(current_version)
#match run_path name to main...
if not os.path.exists(run_path):
#mkmatdir = 'mkdir '+ matpath
os.popen('mkdir ' + run_path, 'w', 1)
test = open(os.path.join(os.path.abspath(mat_path), 'testfi... |
import torch
import config
import utils
import pandas as pd
import os
import numpy as np
from torch.hub import load_state_dict_from_url
import cv2
from os.path import join as pjoin
if __name__ == '__main__':
cfg=config.ConfigTest()
print("Device: ", cfg.DEVICE)
device = torch.device(cfg.DEVICE)
print("... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 12 13:10:00 2018
@author: rick
Script for finding start and end times of camera review sections from YouTube
phone review videos.
Requires:
transcripts to be loaded in local MySQL database by "yt_data.py"
topics to be identified using "find... |
from django.conf.urls import include
from django.conf.urls import url
mock_patterns = []
included_patterns = []
urlpatterns = [
url('^mock/', include(mock_patterns, namespace='mock')),
url('^included/', include(included_patterns))
]
|
import math
import sys
for inputvalue in sys.stdin.readlines():
result = []
# minvalue, maxvalue = input().split(' ')
minvalue, maxvalue = map(int, inputvalue.strip().split())
for i in range(minvalue, maxvalue+1):
value = i
valuelist = []
while i != 0:
valuelist.app... |
balance = 999999
annualInterestRate = 0.18
b = balance
epsilon = 0.01
lb = balance/12.0
ub = balance * (1 + annualInterestRate/12.0) ** 12 / 12.0
mp = (lb+ub)/2.0
def monthlyPay(b, mp):
for month in range(1,13):
b = b - mp
b = b + annualInterestRate/12.0*b
return b
cnt = 0
while True:
cn... |
a, b = map(int, input().split())
if a != b:
if a > b:
a, b = b, a #값 교환
print(b-a-1)
print(*range(a+1, b))
else:
print(0) |
# -*- encoding: utf-8 -*-
from app_settings import *
from app_languages import *
from app_files import *
from app_choices import *
from app_nomenclature_tags import *
|
player = " "
def playIntro(player):
print ("Holly: Welcome to the Total Immersion Video Game Red Dwarf. Who would you like to play as? (Type the character name below)")
print ("Lister - Human")
print ("Rimmer - Hologram")
print ("Kryten - Android")
print ("Cat - Cat")... |
from flask import Flask
from .hejnote.routes import hejnote_routes
app = Flask(__name__)
hejnote_routes(app)
if __name__ == '__main__':
app.run() |
# -*- coding: utf-8 -*-
import wave
import struct
import glob
from scipy import fromstring, int16
import numpy as np
from mylibs import fourier, combine, constants as con
import re
def get_dataset(filename, samples, span, offset=0):
wavfile = filename
wr = wave.open(wavfile, "rb")
origin = wr.readframes(wr... |
import sys
digit_string = sys.argv[1]
res = 0
for letter in digit_string:
res += int(letter)
print(res) |
import machine
from machine import Pin, Timer, I2C
from micropython import const
import time
MC3216_Mode = const(0x07)
MC3216_Opstat = const(0x04)
MC3216_Outcfg = const(0x20)
MC3216_XOut = const(0x0D)
MC3216_YOut = const(0x0F)
MC3216_ZOut = const(0x11)
MC3216_SRTFR = const(0x08)
SlaveAddress = const(0x4C)
class MC321... |
from django.db import models
# Create your models here.
class Rate(models.Model):#=======================
rate_value = models.IntegerField(range(0,5) , blank = True , null = True )
def __str__(self):
return (f' {self.rate_value} ')
class Actor(models.Model):
actor_name = models.CharField(max_lengt... |
from ocp_resources.mtv import MTV
from ocp_resources.resource import NamespacedResource
class NetworkMap(NamespacedResource, MTV):
"""
Migration Toolkit For Virtualization (MTV) NetworkMap object.
Args:
source_provider_name (str): MTV Source Provider CR name.
source_provider_namespace (st... |
try:
import os, logging, sys, glob, webbrowser, time
from collections import Iterable # used in the flatten function
from bisect import bisect_left
except:
print("ImportERROR: Missing fundamental packages (required: bisect, collections, os, sys, glob, logging, time, webbrowser).")
try:
imp... |
from typing import List
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
def reverse(nums: List[int], start: int):
end = len(nums) - 1
while start < end:
nums[sta... |
import unittest
import hello
import index
class TestHandlerCase(unittest.TestCase):
def test_response(self):
print("testing response.")
result = index.handler(None, None)
print(result)
self.assertEqual(result['statusCode'], 200)
self.assertEqual(result['headers']['Content-... |
# Generated by Django 2.1.15 on 2020-04-02 13:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('crawl_elect', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='candidate',
name='candi_cnt',
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 21 15:35:11 2020
@author: prenaudin, elvinagovendasamy
"""
#Packages
from mrjob.job import MRJob
from mrjob.step import MRStep
import numpy as np
class PageRank(MRJob):
#cf version 1
total_nodes = 0
dico_nj = {}
dico_pageran... |
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, User
from home.models import Producto
# Create your models here.
class ManejadorDeClientes(BaseUserManager):
def create_user(self, email, password=None, p_natural_rut=None, tipo=None):
if not email:
... |
"""
Add two new attributes to the parent class: weight and height.
Add change_weight, change_height methods that take one parameter and add it to the corresponding argument.
If the parameter was not passed, increase by 0.2. Modify the fly method of the Parrot class.
If the weight is more than 0.1, display the messa... |
from app.util.dao import MysqlDao
class BotUser:
def __init__(self, qq, point=0, active=0, admin=0):
self.qq = qq
self.point = point
self.active = active
self.admin = admin
self.user_register()
def user_register(self):
"""注册用户"""
with MysqlDao() as db:
... |
from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy import log, signals
from newscollect.spiders.cnn_spider import CNNSpider
from newscollect.spiders.guardian_spider import GuardianSpider
from scrapy.utils.project import get_project_settings
spiders = [GuardianSpider(), CNNSpider()]
spi... |
# Module for complex numbers
class Complex:
''' Creates a complex number. The first parameter is the real component, the second
parameter is the imaginary component.'''
def __init__(self, r, i):
self.r = r
self.i = i
''' Calling print() will display the complex number in the form... |
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
from numpy import nan as NA
import matplotlib.pyplot as plt
import re
import mglearn
import sklearn
import os
os.chdir("../pjt_data")
apart = pd.read_csv("apart5.csv", index_col=0)
## 변수합치기
import seaborn as sns
# 상관관계 조사
corr_matrix... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sortedListToBST(... |
def check_conda_env(expected_env: str):
"""Checks that the expected conda environment is the same as the current
conda environment
Args:
expected_env (str): What the conda env should be for this python
script.
"""
import subprocess
import warnings
import json
comman... |
# coding: utf8
from django.core.management.base import BaseCommand
from core.models import DoskaField, Map
from utils.importer import parser_import
import settings
import urllib2
import json
class Command(BaseCommand):
def handle(self, *args, **options):
for enabled_parser in settings.PARSERS_ENABLED:
... |
#!/usr/bin/env python
# encoding: utf-8
import time
import functools
def timeit(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.clock()
func(args)
end = time.clock()
print 'used:', end - start
return wrapper
class Tester(object):
def __init__(s... |
import os
import pickle
import numpy as np
import pandas as pd
from sklearn import datasets
from django.conf import settings
from rest_framework import views
from rest_framework import status
from rest_framework.response import Response
from sklearn.ensemble import RandomForestClassifier
from scipy.fftpack import rfft
... |
from math import gcd,ceil
reactions = [x.replace('\n','') for x in open('Day14/input.txt').readlines()]
reactions = [[y.strip() for y in x.split('=>')] for x in reactions]
reactions = [(x[0].split(', '), x[1].split(' ')) for x in reactions]
reactions = [([(int(y.split(' ')[0]), y.split(' ')[1].strip()) for y in x[0]], ... |
def solution(array):
new_array = []
for i in range(len(array)):
for j in range(i + 1, len(array)):
for k in range(j + 1, len(array)):
new_array.append(array[i] * array[j] * array[k])
return max(new_array)
print(solution([-3, 1, 2, -2, 5, 6]))
|
from kivy.properties import StringProperty
from kivy.uix.screenmanager import Screen
class ManagerScreen(Screen):
txt_cheese_pizza_price = StringProperty("0")
txt_hawaiian_pizza_price = StringProperty("0")
txt_pepperoni_pizza_price = StringProperty("0")
def welcome(self):
self.manager.cur... |
import mysql.connector as sql
# deze waarden aanpassen
vijf_letter_code = "svbiw"
pwd = "luvinformatica"
HOST_DEFAULT = "hannl-hlo-bioinformatica-mysqlsrv.mysql.database.azure.com"
USER_DEFAULT = vijf_letter_code + "@hannl-hlo-bioinformatica-mysqlsrv"
DATABASE_DEFAULT = vijf_letter_code
sql.connect(host=HOST_DEFAU... |
from PyQt5 import QtCore, QtGui, QtWidgets
import requests, json
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(456, 341)
self.api_key = "8f23a1347177d649fd3afc4d97f09bb1"
self.base_url = "http://api.openweatherm... |
from load_data import *
import numpy as np
# locations = load_WarehouseLocations()
# distances = load_WarehouseRoutes(True)
# durations = load_WarehouseRoutes(False)
# print(locations['Distribution South'][0])
# print(durations['Distribution South']['Distribution North'])
# print(len(durations))
# print('f'... |
import unittest
import logging
from lxml import etree as etree_
import sdc11073
from sdc11073 import namespaces
from sdc11073 import definitions_sdc
#pylint: disable=protected-access
DEV_ADDRESS = '169.254.0.200:10000'
CLIENT_VALIDATE = True
# data that is used in report
observationTime_ms = 14675963591... |
# coding:utf-8
from django.shortcuts import render
import os
import time
from connect import adb
from django import forms
from django. shortcuts import render_to_response
from django. shortcuts import render
from django.http import request
from django.http import HttpResponse
from django.http import HttpResponseRedire... |
from django.db import models
from django.utils import timezone
class LinePush(models.Model):
"""Lineでのプッシュ先を表す"""
user_id = models.CharField('ユーザーID', max_length=100, unique=True)
display_name = models.CharField('表示名', max_length=255, blank=True)
def __str__(self):
return self.displ... |
# -*- coding: utf-8 -*-
__author__ = 'yunge'
'''
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where
index1 must be less than index2. Please note that your returned ... |
# Breakout
import gym
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# %matplotlib inline
from gym import error
from gym.utils import closer
env_closer = closer.Closer()
class Env(object):
# Set this in SOME subclasses
metadata = {'render.modes': []}
reward_range = (-float('inf'), f... |
from otree.api import Currency as c, currency_range
from . import pages
from ._builtin import Bot
from .models import Constants
import random
class PlayerBot(Bot):
def play_round(self):
sex = ['Male','Female']
yield (pages.question, {'sex': sex[random.randrange(0,2)],'age': random.randrange(19,32),... |
from binance.constants import BINANCE_GET_OHLC
from binance.error_handling import is_error
from data.candle import Candle
from utils.debug_utils import should_print_debug, print_to_console, LOG_ALL_DEBUG, ERROR_LOG_FILE_NAME
from utils.file_utils import log_to_file
from data_access.internet import send_request
from... |
from datetime import datetime
from typing import Union
from urllib.parse import urldefrag
import rdflib
from rdflib.namespace import RDF, DC, DCTERMS, XSD
from nanopub import namespaces, profile
from nanopub.definitions import DUMMY_NANOPUB_URI
class Publication:
"""
Representation of the rdf that comprises... |
from Scene import *
from Contains import *
class Sleeping_Beauty(Scene):
def enter(self):
print """
***Sleeping Beauty***
Needs... something to waker her up? make a prince to kiss her?
"""
input = raw_input("> ")
answer = Contains().in_array(input, ['string', 'integer']) # variables are keywords to return... |
from pprint import pprint
from app.app import create_app
app = create_app(environment='development')
def test_get():
with app.test_client() as c:
rv = c.get('/cms/theme/3')
json_data = rv.get_json()
pprint(json_data)
assert rv.status_code == 200
def test_get_all():
with app... |
import azure_translate_api
class translate():
def __init__(self, client_id, client_secret):
self.bing = azure_translate_api.MicrosoftTranslatorClient('pythontest', # make sure to replace client_id with your client id
'y32l8f0X5rq1G+5O9ayNk7p7zI1hHUh5... |
import torch
from app.dataset.wheat import WheatDataset, PredictionDataset
from torch.utils.data import DataLoader
from app import config
from pathlib import Path
from object_detection.utils import DetectionPlot
from app import config
def test_train_dataset() -> None:
dataset = WheatDataset(config.annot_file, con... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('assessment', '0018_auto_20160318_1731'),
]
operations = [
migrations.CreateModel(
name='MentalHealth',
... |
import numpy as np
np.arcsin(0.25)
np.arcsin(np.deg2rad(0.25))
np.rad2deg(np.arcsin(0.25))
180 - (21 + 90)
180 - (47 + 90)
69 - 43
(2500*np.sin(np.deg2rad(21)))/np.sin(np.deg2rad(26))
(2500 * np.tan(np.deg2rad(21))) / (np.tan(np.deg2rad(47)) - np.tan(np.deg2rad(21)))
1394 * np.tan(np.deg2rad(47))
180 - (33 + 63)
(200... |
A,B,C,X,Y = map(int, input().split())
ans = 10**100
cnt = max(X, Y)
for i in reversed(range(0, cnt+1)):
money = 0
money += i * 2*C
if X > i:
money += A*(X-i)
if Y > i:
money += B*(Y-i)
ans = min(ans,money)
print(ans) |
# Copyright 2015 Google Inc. All Rights Reserved.
#
# 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... |
#!/usr/bin/env python3
import signal
import sys
import time
from selenium.common.exceptions import StaleElementReferenceException
from selenium.common.exceptions import WebDriverException
import test_common as common
import test_config as config
from user_map import user_map
session_map = {
"webrtc-test.stirlab.loc... |
class tokens:
__slots__ ='key','value'
def __init__(self,key:str,value:str):
self.key=key
self.value=value
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A script to extract the list of vanity url shorteners maintained at
vanityurlshorteners.com and add them to the list in create_extra_services.py.
This script doesn't actually update create_extra_services.py, it instead
outputs an updated SERVICES list that can be copy... |
#!/usr/bin/python
# (c) 2018 Jim Hawkins. MIT licensed, see https://opensource.org/licenses/MIT
# Part of Blender Driver, see https://github.com/sjjhsjjh/blender-driver
"""Blender Driver unit test that can be run from the unittest application.
This module is intended for use within Blender Driver and can only be used ... |
from flask import Flask
import sys
from flask_socketio import SocketIO, emit, Namespace, join_room, leave_room, rooms
from TwitterAPI import TwitterAPI
app = Flask(__name__)
application = app
# Setup the app with the config.py file
app.config.from_object('config')
socketio = SocketIO(app)
consumer_key='zmkQPv0G6S4... |
# Import libraries
import tensorflow as tf
import numpy as np
import collections
import os
import collections
import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
import scipy.io
from time import sleep
# ROS Stuff
import rospy
... |
# -*- coding: utf-8 -*-
from django.apps import AppConfig
from django.apps import apps
from django.db.models import signals
def connect_tasks_signals():
from tina.projects.tagging import signals as tagging_handlers
from . import signals as handlers
# Finished date
signals.pre_save.connect(handlers.s... |
from django.core.management.base import BaseCommand
from chatwork.models import Account
from chatwork.views import get_diff
from datetime import date
from dateutil.relativedelta import relativedelta
import environ
import requests
env = environ.Env(DEBUG=(bool, False))
class Command(BaseCommand):
def handle(self,... |
#/usr/bin/env python
#
# ChaosGame.py
# Python script for UWS first year lab
# Chaos Game lab experiment
# James Keatings
# James.Keatings@uws.ac.uk
#
import random
import matplotlib.pyplot as plt
points_x = [0, 100, 50]
points_y = [100, 100, 0]
#BEGIN EXPERIMENT
print 'Welcome to the Cha... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Solve project euler 4
Find the largest palindrome made from the product of two 3-digit numbers.
"""
from utils import is_palindrome
def pe4(n=3):
"""
>>> pe4()
906609
"""
first, last = 9*10**(n - 1) + 1, 10**n
mx = 0
for x in range(first, ... |
"""
Site-specific code extension
"""
from typing import Any, Dict
from flask import g
from byceps.services.seating import seat_service
from byceps.services.ticketing import ticket_service
def template_context_processor() -> Dict[str, Any]:
"""Extend template context."""
sale_stats = ticket_service.get_tick... |
import unittest
from leetcode.algorithms.p0328_odd_even_linked_list_1 import ListNode, Solution
from tests.algorithms.list_helper import convert_linked_list_to_list
class TestOddEvenLinkedList(unittest.TestCase):
def test_odd_even_linked_list(self):
a = ListNode(1)
b = ListNode(2)
c = List... |
class Config(object):
DEBUG = True
DEVELOPMENT = True
SECRET_KEY = '@!secretkey!'
static_folder = 'static'
SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://super:!important@inqw-442.postgres.pythonanywhere-services.com:10442/sms'
SQLALCHEMY_TRACK_MODIFICATIONS = False
class Auth(object):
CLIENT_ID = ('KEY')... |
from yarl import URL
def urljoin(base_url: str, *urlpath) -> URL:
path = [str(path).strip(' /') for path in urlpath if path]
path = '/'.join(path)
url = URL(base_url).with_path(path)
return url
|
#!/usr/bin/python3
# Copyright (C) 2011 Internet Systems Consortium, Inc. ("ISC")
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE I... |
#@String directory
from ij import IJ
import os
im = IJ.open(os.path.join(directory, 'dummy.tiff'))
IJ.run(im, "Subtract Background...", "rolling=50")
IJ.saveAs(im,'tiff',os.path.join(directory,'backsub.tiff'))
|
# dizygotic_net.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from base.base_model import BaseModel
from layers.encode import Encode
import tensorflow as tf
class DizygoticNet(BaseModel):
def __init__(self, filters: int, loss: tf.keras.losses.Lo... |
class TreeNode():
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def preorder_traversal(root, visited=[]):
if root is None:
return
visited.append(root.val)
if root.left:
preorder_traversal(root.left, visited)
if root.right:
... |
#coding:utf8
li = [20,15,10,15,10,5]
class h(object):
def __init__(self,num,Q,q,l=None,t=None,child=None):
self.num = num
self.Q = Q-q
self.q = q
self.l = l
self.t = t
if self.l and self.t:
self.l = self.Q/2
self.t = self.Q/2
if chi... |
#
# 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... |
import os
import wave
import pyaudio
import librosa
import librosa.display
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import tensorflow.keras.backend as K
from tensorflow.keras.callbacks import Callback
matplotlib.rcParams['agg.path.chunksize'] = 100000
class GradientSonification(Callback):
... |
__metaclass__ = type#指定使用新式类
class Person:
def setName(self,name):
self.name = name#self相当于C语言中的this指针
def getName(self):
return self.name
def greet(self):
print('Hello,%s' %self.name)
A = Person()
A.setName('ZYQ')
A.greet()
class Bird:
song = 'Squaak!'
def sing(self):
... |
#!/usr/bin/env python
import copy
from studious import question, utils
all_answers = None
class Answer:
key = 0
question_key = 0
user_key = 0
answer = ""
def __contains__(self, item):
return item in self.answer
def __str__(self, verbose=False):
if not verbose:
... |
"""Config file."""
LANGUAGE = 'japanese' #
LEXICON_PATHS = {'english': ['data/raw/english/celex_all.csv', '\\'],
'french': ['data/raw/french/french_lexique.txt', '\t'],
'german': ['data/raw/german/celex_german_all.csv', '\\'],
'japanese': ['data/raw/japanese/japanese_labeled_columns.csv', None], # fo... |
import tensorflow as tf
from prepare_data import generate_datasets
from train import get_model
def test(save_model_dir): |
# !/usr/bin/python
# _*_ coding:utf-8 _*_
import turtle
from random import randint
turtle.speed(10)
turtle.color('gray')
x = -180 # 80
for y in range(-180, 180 +1, 10): # 80
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.forward(360) # 160
y = 180
turtle.right(90)
for x in range(-180, 180 + 1, 10):
t... |
import config
import time, thread
def init():
global BUZZER_PIN, Pi, GPIO
BUZZER_PIN = 12
Pi = False
try:
import RPi.GPIO as GPIO
Pi = True
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(BUZZER_PIN, GPIO.OUT)
except:
print("GPIO not found")... |
from .utils import lback_untitled, lback_backup_dir, lback_backup_ext, lback_db, lback_output, lback_error, lback_print, lback_id,lback_settings, get_folder_size, lback_focused_agent, lback_unique_agent_name
from .restore import Restore, RestoreException
from .backup import Backup, BackupException
from .operation_backu... |
#Making a todo list
def make_list():
'''Making a list to return'''
todo_list =[]
while True:
list_item = input('''What do you need to do today?
Enter one at a time or enter q to quit. ''')
if list_item == 'q':
break
else:
todo_list.append(list_item)
retu... |
# Xander Houdek
# 08/02/20
# minesolver.py - automatically solves a game of minesweeper.py, used for
# my CS325 Algorithms portfolio project
import random
import pygame
from pygame.locals import *
from minesweeper import *
# Global constant, used to check all adjacent cells
PROXIMITY = [
(0, 1), (1, 1), (... |
from flask import Flask
from flask import flash
from flask import render_template
from flask import request
from flask import session
from flask import redirect
from flask import url_for
from diagnostico.reglas import decidirRegla, decidirReglaFormeFruste, decidirReglaQueratocono, decidirReglaSubclinico, decidirReglaS... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.