text
stringlengths
8
6.05M
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # 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 applicab...
# -*- coding: utf-8 -*- import pandas as pd import threading import Queue import logging import time import init_data_struct as ids from extract_from_xml import build_single_itinerary from error_handling import eval_response import trip as tr import sbb_response class SBBAPIThread(threading.Thread): def __init__(...
try: valor = raw_input("Escriba un numero o una palabra para lansar el error ") print type(valor) valor = int(valor) print type(valor) except : print "Error al intrudir datos" else: print valor
import z from collections import defaultdict from sortedcontainers import SortedSet # largest change by mc years ago as a last year predicter wlp_dict = z.getp("wlp_dict") dates = z.getp("dates") rsi_indicator_dic = dict() changers = SortedSet() yearsago = -1*252*2 keeping = 60 discardlocation = int(keeping/2) for j...
import pandas as pd import re # coding=utf-8 import re import string import pandas as pd import csv arabic_punctuations = '''`÷×؛<>_()*&^%][ـ،/:"؟.,'{}~¦+|!”…“–ـ''' english_punctuations = string.punctuation punctuations_list = arabic_punctuations + english_punctuations arabic_diacritics = re.compile(""" ...
while True: al = input("Are you an alien? ").lower() if al == "yes" or al == "y": print("OH MY GOD AN ALIEN!!!!! PLEASE DONT KILL ME.") break elif al == "no" or al == "n": print("Oh, ok. Nevermind.") break else: print("Please put yes or no.")
""" Train a logistic regresion model for document classification. Search this file for the keyword "Hint" for possible areas of improvement. There are of course others. """ #from distutils.version import LooseVersion as Version #from sklearn import __version__ as sklearn_version import pandas as pd import...
import unittest from neo.rawio.tdtrawio import TdtRawIO from neo.test.rawiotest.common_rawio_test import BaseTestRawIO class TestTdtRawIO(BaseTestRawIO, unittest.TestCase, ): rawioclass = TdtRawIO entities_to_test = ['aep_05'] files_to_download = [ 'aep_05/Block-1/aep_05_Block-1.Tbk', 'a...
import copy # import hashlib def leftRotate(num, shiftNum): return ((num << shiftNum) | (num >> (32 - shiftNum))) & 0xffffffff def SHA1(message: bytes): # Initialize variable h0 = 0x67452301 h1 = 0xEFCDAB89 h2 = 0x98BADCFE h3 = 0x10325476 h4 = 0xC3D2E1F0 mask = 0xffffffff messageL...
import dash_bootstrap_components as dbc from dash import html alert = dbc.Alert( [ html.H4("Well done!", className="alert-heading"), html.P( "This is a success alert with loads of extra text in it. So much " "that you can see how spacing within an alert works with this " ...
import torch import torch.nn as nn # # L2 Loss # L2Loss(outputs, targets) # outputs -> shape BATCH_SIZE x NUM_CLASSES # targets -> shape BATCH_SIZE x NUM_CLASSES # class L2Loss(): # Constructor def __init__(self, reduction=None, alpha=1.0): default_reduction = 'mean' if red...
from sqlalchemy.exc import DatabaseError, IntegrityError from marshmallow import ValidationError from .models import ( Costumer, User, Seller ) from .serializers import( CostumerSchema, UserSchema, SellerSchema ) from utils.errors import ( ConflictError, NotFoundError, ClientExceptio...
from django.test import TestCase from django.core.urlresolvers import reverse from .models import Neighborhood class NeighborhoodViewTests(TestCase): def setUp(self): pass def test_neighborhood_home_without_login(self): resp = self.client.get('neighborhood:neighborhood_home') self.assertEqual(resp.status_cod...
"""setup.py for flake8-import-order-tkalus.""" from setuptools import setup __title__ = "flake8-import-order-tkalus" __author__ = "Turtle Kalus" __email__ = "turtle" "@" "kalus.us" __version__ = "2.0" __copyright__ = "Copyright (C) 2019 tkalus" __license__ = "MIT License" install_requires = ["flake8-import-order >=...
class Solution: #Function to find the maximum number of meetings that can #be performed in a meeting room. def maximumMeetings(self,n,start,end): result=[] for i in range(len(start)): result.append((start[i],end[i])) result.sort(key=lambda x:x[1]) ...
#!/usr/bin/env python Import('env') env_module = env.Clone() # Thirdparty sources thirdparty_dirs = [ "thirdparty/exoquant/", "thirdparty/hq3x/", ] thirdparty_sources = [] thirdparty_sources += Glob("thirdparty/exoquant/*.c") thirdparty_sources += Glob("thirdparty/hqx/*.cc") env_thirdparty = env_module.Clone...
from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from rest_framework.authtoken.models import Token from allauth.account.models import EmailAddress from django.shortcuts import get_object_or_404 @receiver(post_save, sender = settings.AUTH_USER_MODEL) d...
import unittest from katas.kyu_8.grasshopper_terminal_game_1 import Hero class HeroTestCase(unittest.TestCase): def setUp(self): self.myHero = Hero() def test_equals(self): self.assertEqual(self.myHero.name, 'Hero') def test_equals_2(self): self.assertEqual(self.myHero.experienc...
#1 def BMIC(): weight = float(input("Please enter your weight in pounds: ")) height = int(input("Please enter your height in inches: ")) BMI = (weight * 720) / (height ** 2) if BMI > 25: print(BMI) print("\nyour BMI is above the healthy range") elif BMI < 19: print(BMI) ...
from flask import Flask, jsonify, request app = Flask(__name__) books = [ {'name': 'Green Eggs and Ham', 'price': 7.99, 'isbn': 9870394800165 }, {'name': 'The Cat In the Hat', 'price': 6.99, 'isbn': 9870394800193 } ] @app.route('/books') def get_books(): return jsonify({'book...
from pyVim import connect from pyVmomi import vim import ssl import tasks import pdb gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1) si=connect.SmartConnect(host="",port=443,user="",pwd="",sslContext=gcontext) def get_root(): content = si.RetrieveContent() rootfolder = content.rootFolder print "Coneected to ...
#!/usr/bin/env python # Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that msvs_external_builder being set will invoke the provided msvs_external_builder_build_cmd and msvs_external_builder_clean_c...
from app import db from app.model.DetailsModel import Details class Queries(db.Model): __tablename__ = "queries" # Define nama tabel id = db.Column(db.Integer, unique=True, primary_key=True, nullable=False) query_name = db.Column(db.String, nullable=False) details = db.relationship("Details", backref...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 23 18:20:22 2019 @author: karthik """ # Importing the needed libraries import pandas as pd import numpy as np import matplotlib.pyplot as pl # Importing the data train=pd.read_csv('Data/train.csv') test=pd.read_csv('Data/te...
import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import KFold, cross_val_score from sklearn.preprocessing import PolynomialFeatures from gaussian_kernel_funcfile import * #(i)(a) x_dummy_training_data=np.array([-1,0,1]).reshape(-1,1) y_dummy_training_data=np.array([0,1,0]).reshape(-1,1)...
#-*- coding:utf8 -*- # Copyright (c) 2020 barriery # Python release: 3.7.0 """ [{ "NodeID": "xxxxxx", "NodeFreeResourceInfo":"...jsonString...", "NodeContractResourceInfo":"...jsonString..." }, { "NodeInfo": "...jsonString...", "NodeFreeResourceInfo":"...jsonString...", "NodeContractResourceInfo":"...jsonString....
from django import forms from reddituser.models import RedditUser class UpdateUserForm(forms.Form): bio = forms.CharField( max_length=250, required=False, widget=forms.TextInput( attrs={ 'class': 'input', 'placeholder': 'Bio' })...
import requests import urllib3 res = requests.get('https://localprod.pandateacher.com/python-manuscript/crawler-html/chromedriver/ChromeDriver.html') print(res.text)
from django.utils.text import slugify def overlap_percent(geom1, geom2): # How much of the area of geom2 is also inside geom1 # (expressed as a percentage) g1 = geom1.transform(27700, clone=True) g2 = geom2.transform(27700, clone=True) intersection = g1.intersection(g2) return (intersection.ar...
from pico2d import * import math class Player: bodyImage = None barrelImage = None interested_keys = [ SDLK_LEFT, SDLK_RIGHT, SDLK_UP, SDLK_DOWN ] d1, d2 = 16, 35 def __init__(self): self.x = 400 self.y = 300 self.angle = 0 self.bAngle = 0 self.bx = self.x ...
from main.page.desktop_v3.setting.pe_user import * from selenium.webdriver.common.by import By from random import randint import time, subprocess class UserProfile(UserSetting): #tab locator for detail _name_loc = (By.ID, "full-name") _birthday_date_dd_loc = (By.XPATH, "//select[@name='bday_dd']/option") ...
import socket import pickle import dice_chess from _thread import * # Server ip address in server add the ip address of the server server = socket.gethostname() PORT = 5555 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((server, PORT)) except socket.error as e: print(e) ...
#!/usr/bin/env python3 """ Scrape heatmaps from Airwave """ from argparse import ArgumentParser from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys import time def scrape(username, password, sites_csv): driver = webdriver...
from backbone import * from backbone.collector import * import time import re ''' To check if the following on collector nodes : 1. Check if kfps of collector is contant for configured days or for 5 days default 2. Check if kfps of collector is contant for configured hours or for 10 hours default ''' nodes ...
#!./venv/bin/python """ Indexes the contents of the bundle store. Used during the launch of the new worker system. TODO(klopyrev): Delete once it's launched. """ import sys sys.path.append('.') from codalab.common import State from codalab.lib.codalab_manager import CodaLabManager from codalab.model.tables import bun...
""" These are member related models. """ from dataclasses import dataclass, field from typing import List, Optional from .base import BaseModel from .common import BaseApiResponse from .mixins import DatetimeTimeMixin @dataclass class MemberSnippetMemberDetails(BaseModel): """ A class representing the m...
# # @lc app=leetcode.cn id=83 lang=python3 # # [83] 删除排序链表中的重复元素 # # @lc code=start # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: # 166/1...
class SQList(): def __init__(self,lis = None): self.r = lis def swap(self,i,j): self.r[i],self.r[j] = self.r[j],self.r[i] def bubble_sort(self): lis = self.r length = len(self.r) for i in range(length): for j in range(i + 1,length): if l...
contents = [] rawline = open("linebuffer.txt", "r") for line in rawline: contents.append(line) rawline.close() if (contents[0] == 'U' && contents[1] == 'n' && contents[2] == 'k'): next_step = open("lined.txt", 'w') next_step.write(". rbrain.txt") next_step.close() else: message_final = open...
import json from graphql_server import (HttpQueryError, default_format_error, encode_execution_results, json_encode, load_json_body, run_http_query) class PaginatedResult(object): def __init__(self, data, per_page, page, total_count): self.__per_page = per_page self.__p...
class Ordenar: def __init__(self, lista): self.lista = lista def borbuja(self): for i in range(len(self.lista)): for j in range(i + 1, len(self.lista)): if self.lista[i] > self.lista[j]: aux = self.lista[i] self.lista[i]...
""" Created by Alex Wang on 2017-07-30 非阻塞异步flask服务 logger:https://stackoverflow.com/questions/26578733/why-is-flask-application-not-creating-any-logs-when-hosted-by-gunicorn """ import os from gevent import monkey monkey.patch_all() from flask import Flask, request from gevent import wsgi import tensorflow as tf os.e...
nome = input("Qual seu nome:") print('Meu nome é {} e programo em python'.format(nome)) print('Meu nome é ' + nome + ' e programo em python')
def factorial(n): if n < 2: return 1 else: return n * factorial(n-1) def combinations(l,s): return factorial(l)/(factorial(s)*factorial(l-s)) def binomialdist(x,n,l): combs = combinations(n,x) first = l[0]*0.01 second = 1-first return combs*(first**x)*(second**(n-x)) def c...
# Copyright (c) 2014 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { 'target_name': 'test-floating-point-model-default', 'type': 'executable', 'sources': ['floating-point-model-precise.cc'], ...
from django.db import models class Aluno(models.Model): nome = models.CharField(max_length=50) cpf = models.CharField(max_length=14) email = models.CharField(max_length=50) tel = models.CharField(max_length=14)
from django.db import models from PIL import Image class Author(models.Model): lastname = models.CharField(max_length=50, blank=True, null=True) middlename = models.CharField(max_length=50, blank=True, null=True) firstname = models.CharField(max_length=50, blank=True, null=True) date_added = models.Da...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, with_statement from revolver.core import run from revolver import package from revolver.tool import pythonbrew def install(version, _update=True): # Without this we would build python without the bz2 package package.ensure("libbz2-dev...
import os import operator from collections import defaultdict from BitVector import BitVector # TODO File with all constants SOURCE_LABEL = "matteosalvinimi" NUM_TWEETS = 100 DATA = "data1" PEOPLE = "people1" FINAL_GRAPH = "graph" def tweet_parser(filename, hashtags_map=None, hashtags_bitmask=None, graph_id=None, de...
import media import fresh_tomatoes """ Create new movie object to 3 variables is dunkirk_movie, the_ragnarok, wonder_woman """ dunkirk_movie = media.Movie('Dunkirk', 'Dunkirk is a 2017 war film written, directed, and' 'produced by Christopher Nolan that depicts t...
import os import datetime from functools import wraps from gevent import monkey, wsgi monkey.patch_all() from app import create_core from flask_script import Manager from flask_migrate import MigrateCommand env = os.getenv('ENVIRONMENT', 'default') core = create_core(env) app = core.app manager = Manager(app) manag...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.contrib.gis.db.models.fields class Migration(migrations.Migration): dependencies = [ ('api', '0002_location_user'), ] operations = [ migrations.CreateModel( ...
from unittest import TestCase from app import app from models import db,User app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///test_user_db' app.config['SQLALCHEMY_ECHO'] = False db.drop_all() db.create_all() class UserModelTestCase(TestCase): def setUp(self): User.query.delete() def te...
#! /usr/bin/python # -*- coding: utf-8 -*- from db_manager import executeDDL from db_manager import executeDML from db_manager import executeSearch print('Inicializando agenda') def createOrConnectDB(): executeDDL('''CREATE TABLE IF NOT EXISTS datos (nombre TEXT, apellido TEXT, telefono TEXT, correo TEXT)'''...
""" Definition of TreeNode: """ class TreeNode: def __init__(self, val= None): self.val = val self.left, self.right = None, None class Solution: """ @param: root: A Tree @return: Preorder in ArrayList which contains node values. """ def createTree(self): root = TreeNo...
# Generated by Django 2.2.3 on 2019-07-14 11:53 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('account', '0028_auto_20190709_1531'), ] operations = [ migrations.RenameField( model_name='user', old_name='tak_address', ...
import datetime import math import numpy as np import pandas as pd from .config import PLAYERS def main(): df2016 = pd.read_csv(r"C:\Users\Michael.Copeland\Projects\nba\NBA Stats 2016.csv") df2017 = pd.read_csv(r"C:\Users\Michael.Copeland\Projects\nba\NBA Stats 2017.csv") df2018 = pd.read_csv(r"C:\Users...
#coding:utf-8 #透视变换 import cv2 as cv import numpy as np img = cv.imread('D:/python_file/Opencv3_study_file/images/PT_Picture.jpg') rows,cols,ch = img.shape pts1 = np.float32([[56,65],[368,52],[28,387],[389,390]]) pts2 = np.float32([[0,0],[300,0],[0,300],[300,300]]) M = cv.getPerspectiveTransform(pts1,pts2) dst = c...
import torch import torch.nn as nn from torch.autograd import Variable class FusedBlock(nn.Module): def __init__(self, z_dim=128): super(FusedBlock, self).__init__() self.fc = nn.Linear(128, 4*4*1024) self.bn1 = nn.BatchNorm1d(4*4*1024) self.conv1 = nn.ConvTranspose2d(1024,...
import socket import sys def run(user, password, * commands): HOST, PORT = "codebb.cloudapp.net", 17429 data = user + " " + password + "\n" + "\n".join(commands) + "\nCLOSE_CONNECTION\n" with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.connect((HOST, PORT)) sock.sendall...
import pandas as pd from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error import random import time import numpy as np from datetime import datetime def randomDate(): frmt = '%d...
#coding:utf-8 if __name__ == "__main__": String1 = "Welcome to Git firstly!" String2 = "jiwei" print(String1,String2)
from typing import Dict, List from .lib.placeholder import Placeholder class AbstractInterface: """ AbstractInterface를 상속받아 새 DB Model의 Interface를 만들 수 있습니다. 새 Interface에서 다음의 변수를 사용하십시오: 1. create_fields INSERT할 때 필수적으로 필요한 Fields를 List로 정의할 수 있습니다. 2. retrieve_fields SELECT할 때 필요한 Fi...
class Environment(): def __init__(self, players, deck, currentPlayer): self.players = players self.deck = deck self.winners = [] self.currentPlayer = currentPlayer self.previousPlayer = None
GlowScript 2.1 VPython # Using a graph-plotting module EPS = 0.001 energy = -0.25 scene.height = 20 scene.background = vector(0.95, 0.95, 0.95) class EventBus: def __init__(self): self.events = dict(color=5) def on(self, event_name, handler): events = self.events if not events[event_name]: e...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Script to parse USN change journal records.""" import argparse import logging import sys from dtformats import usn_journal from dtformats import output_writers def Main(): """The main program function. Returns: bool: True if successful or False if not. """...
from django.shortcuts import render from mainapp.models import CollegeGroup, Student def index(request): return render(request, 'mainapp/index.html') def students(request): categories = CollegeGroup.objects.all() context = { 'categories': categories, 'page_title': 'каталог' } re...
""" This code computes the order of two sibling nodes in a dependency subtree, where the left and the right siblings are defined on the source dependency tree. Each node is represented by the continuous vector of its dependency link to its parent node. """ __docformat__ = 'restructedtext en' import os import sys imp...
from scapy.layers.l2 import ARP, Ether from scapy.sendrecv import srp import time import requests url = "https://api.macvendors.com/" def get_mac_details(mac_address): response = requests.get(url + mac_address) return response.content.decode() target_ip = input('Enter the IP address:') startTime = time.tim...
import numpy as np import scipy.stats as stats import matplotlib.pyplot as plt from sklearn.cluster import KMeans import kmeans import gausian_mixture_model gauss1 = stats.multivariate_normal([0, 0], [[20, 0], [0, 20]]) gauss2 = stats.multivariate_normal([12, 12], [[3, 0], [0, 3]]) gauss3 = stats.multivariate_normal(...
# scrape.py # Ethan Malenchek # a program to gather information on the top NFL fantasy scorers import requests import re import pandas as pd from bs4 import BeautifulSoup website_url = requests.get('https://fantasy.nfl.com/research/scoringleaders').text path = './top_25.csv' soup = BeautifulSoup(website_url, 'html.pa...
import datetime from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth import get_user_model # Create your models here. class Question(models.Model): que...
from model import Base, Product from model import Base, Cart from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///database.db') Base.metadata.create_all(engine) DBSession = sessionmaker(bind=engine) session = DBSession() def add_product(name, price, pictur...
str1='ABCD' str2='PQR' for i in range(4): print(str1[:i+1]+str2[i:])
import random from words import word_list def get_word(): word = random.choice(word_list) return word.upper() def play(word): print('hello lets play') word_completion = '_'*len(word) guessed = False guessed_letters = [] guessed_words = [] tries = 6 ...
import scrapy from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors import LinkExtractor from scraper_auchan.items import ScraperAuchanItem class AuchanSpider(CrawlSpider): name = 'auchan' allowed_domains = ['www.auchandirect.fr'] start_urls = ['http://www.auchandirect.fr...
import pygame from card import * #屏幕大小常量 SCREEN_RECT = pygame.Rect(0,0,997,604) #刷新帧率 FRAME_PER_SEC = 60 #背景图片地址 BGC_IMAGE_NAME = './images/table.png' #牌图片的大小 CARD_SIZE = (56,98) #这些位置目前还没有实现居中对齐 #手牌位置 HAND_CARDS_POS = (120,SCREEN_RECT.bottom-CARD_SIZE[1]-10) #手牌偏移比例 HAND_CARDS_PARTITION = 0.4 #出牌位置 GIVEN_CARDS_POS =...
''' This module provides a set of useful functions on dictionaries For example : - `get_path` to retrieve a nested element in a dict ''' def falsy_key(d:dict, key:str) -> bool: """ returns `True` if key is not an attribute of dict `d` or if `d[key]` is falsy Returns ------- bool False i...
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders fromaddr = "healthyheartdoctor@gmail.com" toaddr = '2017.akash.magdum@ves.ac.in' msg = MIMEMultipart() msg['From'] = "healthyheartdoctor@gmail.com" ms...
# ************************************************************* # # The OpenTRV project licenses this file to you # under the Apache Licence, Version 2.0 (the "Licence"); # you may not use this file except in compliance # with the Licence. You may obtain a copy of the Licence at # # http://www.apache.org/licenses/LICEN...
from kadi import events from utilities import append_to_array, find_first_after, same_limits, heat_map close('all') temp = 'PM3THV2T' on_range = 60 off_range = 89 t_start = '2000:001' t_stop = None #t_stop = '2013:268' t_event = array([DateTime('2006:351:04:38:00.000').secs, DateTime('2006:351:04:...
import random import telebot import JSON from file import read_from_file bot = telebot.TeleBot(read_from_file('token.txt')) users_json = 'users.json' def create_user(data, message): data[message.from_user.id] = {'name': message.from_user.first_name, 'username': message.from_user.username, ...
# coding:utf-8 city = " 北京 " # 原始输出 print(city) # 去除字符串两边的空格 print(city.strip()) # 去除字符串开头的空格 print(city.lstrip()) # 去除字符串末尾的空格 print(city.rstrip())
from pprint import pprint from django.core.management import BaseCommand from web.models import NotionDocument from web.utils import make_topic_model from web.utils import preprocess_docs_to_words class Command(BaseCommand): def handle(self, *args, **options): notion_docs = NotionDocument.objects.all() ...
def valid(num): _str= str(num) total = 0 for i, char in enumerate(_str, 1): digit = int(char) total += digit ** i return total == num def sum_dig_pow(a, b): # range(a, b + 1) will be studied by the function output = [] for i in range(a, b+1): if valid(i): ...
from django.db import models from team.models import Team from user.models import User image_path = "image" class Announcement(models.Model): id = models.AutoField(primary_key=True) author = models.CharField(max_length=16, verbose_name="发布人") title = models.TextField(max_length=100, verbose_name="标题") ...
import cv2,time first_frame=None video=cv2.VideoCapture(0) while True: check,frame=video.read() gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) gray=cv2.GaussianBlur(gray,(21,21),0) if first_frame is None: first_frame=gray continue delta_frame=cv2.absdiff(first_frame,gr...
#coding:utf-8 import sys import pickle class_dict = pickle.load(open(sys.argv[1])) count = 0 for c, wlist in class_dict.items(): print print c, "\n------", len(wlist), "words in class-------" for w in sorted(wlist): count += 1 print "\t", w print "---------\nall words", count
import unittest from katas.kyu_8.grasshopper_bug_squashing import ( coins, health, log, main, position ) class GrasshopperTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(coins, 0) def test_equals_2(self): self.assertEqual(health, 100) def test_equals_3(self): ...
import numpy as np import matplotlib.pyplot as plt class DataLoader: def class_weights(COUNT_PNEUMONIA, COUNT_NORMAL, TRAIN_IMG_COUNT): initial_bias = np.log([COUNT_PNEUMONIA / COUNT_NORMAL]) print(initial_bias) weight_for_0 = (1 / COUNT_NORMAL) * (TRAIN_IMG_COUNT) / 2.0 weight_for...
#importing stuff import turtle import time wn = turtle.Screen() wn.title('Boring game') wn.bgcolor('black') wn.setup(width=600, height=600) wn.tracer(0) ball = turtle.Turtle() start_game = turtle.Turtle() start_game.speed(0) start_game.color('white') start_game.penup() start_game.hideturtle() start_game.goto(0,0) start...
"""Unit test for treadmill.appcfg.abort """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import io import json import os import shutil import tempfile import unittest import kazoo import mock import treadmill fro...
Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 01:25:11) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "copyright", "credits" or "license()" for more information. >>> WARNING: The version of Tcl/Tk (8.5.9) in use may be unstable. Visit http://www.python.org/download/mac/tcltk/ for current information. >...
from otree.api import ( models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer, Currency as c, currency_range ) import random author = 'Your name here' doc = """ Your app description """ class Constants(BaseConstants): name_in_url = 'CTB' players_per_group = None num_rounds = 1 ...
# You are given a file containing the coordinates in 2D plane of 3 points of # N triangles (line by line, comma-seperated in each line). # # Task: Count the number of triangles that contain the origin. MAX_LEN = 3 MAX_NUM = 6 def countNumTriangleContainOrigin(): fileName = input('Enter the name of the file: ') ...
# quotes/urls.py # -*- coding: UTF-8 -*- from __future__ import unicode_literals from django.conf.urls import url from quotes import views urlpatterns = [ # Examples: # url(r'^$', 'myproject.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^(?P<quote_id>\d+)/download/$', views...
from math import ceil def reindeer(presents): assert 0 <= presents <= 180 return int(2 + (ceil(presents / 30.0)))
# Copyright 2017 Intel Corporation # # 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 agreed to in wri...
from typing import List from leetcode import test def move_zeroes(nums: List[int]) -> None: i = 0 for j, num in enumerate(nums): if num != 0: nums[i] = nums[j] i += 1 while i < len(nums): nums[i] = 0 i += 1 test(move_zeroes, [([0, 1, 0, 3, 12], [1, 3, 12,...
from bert_serving.client import BertClient def get_bert_client(): # return BertClient(ip="192.168.86.176") # if in Aperture Science return BertClient() # requires active SSH tunnel with local forwards on 5555 and 5556