text stringlengths 38 1.54M |
|---|
def validate_tournament_info(tournament_info):
is_validated = True
player_name = []
for p in tournament_info["playerlist"]:
#重複チェック
if p["name"] in player_name:
is_validated = False
#空文字チェック
if len(p["name"]) is 0:
is_valida... |
## board.py Dana Hughes 25-Aug-2017
##
## Object representing an individual board in ZZT.
class Tile:
"""
Object to hold tile data
"""
def __init__(self, element_id, color_id):
"""
Create a tile of the provided element and color
"""
self.element_id = element_id
self.color_id = color_id
class Bo... |
import praw
import utils.config as cf
import data_pull as dp
import utils.constants as constants
import string
def get_reddit_instance(config_filepath):
"""
Gets a PRAW reddit instance.
:return: a reddit instance.
"""
client_id, client_secret, password, user_agent, username = cf.get_oauth(config_f... |
#from django import forms
#from .models import Maison
"""
STATUS_CHOICES = (
('L', 'libre'),
('O', 'occupee'),
('I', 'indisponible')
)
class ChambreForm(forms.Form):
"""
# This is the form for chambre.
"""
error_messages = {
'chambre existant': 'Cette chambre existe deja',
... |
from office365.onedrive.internal.resourcepaths.resource_path_url import ResourcePathUrl
from office365.runtime.http.http_method import HttpMethod
from office365.runtime.queries.service_operation_query import ServiceOperationQuery
def create_upload_content_query(folder_item, name, content=None):
"""
:param of... |
import numpy as np
import matplotlib.pyplot as plt
def axesCross(ax):
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
def periodization(f, T, times, ax=None):
limit = np.floor(T*times/2)
x =... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 15 19:58:02 2017
@author: chris
"""
import pandas as pd
import numpy as np
import random as rd
################################
#Does the SRS(Spaced Repition) Dirty Work
def ChooseIDs(df,TotalSentences,SentsPerDay):
length = len(df)
if TotalSentences <... |
def karatsuba(x,y):
"""Karatsuba multiplication algorithm.
Return the product of two numbers in an efficient manner
@author Shashank
date: 23-09-2018
Parameters
----------
x : int
First Number
y : int
Second Number
Ret... |
class Solution:
def maxProduct(self, nums):
if not nums:
return 0
maxx = minn = product = nums[0]
for i in range(1, len(nums)):
if nums[i] < 0:
maxx, minn = minn, maxx
maxx = max(nums[i], maxx * nums[i])
mi... |
from django.contrib import admin
from .models import Product, OrderItem, Order, OrderInfo, Status,Updates
admin.site.register(Product)
admin.site.register(OrderItem)
admin.site.register(Order)
admin.site.register(OrderInfo)
admin.site.register(Status)
admin.site.register(Updates) |
__author__ = 'hiking'
import os
import sys
sys.path.append(os.path.dirname(__file__)+'/../../lib')
sys.path.append(os.path.dirname(__file__)+'/../../bin')
|
# Generated by Django 2.1.5 on 2019-09-13 19:34
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
# -*- coding:utf-8 -*-
"""
数据存储与读取
Author: Gary-Hertel
Date: 2021/01/19
"""
import csv
def txt_save(content, filename, mode='a'):
"""
保存数据至txt文件。
:param content: 要保存的内容,必须为string格式
:param filename:文件路径及名称
:param mode:
:return:
"""
with open(filename, mode=mode, encoding="utf-8") as ... |
import asyncio
from functools import partial
import os
import logging
from again.utils import unique_hex
import aiohttp
from aiohttp.web import Application, Response
import signal
from .jsonprotocol import ServiceHostProtocol, ServiceClientProtocol
from .registryclient import RegistryClient
from .services import TCP... |
"""Changed Views table name
Revision ID: 7f559bb24ca4
Revises: cc927fe47c8f
Create Date: 2021-08-20 23:20:31.959984
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "7f559bb24ca4"
down_revision = "cc927fe47c8f"
branch_labels = None
depends_on = None
def upgrade... |
def find(x):
if x==parent[x]:
return x
else:
p=find(parent[x])
parent[x]=p
return parent[x]
def union(x,y):
x=find(x)
y=find(y)
parent[y]=x
parent=[]
for i in range(0,5):
parent.append(i)
union(1,4)
print(parent)
for i in range(1,len(parent)):
print(find(... |
#!/usr/local/bin/python3
import time
import random
from twilio.rest import TwilioRestClient
#twilio information - You'll need to update this with your account information.
ACCOUNT_SID = "xxxxxxxxxxxxxxxxxx"
AUTH_TOKEN = "yyyyyyyyyyyyyyyyyyyy"
TWILIO_NUMBER = "+18005551212"
#random phrases - you can exted to as many ... |
# BasicInputA.py
import math
t = int(input())
nada = int('0b0000000000',2)
todo = int('0b1111111111',2)
for loopNum in range(1, t + 1):
orgN = int(input())
treshold = 0
numLength = 0
try:
numLength = int(math.log10(orgN)) + 1
treshold = pow(10,numLength)
except:
n = "INSOMNIA"
els... |
"""
Allows to set start and/or end time of nightly jobs time window.
The <value> is supposed to be specified as 'hh:mm', e.g. '23:45'
Example Usage:
bin/instance run set_nightly_jobs_time_window.py --start '01:00' --end '05:00'
"""
from datetime import timedelta
from opengever.maintenance.debughelpers import set... |
import math
n=int(input("enter a number greater than 1:"))
if (n>1):
if (2**int(math.log(n,2))==n):
print("Y")
else:
print("N")
else:
n=int(input("enter a number greater than 1:"))
|
from copy import copy
from day10_1 import hash_string
SUFFIX = [17, 31, 73, 47, 23]
def run_rounds(start_lengths, num_rounds=64):
pos = 0
skip_size = 0
original_lengths = copy(start_lengths)
the_input = list(range(256))
for _ in range(num_rounds):
working_lengths = copy(original_lengths)... |
# lst = list([12, 30, 10, 4, 100])
# maximum = max(lst)
# print(f'The maximum age of students in the class is {maximum}')
# name = input('Enter your first name: ')
# print(f'Your first name is {name}')
# math module is named math.py
# to use the mofule ww need to import it
# import math
# using sqrt(x)
# x = 9
# r... |
from django.shortcuts import render
from django.template import RequestContext, loader
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.contrib.auth import logout,authenticate,login
from django.shortcuts import redirect
from .config import *
from .forms import CustomerForm
... |
import requests, re
import bs4
def getName():
while True:
print("please input name")
original_name = input()
if(not original_name):
print("empty name")
else:
break
return original_name
def searchName(Name):
res = requests.get("https://google.com/sear... |
# my solution
# i = 1
#
# while i != 100:
# print(i, end=' ')
# if i % 10 == 0:
# print()
# if i > 90:
# print('...')
# break
# i += 1
# instructor solution
start = 10
stop = 90
total = 0
while True: # Loop Forever!
print(start, end=' ')
total += 1
start += 1
... |
import sys
import time
import os
import commands
def main():
file_ref = open('E-MTAB-2600.sdrf.txt','r')
all_names = {}
file_ref.readline()
for line in file_ref:
id = line.strip().split("\t")[26].split('/')[-1].split(".fastq")[0]
name = line.strip().split("\t")[24].split("Teichmann_")[1].split("... |
import pygame, sys
from pygame.locals import *
pygame.init()
monitor_size = [pygame.display.Info().current_w, pygame.display.Info().current_h]
WINDOW_SIZE = (1200, 800)
fullscreen = False
screen = pygame.display.set_mode(WINDOW_SIZE, pygame.RESIZABLE)
display = pygame.Surface((300, 200))
pygame.display.... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2021-03-23 10:34
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wildlifecompliance', '0531_auto_20210120_1001'),
]
operations = [
migratio... |
from random import seed, random
import os
from time import sleep, time
import pathlib
import math
from lf_camera import LightFieldCamera
from random_lf import create_random_lf_cameras
from random_clip import random_clip_lf, restore_clip
from random_clip import random_plane_clip
import welford
import inviwopy
import i... |
from config.util.topo import VaranusTopo
from varanuspy.functions import resetqos, setqos, ssrclinks, switches
from varanuspy.rcli import start_rcli
from varanuspy.utils import resolve
def pre_start_config( mr, extra_args, local_varanus_home ):
""" Configure a MininetRunner object before Mininet starts.
-... |
'''
Created on 2020年10月27日
@author: MR.Tree
'''
#ak服务器端
AK='15qi7rWWtKV04jb7EDiV8XsbmdODmcFp'
query=[{'key':'zt_1','value':'绝味鸭脖'},
{'key':'zt_2','value':'煌上煌酱鸭'},
{'key':'zt_3','value':'紫燕百味鸡'},
{'key':'zt_4','value':'精武鸭脖'},
{'key':'zt_5','value':'久久丫'},
{'key':'zt_6','value':'降龙爪... |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import pandas as pd
df=pd.read_csv("salaries.csv")
df.head()
# In[5]:
inp=df.drop("salary_more_then_100k",axis="columns")
inp
# In[6]:
target=df["salary_more_then_100k"]
target
# In[7]:
from sklearn.preprocessing import LabelEncoder
le_company=LabelEncoder()... |
import re
import itertools
line = 'mtMmEZUOmcqWiryMQhhTxqKdSTKCYEJlEZCsGAMkgAYEOmHBSQsSUHKvSfbmxULaysmNOGIPHpEMujalpPLNzRWXfwHQqwksrFeipEUlTLeclMwAoktKlfUBJHPsnawvjPhfgewVzKTUfSYtBydXaVIpxWjNKgXANvIoumesCSSvjEGRJosUfuhRRDUuTQwLlJJJDdkVjfSAHqnLxooisBDWuxIhyjJaXDYwdoVPnsllMngNlmkpYOlqXEFIxPqqqgAWdJsOvqppOfyIVjXapzGOrfin... |
#!/usr/bin/env python
'''
gpfilespace wrapper for executing and creating filespace/tablespace
'''
############################################################################
import os
import re
import tinctest
from gppylib.commands.base import Command
from mpp.lib.PSQL import PSQL
from mpp.lib.config import GPDBConf... |
"""Testing the taxi class which has inherited its data from the car class"""
from prac_08.taxi import Taxi
def main():
my_taxi = Taxi('', '')
my_taxi.name = 'Prius 1'
my_taxi.fuel = 100
my_taxi.drive(40)
print(my_taxi)
print('Fare: ${}'.format(my_taxi.get_fare()))
my_taxi.start_fare()
... |
from planar import Vec2
from .shapes import Circle, BoundingBox, Polygon
def bbox_contains_circle(bbox, circle):
c_radius_2 = 2 * circle.radius
if bbox.height < c_radius_2 or bbox.width < c_radius_2:
return False
# Little simpler to checking bboxes
inflated = bbox.inflate(-circle.radius * 2)
... |
from .LinearRegressor import LinearRegressor
from .Matrix import Matrix
from .NeuralNetwork import NeuralNetwork
from . import activations
from . import stats |
from django.utils.translation import ugettext_lazy as _
from wagtail.core.models import Page
from wagtail.core.fields import StreamField
from wagtail.admin.edit_handlers import StreamFieldPanel
from .blocks import PageHomeStreamBlock
class PageHome(Page):
# page fields
body = StreamField(PageHomeStreamBlock... |
"""
听着音乐打飞机
这节视频主要讲的是飞机大战的游戏款框架的搭建
我们的目标是 使用面向对象 设计我们飞机大战的游戏类
所以我们需要先来明确我们主程序的职责
在这里我把程序分为两个模块 一个是主程序模块
一个是精灵模块(主要有两个功能 1 工具类 2 设计一些精灵类
包括英雄类 敌机类 背景精灵类 子弹类等等等
"""
# 要使用pygame打飞机 必须先导入pyagme模块
#之前我们学过导入模块有两种方式
#1 在这里我是用第一种
import pygame
#2
#from pygame import *
from plane_sprites import *
# 我先写在这里
# 初始化
pygame.m... |
"""
MIT LICENSE
https://github.com/gtalarico/ironpython-stubs
Gui Talarico
-----------------------------------------------------------------
This file is intended to be executed from within Civil 3D.
Takes about 3 min
"""
import clr
import sys
sys.path.append(r'C:\Program Files (x86)\IronPython 2.7\Lib')
import os
... |
from NXController import Controller
import time, datetime
# 過日
def change_day(ctr, isSaved, current_date):
# 判斷目前日期是否為主機的最大天數
if current_date.year == 2060 and current_date.month == 12 and current_date.day == 31:
ctr.A()
# 將目前時間調至 2000/1/1
if not isSaved:
for i in range(5):
... |
from __future__ import absolute_import
from keras.layers.convolutional import Conv1D
from keras.engine import Layer
from keras.engine import InputSpec
from keras.utils import conv_utils
from keras import backend as K
from keras import initializers
import numpy as np
class Conv1DTranspose(Conv1D):
"""1D analog of... |
import csv,sys,re
Subjects_offered= {}
Subjectsls = []
Menu = {0 : "Exit",1 : "Read data info from dataset",2 : "Show all the result",3 : "Search by exact school name",4 : "Search school that contains the following word",
5 : "Display all the subject offer",6: "Search school that offer the subject search"}
def ... |
'''
aabbabba
1. state function dp[left][right] 指的是substring left ~ right是否是palindrome
2. 每一个字串自己是palindrome, dp[i][i] = 1
3. 'bab'为例子 dp[3][5] 首尾相等,那么我们得判断 中间的是不是palindrome,则判断dp[4][4], 【a】这个位置,
我们发觉我们需要未来的信息,则我们可以bottom up来坐这个dp
transfer: s[left] == s[right] and right - left < 2 or dp[left + 1][right - 1]:
... |
"""New Job Command."""
from masonite.commands import BaseScaffoldCommand
class JobCommand(BaseScaffoldCommand):
"""
Creates a new Job.
job
{name : Name of the job you want to create}
"""
scaffold_name = 'Job'
template = '/masonite/snippets/scaffold/job'
base_directory = 'app/jobs... |
import codecs
f=codecs.open("a.txt","r","utf-8")
fileList=f.readlines()
for line in fileList:
l=line.strip().split('\t')
f2=codecs.open(l[1],"w","utf-8")
f2.write(l[0])
|
import warnings
import os
import numpy
import torch
from . import networks
from utils.io_utils import empty_cache
class rter:
warnings.filterwarnings("ignore")
# torch.backends.cudnn.enabled = True
# torch.backends.cudnn.benchmark = True
torch.set_grad_enabled(False)
def __init__(self, height: ... |
import streamlit as st
import psycopg2
import inspect
import sys
import os
import importlib
import functions.fn_db as fn_db
import functions.fn_plot as fn_plot
import pandas as pd
import numpy as np
import webbrowser
import altair as alt
import markdown
import base64
def write(dispdf):
#PAPER INFORMATION
s... |
import sys
sys.stdin = open('input.txt', 'r')
T = int(input())
for tc in range(1, T+1):
# N : 2차원 크기 N x N
# K : 내가 원하는 단어길이
N, K = map(int, input().split())
puzzle = [list(map(int, input().split()) for _ in range(N))]
ans = 0
for i in range(N):
cnt = 0
# 행 검사
for j ... |
import os
import gdown
import cv2
import pandas as pd
from deepface.detectors import OpenCvWrapper
from deepface.commons import functions
# pylint: disable=line-too-long
def build_model():
home = functions.get_deepface_home()
# model structure
if os.path.isfile(home + "/.deepface/weights/deploy.prototx... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2017-09-30 09:50
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('tushareapi', '0004_reportdata'),
]
operations = [
migrations.RenameField(
... |
import random
import json
logfichier = ''
############### INPUT USER : FICHIER, TAILLE MAX GROUPE #################
fichier = input('Nom du fichier qui contient la liste des prénoms :\n')
nbrpersonnemax = int(input('Entrez la taille maximum des groupes :\n'))
logfichier += 'Les paramètres (nom de fichier + taille ma... |
import tensorflow as tf
import numpy as np
import PIL.Image
import time
import functools
import matplotlib.pyplot as plt
import matplotlib as mpl
import tensorflow_hub as hub
def tensor_to_image(tensor):
tensor = tensor*255
tensor = np.array(tensor, dtype=np.uint8)
if np.ndim(tensor)>3:
assert te... |
class Counter_Imposter():
"""
bare bone imposter of counter container in python
for the purpose of testing things
"""
def __init__(self):
self.counter = {}
def __getitem__(self, key):
"""
will get the item if present in the
container, else will return 0
"""
if key in self.counter:
return self.cou... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-06-05 07:11
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('home', '0030_auto_20170601_2232'),
]
operations = [
... |
from amazon.amazonTest.POM.locators import MainPageLocators
from amazon.amazonTest.POM.actions.actionPage import Actions
class CategoryPage(Actions):
def is_searching_page(self):
self.assertEqual(MainPageLocators.IS_SEARCHING_PAGE, self.driver.current_url)
def pagination(self):
Actions.click... |
# USAGE
# python color_spaces.py --image mai-ngoc.jpg
# import the necessary packages
import argparse
import cv2
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the image")
args = vars(ap.parse_args())
# load the ori... |
import numpy as np
class MarkovModel:
def __init__(self, k):
"""
Initialize a Markov model with a particular prefix length
Parameters
----------
k: int
Length of prefix to use
"""
self.k = k
## TODO: Setup any other member variabl... |
import math
import random
import matplotlib.pyplot as plt
def geray(lista):
dataacu=[]
sum=0.0
for i in range(0,len(lista)):
sum=sum+1
dataacu.append(sum)
return dataacu
po=100000
ca=1
su=po-ca
p=0.7
cur=0
pcua=0.1
curados=[]
curados.append(cur)
pobla=[]
pobla.append(po)
Casos=[]
Caso... |
class MyClass:
"""
Class description
"""
def __init__(self, value):
self.value = value
def __str__(self):
return "MyClass[{}]".format(self.value)
def func1(self):
"""
Function description
:return: None
"""
print("Hello from func1 with v... |
# Generated by Django 2.1.7 on 2019-02-22 01:55
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('surveys', '0007_survey_welcome_prompt'),
]
operations = [
migrations.AddField(
model_name='ques... |
# Write a function to find the longest common prefix string amongst an array of strings.
# If there is no common prefix, return an empty string "".
# Input: strs = ["flower","flow","flight"]
# Output: "fl"
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
... |
#importing packages to stream to plot.ly and work with surface Temp-sensors
#tutorial: https://plot.ly/raspberry-pi/tmp36-temperature-tutorial/
import plotly.plotly as py
import json
import time
import datetime
import os
import glob
import urllib2
import re
#reading file with user credentials and streaming tokens for ... |
import argparse
from loader import BioDataset
from torch_geometric.data import DataLoader
from torch_geometric.utils import dropout_adj
from torch_geometric.nn.inits import uniform
from torch_geometric.nn import global_mean_pool
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as ... |
import json
import traceback
from typing import List
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ValidationError
from django.db.models import Count, Subquery, OuterRef, \
IntegerField, Q
from django.shortcuts import render
from django.template.loader import render_t... |
import sys, argparse, os ,datetime,logging, uuid
import multiprocessing as mp
from . import config
ID = str(uuid.uuid4()).split('-')[0]
def loadFrame(fin):
nomap=0
mis=0
exonFrameDict={}
for l in open(fin):
ls=l.strip().split('|')
if len(ls)>5: #no hits
if (float(ls[1])/3)*0.4>float(ls[11]): #identities to... |
from optparse import OptionParser
from ROOT import *
import sys
import ConfigParser
import time
import gc
import math
import CMS_lumi, tdrstyle
import array
gStyle.SetGridColor(kGray)
gStyle.SetOptStat(kFALSE)
gStyle.SetPadTopMargin(0.07)
gStyle.SetPadBottomMargin(0.13)
gStyle.SetPadLeftMargin(0.14)
gStyle.SetPadRight... |
#!/usr/bin/env python
"""Practical of list comprehensions"""
__author__ = 'Xiaosheng Luo (xiaosheng.luo18@imperial.ac.uk)'
__version__ = '0.0.1'
birds = ( ('Passerculus sandwichensis','Savannah sparrow',18.7),
('Delichon urbica','House martin',19),
('Junco phaeonotus','Yellow-eyed junco',19.5),
... |
class Solution(object):
def integerBreak(self, n):
"""
:type n: int
:rtype: int
"""
if n == 2:
return 1
elif n == 3:
return 2
a = n // 3
b = n % 3
if b == 1:
a = a - 1
b = 4
elif b == 2:
... |
# -*- test-case-name: twisted.words.test -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
An implementation of the OSCAR protocol, which AIM and ICQ use to communcate.
Maintainer: Paul Swartz
"""
import struct
import string
import socket
import random
import types
impo... |
from django.urls import path, re_path
from .views import (
OrderDetailView,
OrderPayView,
)
urlpatterns = [
re_path(r'^o[0-9A-Za-z_\-]{25}/(?P<order_id>[\w-]+)[0-9A-Za-z_\-]{25}/$', OrderDetailView.as_view(), name='order-detail'),
re_path(r'^o[0-9A-Za-z_\-]{25}/pay[0-9A-Za-z_\-]{25}/(?P<order_id>[\w-]... |
from .netdev import NetDev
from .topology import TopologyMember
class Veth(TopologyMember):
REF = 'veth'
DESC = {'title': 'Virtual Ethernet (Veth) with IPv4 addresses'}
SCHEMA = {
'type': 'object',
'additionalProperties': False,
'required': ['name', 'dev1', 'dev2'],
'proper... |
import pygame
# Colores
NEGRO = ( 0, 0, 0)
BLANCO = ( 255, 255, 255)
AZUL = ( 0, 0, 255)
ROJO = ( 255, 0, 0)
VERDE = ( 0, 255, 0)
# Dimensiones pantalla
ANCHO = 6800
ALTO = 470
def recortar2(imagen, inicio, anchos, altos):
sp_col = len(anchos)
sp_fil = len(altos)
... |
import pandas
import matplotlib.pyplot as plt
df = pandas.read_csv('sample2.csv')
# This table has 3 columns: Office, Year, Sales
print df.columns
# It's really easy to query data with Pandas:
print df[(df['Office'] == 'Stockholm') & (df['Sales'] > 260)]
# It's also easy to do aggregations...
aggregated_sales = df... |
"""
Dynamic Programming
dp[i][j] = the edge length of maximum square with cell(i,j) as the right bottom corner.
if dp[i][j] = 1, then it can at least form a 1 unit square;
then if dp[i-1][j-1] >= 1 , it means there is a square ending at matrix[i-1][j-1];
if we can have a horizontal edge ending at matrix[i][j], and a ve... |
# Generated by Django 2.2 on 2020-02-06 13:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('publications', '0008_auto_20200206_0950'),
]
operations = [
migrations.CreateModel(
name='OtherPublication',
fields=[
... |
from cs50 import *
from enum import Enum
class CreditCard(Enum):
AmericanExpress = 'AMEX'
MasterCard = 'MASTERCARD'
Visa = 'VISA'
Undefined = ''
CARD_LEN = {
CreditCard.AmericanExpress: [15],
CreditCard.MasterCard: [16],
CreditCard.Visa: [13, 16]
}
CARD_PREFIX = {
CreditCard.AmericanE... |
import cv2,time
video=cv2.VideoCapture(0)
# two outputs, check and frame
# Capture frame-by-frame.returns a bool (True/False). If frame is read correctly, it will be True. So you can check end of
# the video by checking this return(check) value.
check,frame=video.read()
print("===check===")
print(check)
print("===fr... |
import sys
import json
import time
import uuid
from flask import Flask, request, jsonify
from common.skadnetwork import SKAdNetwork
app = Flask(__name__)
ADNET_ID = u'<ADNET_ID>'
CAMPAIGN_ID = u'1' # Should be between 1-100
TARGET_ITUNES_ID = u'1499436635' # The product you want to advertise
@app.route('/rtb/2.5',... |
import classifier
#import pytest
import status_test
import os
train_data = '/home/fairoos/naive_byaes/pytest_data/training_data/'
test_data = '/home/fairoos/naive_byaes/pytest_data/testing_data'
def test_words_in_a_folder():
path = '/home/fairoos/naive_byaes/pytest_data/training_data/sports data'
assert class... |
import random
import time
from types import SimpleNamespace
import numpy as np
from cli import _is_latest_version
from jina.clients.python import PyClient
from jina.drivers.querylang.queryset.dunderkey import dunder_get
from jina.helper import cached_property
from jina.logging.profile import TimeContext
from jina.pro... |
import random #取随机数
answer = random.randint(1, 100)
counter = 0
while True:
counter += 1
number = int(input('请输入: '))
if counter <=4:
if number < answer:
print('大一点')
if number > answer:
print('小一点')
if number == answer:
print('恭喜你猜对了!')
... |
import clock
import datetime
def is_evening(iso8601_time_string, longitude, latitude):
sunrise, sunset = \
clock.sunrise_sunset(iso8601_time_string, longitude, latitude)
Y = int(sunrise[0:4])
M = int(sunrise[5:7])
D = int(sunrise[8:10])
h = int(sunrise[11:13])
m = int(sunrise[14:16])
s = in... |
# Generated by Django 2.0.3 on 2018-03-25 17:41
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('games', '0004_auto_20180325_1739'),
]
operations = [
migrations.DeleteModel(
name='AbstractChessPiece',
),
migrations.Re... |
from flask import Flask
from file_utils import download_file, delete_file
import os
import requests
from keras import backend as K
#load model
import vgg16_places_365_model
if not os.path.exists('uploads'):
os.mkdir('uploads')
app = Flask(__name__)
@app.route('/<filename>')
def predict(filename):
try:
#Bef... |
from django.conf.urls import include, url
urlpatterns = [
url(r'^$', 'django.contrib.auth.views.login' , {'template_name':'home/index.html'}),
url(r'^$' , home_index)
]
|
"""
Python 3.8.0
列出图片的信息
大约耗时10分钟
Jan 19, 2020
Hu Xiangyou
"""
print(__file__.rsplit("\\",1)[1])
print(__doc__)
import requests
from urllib import parse
import time
import openpyxl
import second2days
filepath="imagelist.xlsx"
url="https://common.moegirl.org/api.php"
params={'action':'query','format':'json','prop':'... |
from tkinter import*
#from PIL import Image,ImageTk
from tkinter import ttk
import random
from time import strftime
from datetime import datetime
#import mysql.connector
from tkinter import messagebox
import psycopg2
class Details:
def __init__(self, root):
self.root = root
self.root.title("Hotel ... |
money_amount = int(input('Enter your money emount : '))
if money_amount >= 200:
quantyty_of_200 = money_amount // 200
print('Кількість 200 гривневих купюр ', quantyty_of_200)
money_amount = money_amount - quantyty_of_200 * 200
if money_amount >= 100:
quantyty_of_100 = money_amount // 100
prin... |
def Factorial(n):
n=int(n)
if n<0:
print("错误信息")
elif n==0:
print("1")
else:
m=n-1
while m>0:
n=n*m
m=m-1
return n
import math
A=Factorial(10)
B=Factorial(8)
C=Factorial(7)
D=Factorial(6)
X=A/B
Y=B/C
Z=C/D
result=X*Y*Z
print("不同的选法有",int(resu... |
import tensorflow as tf
from datasets.tabular_dataset import TfrecordBuilder, TabularDataSet
import pandas as pd
from models.lr import LR
from models.dcn import DCN
from sklearn.preprocessing import LabelEncoder
from utils.toolbox import build_scheme_dict
from sklearn.preprocessing import MinMaxScaler
def main(_):
... |
import numpy as np
from matplotlib import pyplot as plt
import csv
import pdb
from matplotlib import colors as colors
import sys
pickup_xs, pickup_ys, dropoff_xs, dropoff_ys = [], [], [], []
#make commandline later:
# filename = 'trips_from_lazy_drivers_cleaned.csv'
# filename = 'trips_from_lazy_drivers_frequent.csv'... |
import os
import logging
import time
import subprocess
import numpy as np
from pathlib import Path
from functools import wraps
def create_directory_if_not_exist(path):
"""Create directory
Args:
path (str): If the dir of given path not exist,
create it
"""
directory = os.path.dirn... |
from psana import DataSource, Detector
#import psana
#psana.setOption('psana.calib-dir', './calib')
#event_keys -d exp=xpptut15:run=460 -m3
#event_keys -d exp=mfxls4916:run=298 -m3
dsname = 'exp=mfxls4916:run=298' # '/reg/d/psdm/xpp/xpptut15/xtc/*'
#dsname = '/reg/g/psdm/detector/data_test/types/0028-NoDetector.... |
from django.test import TestCase
from .models import Ticket, Event
# Create your tests here.
class TestEvent(TestCase):
@classmethod
def setUpTestData(cls):
Event.objects.create(name='Test Event', venue='Lviv', description='abcdefg')
def test_name_max_length(self):
event = Event.objects... |
from __future__ import print_function
import tensorflow as tf
from autoencoder_trainer import train_autoencoder
training_dir = "/Users/afq/Google Drive/networks/"
data_dir = "/Users/afq/Documents/Dropbox/ML/primaryautoencoder/data_files/"
#data_dir = "/Users/afq/Dropbox/ML/primaryautoencoder/data_files"
if __name__=="... |
# A function that removes one occurrence of a given item from a list w/o using .pop() or .remove()
# If the item is not present in the list, output should be ‘The item is not in the list’.
def remove_item(list_items, item_to_remove):
''' Remove first occurrence of item from list
Returns: if the item is in the ... |
#!/usr/bin/env python
"""
Python source code - describe the code here
"""
import time
st = time.time()
import sys
import re
def same_row(i,j): return (i/9 == j/9)
def same_col(i,j): return (i-j) % 9 == 0
def same_block(i,j): return (i/27 == j/27 and i%9/3 == j%9/3)
total = 0
def r(a):
i = a.find('0')
if i... |
from source.task_runner.tasks.interface import TaskInterface
class MergerTask(TaskInterface):
items = TaskInterface.items + (
'quest_id',
'query_id',
'split_kernel_id',
'is_past',
'sub_kernel_ids',
'task_config',
)
def __init__(self, job_id, customer, quest... |
import datetime as dt
from freezegun import freeze_time
from model_mommy import mommy
import pytest
from blog.models import Post
pytestmark = pytest.mark.django_db
def test_published_posts_only_returns_those_with_published_status():
post = mommy.make('blog.Post',status=Post.PUBLISHED)
mommy.make('blog.Post... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.