text
stringlengths
8
6.05M
## DAVID ROTHBLATT ## SOFT DEV ## Mr Zamansky ## Fall 2015 from flask import Flask, render_template, request, session, redirect, url_for from random import randrange import auth app = Flask(__name__) @app.route("/") @app.route("/home") @app.route("/home/") def home(): return redirect(url_for("about")) @app.rout...
import pandas as pd import numpy as np import sys trainxcsv = sys.argv[3] trainycsv = sys.argv[4] testcsv = sys.argv[5] anscsv = sys.argv[6] train_X = pd.read_csv(trainxcsv) train_Y = pd.read_csv(trainycsv,header = None) test_X = pd.read_csv(testcsv) train_X['fnlwgt'] = train_X['fnlwgt'].clip(0,800000) test_X['fnlwgt...
#!/usr/bin/python2.7 import dbus import gobject from dbus.mainloop.glib import DBusGMainLoop import subprocess # MAC address of the bluetooth device DEV_MAC = '00:1A:7D:DA:71:13' dbus_loop = DBusGMainLoop() bus = dbus.SystemBus(mainloop=dbus_loop) man = bus.get_object('org.bluez', '/') print man iface = dbus.Interf...
from django.contrib import admin from .models import * # Register your models here. admin.site.register(university) admin.site.register(Student) admin.site.register(Faculty) admin.site.register(course) admin.site.register(Attendance) admin.site.register(SRS) admin.site.register(SRS_Question)
from . import views from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url urlpatterns=[ url(r'^$',views.pics,name='pics'), url(r'^single_pic/(\d+)',views.single_pic,name='single_pic'), # url(r'^single_car/<art_id>', views.single_car, name='single-car'...
from __future__ import annotations import sys import threading import time from typing import Union, Optional, Dict import serial import _thread import queue import RPi.GPIO as GPIO from LoRaUI import LoRaUI # from Protocol import Protocol # often used strings from Protocol import Protocol from Util import LoopingT...
# -*- coding: utf-8 -*- import signal import sys def signal_term_handler(signal, frame): print 'got SIGTERM' sys.exit(0) signal.signal(signal.SIGTERM, signal_term_handler) signal.signal(signal.SIGABRT, signal_term_handler) signal.signal(signal.SIGBREAK, signal_term_handler) while True: pass
from datetime import date from onegov.ballot import Candidate, List, ListResult from onegov.ballot import CandidateResult from onegov.ballot import ProporzElection from onegov.ballot import ElectionResult def test_candidate_percentages(session): election = ProporzElection( title='Election', domain...
from rv.api import m def test_spectravoice(read_write_read_synth): mod: m.SpectraVoice = read_write_read_synth("spectravoice").module assert mod.flags == 0x49 assert mod.name == "SpectraVoice" assert mod.harmonic_freqs.values == EXPECTED_HARMONIC_FREQS assert mod.harmonic_volumes.values == EXPEC...
import api api = api.api(True,False,False,True) print api.waitForButtonPress()
# -------------------------------------------------------------------- import os # -------------------------------------------------------------------- # Oracle db dsn_tns = """(DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (COMMUNITY = tcp.world) (PROTOCOL = TCP) (HOST = aepw04-bulwscan.e-ssi.net)(PORT = 152...
from flask import Flask, request, jsonify, send_file from utils import Config from wrapper import SmartNews import json def init_model(): config = Config() config.test_from = '../models/model_step_148000.pt' model = SmartNews(config) return model app = Flask(__name__) model = init_model() @app.route...
# @Title: 访问所有点的最小时间 (Minimum Time Visiting All Points) # @Author: 2464512446@qq.com # @Date: 2019-12-17 10:16:27 # @Runtime: 48 ms # @Memory: 11.5 MB class Solution: def minTimeToVisitAllPoints(self, points): x0, x1 = points[0] ans = 0 for i in range(1, len(points)): y0, y1 = ...
from lid_driven_cavity_problem.residual_function import pure_python_residual_function, \ numba_residual_function, cython_residual_function, numpy_residual_function, \ cpp_residual_function, cpp_omp_residual_function from lid_driven_cavity_problem.staggered_grid import Graph import numpy as np def test_residua...
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2018-01-10 06:06 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('nova', '0067_config'), ] operations = [ migrations.AlterField( ...
from flask import Flask, jsonify import requests application = Flask(__name__) @application.route("/api/getmvplate/<string:plate>",methods=["GET"]) def extractplates(plate): data = [('txt', plate),] results = requests.post('http://159.203.187.227/ocpu/user/bando/library/mpesaoptim/R/extractplates/json', data=data) ...
#!/usr/bin/env python import asyncio from typing import Callable from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.application import Application from prompt_toolkit.clipboard.pyperclip import PyperclipClipboard from prompt_toolkit.document import Document from prompt_toolkit.layout.processors imp...
from .whitelistedhashesmodel import WhitelistedHashesModel from .votingdatamodel import VotingDataModel # noinspection PyUnresolvedReferences from pystratis.api.global_responsemodels import PollViewModel __all__ = ['WhitelistedHashesModel', 'VotingDataModel', 'PollViewModel']
#-*- coding: utf-8 -*- from django.db import models from django.utils import timezone from django.core.urlresolvers import reverse from django.contrib.auth.models import User class News(models.Model): title = models.CharField(max_length=60, verbose_name = 'Заголовок') slug = models.SlugField(max_length=60, verbose_n...
from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/login', methods=['POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] ...
if key in counts: counts[key] = counts[key] + 1 else: counts[key] = 1
from sklearn import linear_model import checks as c import visualizations as viz import regClass as rc class OLS(rc.REG): """Object which performs ordinary least squares regression, checks assumptions, and makes plots.""" def check_model(self): """Checks assumptions of OLS regression. Inherits 4 from ...
from django.conf.urls import url, include from rest_framework.urlpatterns import format_suffix_patterns from myapp import views from rest_framework import routers router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'objects', views.ObjectViewSet) router.register(r'categorys'...
import numpy as np import cv2 print(cv2.__version__) image = cv2.imread("AVR_pinmap.png",cv2.IMREAD_UNCHANGED) cv2.imshow("Moon",image) cv2.waitKey(0) cv2.destroyAllWindows()
from .filters import MSAnd from .instructions import SY from .layer import DisplayPriority class Lookup: def __init__(self, id='', table=None, display=None, comment='', instruction=None, rules=None, display_priority=DisplayPriority.NotSet): if rules is None: r...
import tkinter as tk prev = [0, 0] isMouseDown = False root = tk.Tk() canvas = tk.Canvas(root, width=500, height=500) canvas.pack() def mousemove(event): if isMouseDown: canvas.create_line(prev[0], prev[1], event.x, event.y) prev[0], prev[1] = event.x, event.y def mousedown(event): global isM...
import collections import re import numpy as np from janome.tokenizer import Tokenizer from janome.analyzer import Analyzer from janome.tokenfilter import POSStopFilter def CountWord(tweets: list, keyword: str = None, stopword_list: set = None) -> dict: tweet_list = [tweet["text"] for tweet in tweets] all_tw...
import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression #The class sklearn.linear_model.LinearRegression # will be used to perform linear and # polynomial regression an...
#import sys #input = sys.stdin.readline def main(): K = int( input()) X, Y = map( int, input().split()) if K%2 == 0: if (X+Y)%2 == 1: print(-1) return abX = abs(X) abY = abs(Y) a, b = 1, 1 if X < 0: a = -1 if Y < 0: b = -1 if (X+Y)%K ==...
import sys import os from collections import defaultdict from text_preprocess import txt_preprocesser import math import json """KMAMIN 62182275 KRISHAN AMIN""" class bayesian_classifier: def trainNaiveBayes(self,addition): trainlist = [] with open('corpus_data/preprocessedf_corpus.json') as corpus...
import json import uuid import sample import sys sample_map = json.load(open('sample_map.json', 'r')) entity_map = json.load(open('entity_map.json', 'r')) class Intent(): def __init__(self, name, sample_frame): self.id = str(uuid.uuid4()) self.name = name self.sample_frame = sample_frame ...
### preparing data for training variants of CRF models (e.g. semi-markov) on the command line ### import io, argparse def read_data(file): pred = [] for line in file: line = line.strip('\n') toks = line.split() if len(toks) == 0: return pred else: pred.a...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'CounselingAgency' db.create_table(u'hud_api_replace_counselingagency', ( (u'id',...
import urllib, urllib2, json class Salary: def __init__(self, username): url = 'https://socialblade.com/js/class/youtube-money-calculator' param = { 'query' : username } self.req = urllib2.Request(url, urllib.urlencode(param)) self.req.add_header('User-Agent', 'Mozilla/5.0 (X11;...
from morepath import redirect from onegov.org import _ from onegov.org import OrgApp from onegov.org.forms import ManageUserGroupForm from onegov.org.layout import UserGroupCollectionLayout from onegov.org.layout import UserGroupLayout from onegov.core.elements import Link from onegov.core.security import Secret from o...
#DONE #https://www.reddit.com/r/dailyprogrammer/comments/bqy1cf/20190520_challenge_378_easy_the_havelhakimi/ #returns a list that has no zeroes in it def eliminateZero(arr): newArr = [i for i in arr if i != 0] return newArr #returns a list that has been sorted in descending order def sortDesc(arr): newAr...
import argparse import asyncio import logging import os from telegram2mqtt.gateway import Gateway DEFAULT_LOGLEVEL = 'INFO' LOGLEVEL_CHOICES = [ 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL', ] TELEGRAM_API_TOKEN = os.getenv('TELEGRAM_API_TOKEN', None) def main(): # ArgumentParser pars...
# -*- coding:UTF-8 -*- from rest_framework.routers import DefaultRouter from . import views router=DefaultRouter() app_name='goods' router.register('firstClass',views.FirstClassView,base_name='firstClass') # router.register('secondClass',views.SecondClassView,base_name='secondClass') router.register('thirdClass',view...
import torch import torch.nn as nn import torch.optim as optim import torchvision.transforms as transforms import os from torch.autograd import Variable import argparse import numpy as np from torch.optim.lr_scheduler import * import csv from model.resnet import resnet101 from dataset.DogCat import DogCat...
from __future__ import division import pandas as pd import numpy as np import networkx as nx import geopandas as gp from osmnx.utils import make_str from shapely.geometry import LineString, Point from osmnx_simplify_overwrite import simplify_graph from weighted_betweenness import probit_assignment de...
import os import sys import unittest class TestAutoloads(unittest.TestCase): def setUp(self): # Force reload of testconfig module to prevent side-effects from # previous tests try: del sys.modules['testconfig'] except KeyError: pass def tearDown(self): ...
import logging import re from datetime import datetime from decimal import Decimal from .exceptions import ExchangeRateDataError from urllib import parse import requests from requests.exceptions import HTTPError # Regular expression used to destinguish between multiple URLs URL_DETECTION_RE = re.compile( r'([a-z...
from MyUtilities import PrimeNumbers,PowNMod,EuclidianExtended from PrimitiveRoots import PrimitiveRoots import random import time class ElgamalCriptography: def __init__(self,base=0): self.base = base self.generateKeys() def generateKeys(self): prime_length = int(input("How many digit...
"""django0002 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-ba...
# Converting to fuzzy sets import numpy as np def mem1(x,hb,lb): return float((hb-x) / (hb-lb)) def mem2(x,hb,lb): return float((x-lb) / (hb-lb)) def preprocess(num): fname = 'iris.csv' data = np.genfromtxt(fname,delimiter=',') data = data[1:] #if there is heading attribute =[] for i in range(1,num): ...
import serial arduinoComPort = "COM7" baudRate = 9600 ser = serial.Serial(arduinoComPort, baudRate, timeout=1) # # main loop to read data from the Arduino, then display it # while True: # # ask for a line of data from the serial port, the ".decode()" converts the # data from an "array of bytes...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 28 18:50:52 2018 @author: ddeng """ import pandas as pd import pdb import os import numpy as np from sklearn.svm import SVC, LinearSVC from sklearn.model_selection import StratifiedKFold from sklearn.model_selection import train_test_split from sk...
from grpc import insecure_channel import requests import time from canoser import Uint64 from libra.account import Account from libra.account_address import Address from libra.account_resource import AccountState, AccountResource from libra.account_config import AccountConfig from libra.transaction import Raw...
""" Пробуем создать утилиту, которая будет отслеживать редисок, которые скручивают километраж на мажинах и их перепродают """ import urllib3 import json import requests my_kay = "mnrOlvNOeTnNJHyFrkjk6RFZ0NfDkftYxlO2cD1t" def url_search(search_url: str) -> str: # берет строку с функции take_search_string и добав...
from django import forms from itens.models import Filme, Serie, Livro from .models import Avaliacao, Comentario class FazerAvaliacaoFilme(forms.ModelForm): class Meta: model = Avaliacao fields = ['avaliacao', 'valor', 'user_id', 'filme', 'tipo'] labels = {'user_id': '', 'filme': '', 'tipo'...
from django.shortcuts import render from prices.models import Consultant def home(request): context = {'consultants': Consultant.objects.order_by('id')} return render(request, 'landing_page.html', context)
#!/usr/bin/env python """This script plots the mean of the identified gains. The gains must be precomputed. It currently does not include trials from Subject 9.""" # builtin import os import argparse # external import numpy as np import matplotlib.pyplot as plt # local import utils PATHS = utils.config_paths() d...
class Solution: dp = [] def kmp(self, text,pattten) -> int: self.build(pattten) return self.search(text) def build(self,patten): length = len(patten) self.dp = []*length for _ in range(length): alphabetDict = {} for alphabet in range...
""" LARPER - Let's Authenticate Resources Per Each Request Design ====== larper provides the following ways to start an LDAP directory session: * UserSession.connect(request) * RegistrarSession.connect(request) * AdminSession.connect(request) UserSession ----------- Once one has obtained a directory session, one ca...
""" @Author : Laura @File : hr_selenium.py @Time : 2020/3/16 15:43 """ # encoding: utf-8 #指定编码格式 from selenium import webdriver #selenium 模块中导入指定部分webdriver(类) import time #导入时间模块 import unittest chrome_driver=r"E:\Program Files\python 3.8.2\Lib\site-packages\selenium\chromedriver.exe" browser = webdriver.Chro...
# ================================================================================================== # Copyright 2011 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use thi...
import pandas import numpy import random import math from statsmodels import api as sm class Tree(object): def __init__(self): self.left = None self.right = None self.data = None self.feature = None self.constraint = None self.featuresLeftToTry = None self.gi...
from dataclasses import dataclass from enum import Enum from typing import Callable, Type, Union from bot.bot import Bot, Event from mypy_extensions import KwArg, VarArg from typing_extensions import Protocol, runtime_checkable @dataclass class MessageEnv: bot: Bot event: Event user_id: str class BadAr...
import os # ---------------------------------------------------------- def ReadDarksusy(fn): f = open(fn); lines = f.readlines(); f.close() L = lines[0] w = L.split() par = {} #print L w.pop(0); w.pop(0); w.pop(0) par['tests'] = w.pop(0) w.pop(0); w.pop(0) par['ds_oktot'] = int(w.p...
# Copyright Hal Emmerich <SolidHal> 2020 ### tap functions taplock_key = "taplock" # All internal layers should be integers #layers on left hand LEFT_PREFIX = 0 #left_prefix_layer LEFT_CMD = 1 #"left_blank_cmd_layer" SYMS = 2 #"symbols_layer" #layers accessed by left hand prefix RIGHT_PREFIX = 0 #right_prefix_layer...
from bs4 import BeautifulSoup from file_handler.file_handler import FileHandler class XMLHandler(FileHandler): def preview(self): print self.get_xml().prettify() def get_xml(self): return BeautifulSoup(self.get(), 'html.parser') def extract(self, element): for row in self.get_x...
class Stack(object): """ Stack implementation | (C) @ Bofin Babu""" def __init__(self): self.elements = [] def pop(self): return self.elements.pop() def push(self, item): self.elements.append(item) def is_empty(self): return self.elements == [] def size(self):...
#! /usr/bin/env python import rospy import time import actionlib from my_turtlebot_actions.msg import record_odomFeedback, record_odomResult, record_odomAction from std_srvs.srv import Empty from odom_sub import getOdom from geometry_msgs.msg import Twist class Odom_server(object): # create messages that are ...
from pathlib import Path from setuptools import setup wemail = Path(__file__).parent / "wemail.py" with wemail.open("r") as f: for line in f: if line.startswith("__version__"): __version__ = line.partition("=")[-1].strip().strip('"').strip("'") break changelog = (Path(__file__).par...
# -*- coding: utf-8 -*- # This file as well as the whole tsfresh package are licenced under the MIT licence (see the LICENCE.txt) # Maximilian Christ (maximilianchrist.com), Blue Yonder Gmbh, 2016 import pandas as pd from sklearn.base import BaseEstimator, TransformerMixin from sklearn.exceptions import NotFittedError...
import datetime from aiohttp import web from dataclasses import asdict from serv.json_util import json_dumps from .config import db_block, web_routes #得到所有学生的信息 @web_routes.get("/api/student/list") async def get_student_list(request): with db_block() as db: db.execute(""" SELECT sn AS stu_sn, no ...
"Run the MEAPSoft Analyzer" import chop import subprocess import glob import re MEAP_PATH = "lib/MEAPsoft-2.0.beta/bin/MEAPsoft.jar" def run(cmd): p = subprocess.Popen(cmd) p.wait() def analyze(src): f_paths = [] for path in chop.chopped(src): f_path = path + ".feat" f_paths.append(...
#========================================================================= # pisa_sltiu_test.py #========================================================================= import pytest import random import pisa_encoding from pymtl import Bits, sext, zext from PisaSim import PisaSim from pisa_inst_test_utils import...
from game.entity import Entity from game.level import Level from game.component import Component from game.graphicsComponent import GraphicsComponent from game.physicsComponent import PhysicsComponent from game.playerInputComponent import PlayerInputComponent
#coding = utf-8 # refer to http://blog.csdn.net/bone_ace/article/details/46718683 class Node(): def __init__(self,data,left=None,right=None): self.data = data self.left = left self.right = right #层次遍历 def lookup(root): stack = [root] while stack: currrent = stack.pop(0) ...
# Script for Hollerado - Don't Shake project # # The idea is to trace a path from The Barfly in Montreal to # The Danforth Music Hall in Toronto, and to synchronize # the video with the song "Don't Shake" by Hollerado. # # This script is just intended to be an illustration of # the workflow, and a record of the scrip...
import time start = time.time() m = 1 for i in xrange(1, 101): m *= i result = sum(map(int, str(m))) spend = time.time() - start print "The result is %s and take time is %f" % (result, spend)
#!/usr/bin/env python # -*- coding: utf-8 -*- # resources.py # Author: gfcocos import os,sys from xml.etree import ElementTree as ET import json import re import string #输入 # 资源搜索目录 rs_paths = [ "D:\\DiceApp\\res\\branches\\2014-1-17-91\\ResourcesOutput\\image\\ui_winlost", "D:\\DiceApp\\res\\...
from django.contrib import admin # Register your models here. from .models import Stage, SubStage, Block, Level, ProgressEntry, ProgressInventoryEntry, ProgressEntryMedia, \ ProgressComment class StageAdmin(admin.ModelAdmin): search_fields = ['project', 'title'] list_display = ('title', 'created_at', 'up...
kmrodado = float(input('Insira a quantidade de KM percorrido: ')) diasaluguel = float(input('Insira a quantidade de dias de aluguel: ')) totalkm = kmrodado*0.15 totaldias = diasaluguel*60 totalgeral = totalkm+totaldias print(' o seu carro foi alugado por {:.0f} dias e rodou por {} Quilômetros o total a ser pago pelo al...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.dispatch.dispatcher import receiver from django.db.models.signals import post_save from django.utils.encoding import python_2_unicode_compatible from django.core.validators import RegexValidator from django.core.val...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from cnn import CNN import os import librosa FLAGS = tf.app.flags.FLAGS tf.flags.DEFINE_string("checkpoint_path", "data/ckpt", "Model checkpoint file or directory containing a ...
from __future__ import print_function, unicode_literals, division import re def remove_newlines(s): p = re.compile("[\n|\r\n|\n\r]") s = re.sub(p, " ", s) s = remove_extraneous_whitespace(s) return s def remove_extraneous_whitespace(s): p = re.compile("(\s+)") s = re.sub(p, " ", s) retu...
from mazel.runtimes import GoRuntime from .utils import RuntimeTestCase class JavascriptRuntimeTest(RuntimeTestCase): runtime_cls = GoRuntime def test_runtime_label(self): runtime = self.make_runtime() self.assertEqual(runtime.runtime_label, "go") def test_workspace_dependencies(self): ...
import os import day18_part1, day18_part2 def test_part1_example(): input = """set a 1 add a 2 mul a a mod a 5 snd a set a 0 rcv a jgz a -1 set a 1 jgz a -2""".splitlines() assert day18_part1.solve(input) == 4 def test_part1(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = open("da...
import pandas as pd import math import itertools from bokeh.palettes import Dark2_5 as palette def parse_excel_data(directory, sheet_name): ds = pd.ExcelFile(directory) ds_df = ds.parse(sheet_name) return ds_df def extract_column_names(df): return list(df) def extract_row_names(df): return list(df.inde...
#!/usr/bin/python #\file classification1.py #\brief Chainer for 2-D --> Multi-class classification test. # Based on regression4a.py # Search DIFF_REG for the difference. #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date May.16, 2017 import random,math,copy #Float version of ra...
''' Created on Dec 18, 2013 @author: anbangx ''' class C: def __init__(self,los): self.los = los def __len__(self): print('Calling len') return sum((len(i) for i in self.los)) def __bool__(self): return ''.join(self.los) != 'False' if __name__ == '__mai...
from random import randint maria_score = 1001 ivan_score = 1001 winner_found = False while not winner_found: tempSumMaria = 0 tempSumIvan = 0 diceCountMaria = 5 diceCountIvan = 5 while diceCountMaria > 0: roll = randint(1, 6) tempSumMaria += roll diceCountMaria -= 1 if...
import pygame from pygame.sprite import Sprite class Bullet(Sprite): def __init__(self, AI_game): super().__init__() self.screen = AI_game.screen self.setting = AI_game.setting # Loading an image self.image=pygame.image.load("laserRed01.png").convert_alpha()...
#!/usr/bin/env python from os.path import join, realpath import sys; sys.path.insert(0, realpath(join(__file__, "../../../"))) import asyncio import conf import contextlib from decimal import Decimal import logging import os import time from typing import ( List, Optional ) import unittest from hummingbot.co...
import json from os.path import join from pkg_resources import resource_listdir, resource_isdir, resource_stream from public import public from .coordinates import AffineCoordinateModel from .curve import EllipticCurve from .mod import Mod from .model import (ShortWeierstrassModel, MontgomeryModel, TwistedEdwardsMode...
import pygame import os pygame.init() bgDir = 'D:\\GitHub\\PyGame\\texture\\background' bg = pygame.image.load(os.path.join(bgDir, 'bg.jpg')) win = pygame.display.set_mode((500, 500)) win.blit(bg, (0, 0)) pygame.display.update() while 1: for i in pygame.event.get(): if i.type == pygame.QUIT: ...
class Solution(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if root == None: return [] queue = [root] solution = [] while queue != []: solution.append([i.val for i in queue]) ...
import json import httpretty import pytest from hangups import auth # pylint: disable=redefined-outer-name class FakeCredentialsPrompt(auth.CredentialsPrompt): def __init__(self): self.was_prompted = False def get_email(self): self.was_prompted = True return 'test@example.com' ...
#!/usr/bin/env python """ RPG: Timer """ CLOCK = None import pygame def LockFrameRate(framerate=60): global CLOCK if not CLOCK: CLOCK = pygame.time.Clock() CLOCK.tick(framerate)
from django.views.generic.base import View, TemplateView from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.views.generic.edit import CreateView, UpdateView from .models import Payment from .forms import PaymentForm class PublicBaseView(View): """ A base...
import requests import json import pandas as pd import numpy as np import random import time from boto.s3.connection import S3Connection from boto.s3.key import Key tournament_name = 'World Golf Championships - Cadillac Championship' year = 2015 timestamp = time.time() def calculate_mean(hole_distr...
import sys import nltk from nltk.tokenize import TweetTokenizer nltk.download("punkt") import generator.model as md # import generator.ig_utils as igu import generator.twt_utils as twt def generate_tweet(creds, search_terms): # generate a tweet based on credentials file and a list of hashtags tm = {} t...
import subprocess import re import os import sys import time import concurrent.futures # time counter to measure program performance start_time = time.time() # set file location ## remember to use "/" instead of "\" and remember to put an extra "/" at the end file_location = "C:/Users/Rob/Documents/Datalo...
#!/usr/bin/python # # Keeps your IAP up to date # Version 0.1 import os import sys import urllib2 import re import os.path import urlparse import posixpath url001 = 'http://airnav.com/airport/' url002 = 'http://www.ais-netherlands.nl/aim/2015-03-19-AIRAC/eAIP/html/eAIP/EH-AD-2.EHAM-en-GB.html#eham-ad-2.24/' def er...
# -*- coding: utf-8 -*- """ Created on Fri Feb 2 12:07:59 2018 @author: lcristovao """ import numpy as np class Neuron: @staticmethod def Add(array): Sum=0 for e in array: Sum+=e return Sum @staticmethod def Relu(x): if x<0: return ...
#!/usr/bin/python # -*- coding: utf-8 -*- from firstApp.extensions import db class BaseModel(): # 添加一条数据 def save(self): try: # self 代表当前当前实例化的对象 db.session.add(self) db.session.commit() return True except: db.session.rollback() ...
''' author: juzicode address: www.juzicode.com 公众号: 桔子code/juzicode date: 2020.6.26 ''' print('\n') print('-----欢迎来到www.juzicode.com') print('-----公众号: 桔子code/juzicode\n') import platform print('architecture():',platform.architecture()) print('machine():',platform.machine()) print('processor():',platform.processor...
from printer import Color, danger, success, info, format_table from converter import * def resolve(function, value, expected): try: result = function(value) except ValueError as e: result = 'ValueError' except NotImplementedError as e: return e.message, Color.BLUE if result ==...