text stringlengths 8 6.05M |
|---|
# Generated by Django 2.0 on 2017-12-21 14:57
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('main', '0030_auto_20171220_1707'),
]
operations = [
migrations.RemoveField(
model_name='userprofi... |
#!/usr/bin/env python3
import argparse
import cmd
import os
import re
import shutil
import sys
DIRECTORY_REGEX = re.compile(r'^(.+) v(\d{3}) c(\d{3}[a-z]?)$')
ARCHIVE_REGEX = re.compile(r'^(.+) v(\d{3}) c(\d{3}[a-z]?)\.(cbz)$')
PAGE_REGEX = re.compile(r'^(.+) v(\d{3}) c(\d{3}[a-z]?) p(\d{3}(?:-\d{3})?[a-... |
"""
The Sonar API is defined here to interact with the sonar database and perform
the CLI tasks.
"""
import logging
import os
import pprint
import shutil
import sys
import textwrap
from distutils.dir_util import copy_tree
from pathlib import Path
import toml
import sonar.database
import sonar.include
from sonar.core... |
from django.urls import path
from . import views
# specific paths with view names to call functions to perform actions on the views.py
urlpatterns = [
path("", views.index,name="index"),
path('music/', views.music, name="index"),
path('John_Legend', views.John_Legend, name="index"),
path('Brain_Mckni... |
#
# trajectory_latent_tools.py
#
# Tools for training NNs to create
# latents of trajectories and then summarize
# them to describe policies.
# Inspired by "Robust Imitation of Diverse Behaviors":
# [1] https://arxiv.org/abs/1707.02747
import random
import numpy as np
import torch as th
# Structure of the trajector... |
import pandas as pd
import util
from keras.preprocessing import text, sequence
import pickle
import numpy as np
print('loading data...')
df_train = pd.read_csv(util.train_data)
df_test = pd.read_csv(util.test_data)
df_train['comment_text'] = df_train['comment_text'].fillna('UN')
df_test['comment_text'] = df_... |
from tod import app
app.run(debug=True)
|
import os
import shlex, subprocess
import sys
def execute():
wd=os.getcwd()
os.environ['SIMUL']="C:/Simul/master/Simul"
#os.environ['ue.bEnableFastIteration']='1'
#os.environ['ue.bUseUnityBuild']='false'
os.environ['QTDIR']=os.environ['DROPBOX']+'/Qt/qt5_msvc2012_64_opengl'
os.environ['SIMUL_BUILD']='1'
os.env... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 16 18:58:05 2019
@author: gustavo.fonseca
"""
import pandas as pd
import funcs as f1
#Tarefa 17
#Função utilizada no arquivo 'funcs.py'
#Teste com as colunas 'Renda (R$)' e 'Público' da tabela do Campeonato Brasileiro.
t=pd.read_csv('file:///C:/... |
import torch
import scipy.optimize
import numpy as np
def local_OT(D, window = 0):
window = window
p = D.shape[1]; m = D.shape[2] # p < m, e.g., p = 10, m = 20
# construct the cx, ax=b
x = torch.rand([10,p*m])
A = torch.zeros([p,p*m])
b = torch.ones([p])
for i in range(p):
A[i, (i)... |
from state import State
import random
import timeit
import matplotlib.pyplot as plt
import statistics as stats
# If the disks are in different pins, we name the state first with where the big one is
statesString = ["b1s1", "b1s2", "b1s3", "s2b2", "s3b3", "b3s2", "b2s3", "b3s3", "b2s2", "b3s1", "b2s1", "s1b1"]
obeyProb... |
# PARAMETERS
#################################################
# DATA
resize_image_height_to = 128
resize_image_width_to = 128
smooth = 1.0
test_data_fraction = 0.15
# COMPUTATION
number_of_epochs = 40
batch_size = 80
# MODEL
##############################... |
import requests
import re
headers ={
"Accept": "application / json, text / javascript, * / *; q = 0.01",
"User - Agent": "Mozilla / 5.0(WindowsNT10.0;Win64;x64;rv:61.0) Gecko / 20100101Firefox / 61.0",
"X - Requested - With": "XMLHttpRequest"
}
s = requests.session()
# print(s.cookies)
c = requests.cooki... |
# @Title: 自除数 (Self Dividing Numbers)
# @Author: 2464512446@qq.com
# @Date: 2019-09-28 17:14:52
# @Runtime: 28 ms
# @Memory: 11.6 MB
class Solution(object):
def selfDividingNumbers(self, left, right):
ans = []
for num in range(left,right + 1):
copy = num
while copy > 0:
... |
import os
resourcesFolder = os.path.join(os.getcwd(), 'source', 'resources')
imgPath = os.path.join(resourcesFolder, 'pixelToolbarIcon.png')
size(512, 512)
im = ImageObject()
with im:
scale(29.01)
image(imgPath, (-1.29, -1.31))
steps = 10
w = h = width() / (steps-1)
r = w * 0.5
for i in range(steps):
fo... |
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution:
def copyRandomList(self, head):
#make copy of each node,link them in a single list.
if not head: return None
ptr = head
while ptr:
... |
import os
import pandas as pd
from requests import get
from settings import INPUT_DATA_PATH
HOSPITAL_DIRPATH = os.path.join(INPUT_DATA_PATH, "hospitalisation_data")
URL = "https://opendata.ecdc.europa.eu/covid19/hospitalicuadmissionrates/csv/data.csv"
COUNTRIES = {"france", "belgium", "italy", "sweden", "uk", "spa... |
# Root finding with bisection method
from math import *
def sign(y):
if y>0: return 1
if y<0: return -1
return 0
def bisection(f,a,b,tol):
sfa = sign(f(a)) # so we won't have to call f or sign multiple times at a or b
sfb = sign(f(b))
if sfa == 0: return a # a is a root
if sfb == 0: return b # b is a root
... |
# -*- coding:utf-8 -*-
import pandas as pd
import matplotlib.pyplot as plt
train_data_path = "/Users/withheart/Documents/studys/senmantic/data/ai_challenger_sentiment_analysis_trainingset_20180816/sentiment_analysis_trainingset.csv"
# 加载数据
def load_data_from_csv(file_name, header=0, encoding="utf-8"):
data_df = ... |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 7 00:32:20 2018
@author: home
"""
def solution(s):
if s == '':
return True
if len(s) % 2 == 1:
return False
else:
xiaoL = '('
xiaoR = ')'
zhongL = '['
zhongR = ']'
daL = '{'
daR = '}'
... |
"""
Basic Validation of PowerballGame Validation + Earnings Logic
"""
from django.test import TestCase
from yoolotto.lottery.game.base import LotteryResultsInvalidException, LotteryPlayInvalidException
from yoolotto.lottery.game.manager import GameManager
class PowerballGameTest(TestCase):
HANDLER = GameManager.g... |
graph = { 'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'F']),
'D': set(['B']),
'E': set(['B', 'F']),
'F': set(['C', 'E'])}
graph2 = { 1: set([2, 3]),
2: set([1, 4, 5]),
3: set([1,5,7]),
4: set([2]),
5: set([2,3,6]),
6: set([5,7]),
7: set([3,6])}
... |
#-*- coding:utf-8 -*-
import types
from functools import wraps
import constants
def _raise_when_models_empty(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
if not self.registered_models:
raise RuntimeError(u"未注册models")
return func(self, *args, **kwargs)
return wrappe... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('submit_exercise', views.submit_exercise, name='submit_exercise'),
path('get_exercise', views.get_exercise, name='get_exercise'),
path('set_journal', views.set_journal, name='set_journal'),
p... |
#!/usr/bin/python
### FOR THIS PROGRAM, CLASS SLIDES WHERE USED AS TEMPLATE ####
import sys
sys.path.append("/Users/ianhoyos/biopython-1.70")
import Bio
from Bio.Blast.Applications import NcbiblastpCommandline
from Bio.Blast import NCBIStandalone
### Fixed path to where blastp is located ###
### The Database utili... |
class Solution:
def repeatedSubstringPattern(self, s):
"""
:type s: str
:rtype: bool
"""
s1 = s+s
sub = s1[1:-1]
if s in sub:
return True
else:
return False
print(Solution().repeatedSubstringPattern('abab')) |
#!/usr/bin/python
# SPDX-License-Identifier: GPL-2.0-only
#
# Tool for analyzing boot timing
# Copyright (c) 2013, Intel Corporation.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms and conditions of the GNU General Public License,
# version 2, as published by the Free Soft... |
# encoding: cinje
: from .template import page
: def siteoptionstemplate title, ctx, updated=False
: using page title, ctx, lang="en"
<h3 style='text-align: center;'>Site Options ${'(Saved)' if updated else ''}</h3>
<form style='width: 50vw; margin: 0 auto;' action='/siteoptions' method='post'>
... |
from collections import deque
import os
import numpy as np
# Define a simple TreeNode struct/record.
class TreeNode():
def __init__(self, x, parent, children, id):
self.x = x
self.parent = parent
self.children = children
self.id = id
# Parameters
MAX_TREE_SIZE = 10000
GOAL_SAMPLE_P... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
# from django.contrib.auth.models import AbstractUser
# from django.core.urlresolvers import reverse
# from django.db import models
# from django.utils.encoding import python_2_unicode_compatible
# from django.utils.translation import uge... |
import csv
from ..utility import nanoseconds_since_midnight as labtime
import os
from datetime import datetime
from .row_formatters import *
author = 'hasan ali demirci'
# TODO: move this to redis. There are many good reasons to do that.
logs_folder = 'hft_bcs/hft_logging/logs/'
class SessionEvents:
dispatch =... |
import pygame
from pygame.locals import *
import pytmx
from pytmx import TiledImageLayer
from pytmx import TiledObjectGroup
from pytmx import TiledTileLayer
from pytmx.util_pygame import load_pygame
class Mapa():
def __init__(self):
self.mapa = load_pygame("sprites/street.tmx") # LE O MAPA
self.ma... |
from django.urls import path
from . import views
urlpatterns = [
path('radio/', views.radio_form_method),
path('radio_value/', views.radio_form_method2),
path('views1/',views.template_view_method),
path('views2/',views.Template_view_class.as_view()),
path('list/' , views.Info... |
#-------------------------------------
# Unit Test
#-----------------------------------
import unittest
from mspack import msmath
from mspack import msstring
class MsPackMsMathTestCase(unittest.testCase):
def test_sum(self):
sum = msmath.sum(8, 12)
self.assertEqual(sum, 20)
if __name__ == ... |
import pandas as pd
import numpy as np
def small_df():
return pd.DataFrame(
{
"a": [1, 2, 3, 4, 5],
"b": ["v", "W", "X", "Y", "Z"],
"c": [1.5, 2.5, 3.5, 4.5, 5.5],
"d": [
np.datetime64("now"),
np.datetime64("now"),
... |
from os import listdir
from os.path import join as path_join
from subprocess import check_output
inDir=r'.\csv' #Directory holding input files
outDir=r'.\json' #Directory holding output files
#Change to whatever version your system is running, remove the folder if on Path
cycloneAddress=r'.\cyclonedx-win-x64'... |
number = "9,223,372,036,854,775,807"
cleanedNumber = ''
for char in number:
if char in '0123456789':
cleanedNumber = cleanedNumber + char
newNumber = int(cleanedNumber)
print("The number is {}",format(newNumber))
for state in ["not pinin'", "no more", "a stiff", "befeft of lift"]:
print("This par... |
from . import bp
from app.erros import bad_request
from app import cross_origin,db
from flask import jsonify,request
from app.authenticate import check_token_dec
from app.models import Cores,Direcao,CoresDirecao
@bp.route('/',methods=['GET','POST'])
@cross_origin()
@check_token_dec
def direcao_():
try:
#p... |
from django.db import models
class ActionPermission(models.Model):
"""
This model only serves to provide a content type for action permissions.
When this table is created, Django makes a content type for the model.
We associate all auto-generated action permissions with this content type
in order... |
# https://leetcode.com/problems/longest-substring-without-repeating-characters/
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
max_len = 0
dummy = []
x = 0
while x < len(s):
if s[x] not in dummy:
dummy.append(s[x])
... |
def getPossibleSuffixes(s):
if len(s) == 5:
print(0)
return
possible_suffixes = s[5:len(s)]
suffixes = []
helper_hash = {}
suffix_starts = [0 for x in range(len(possible_suffixes))]
prev_2 = ["" for x in range(len(possible_suffixes))]
suffix_starts[-1] = 1
for i in range(... |
Author = 'Liu Lei'
import json
#def sayhi(name):
# print("hello",name)
info={
'name':'liulei',
'age':22
}
f=open("text.txt","r")
data=json.loads(f.read())
print(data) |
#Interpolation is used to change the original size of the image
#We can increase the width and height of the image
#There are almost 5 types of interpolation
#INTER_AREA, INTER_CUBIC, INTER_NEAREST, INTER_LANCZOS4, INTER_LINEAR
import cv2
import numpy as np
#to load an image
image = cv2.imread('C:/Users/LENOVO IDEA... |
#in this example, the input was "venit"
str = "Venit"
#I then evaluate whether the ending is "it", then add "imus" to conjugate it
if str[-2:] == "i":
print("str" + "imus")
print("Error: Not an -it verb") |
print ("Digite uma letra e ela se´ra correspondente a um número do vetor")
import string
letras = list(string.ascii_lowercase)
letra =input('Digite uma letra: ')
for i in range(len(letras)):
if(letra==letras[i]):
print(i)
|
# -*- coding: utf-8 -*-
from collections import defaultdict
import pprint
import re
_re_num = re.compile(r'\s(?P<num>\d+)\s+(?P<name>(RPL|ERR)_\w+)\s*(?P<_>.*)')
_re_mask = re.compile(r'^\s{24,25}(?P<_>("(<|:).*|\S.*"$))')
def main():
print('Parsing rfc file...')
item = None
items = []
out = open('i... |
import pygame
from pygame import mouse
from pygame.constants import MOUSEBUTTONDOWN
from pygame.event import clear, get
import random
class Text:
def score_text():
font = pygame.font.Font("freesansbold.ttf",32)
text = font.render(str(Game.score),True,(255,255,255))
Game.screen.blit(... |
room = [line.strip() for line in open('in').readlines()]
next_room = [[None] * len(room[0]) for _ in range(len(room))]
print('\n'.join(room))
changes = 1
while changes != 0:
changes = 0
for row, line in enumerate(room):
for col, seat in enumerate(line):
if seat == '.' or seat is None:
next_room[r... |
from backprop import *
from handleimages import *
if __name__ == '__main__':
images = all_images()
pat = [[make_input(i), make_output(i)] for i in images]
|
__author__ = 'artemiibezguzikov'
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('low-contrast.png')
img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
hist, bins = np.histogram(img.flatten(), 256, [0, 256])
cdf = hist.cumsum()
cdf_m = np.ma.masked_equal(cdf,0)
cdf_m = (cdf_m - cdf_m.mi... |
'''
Словари
'''
d1 = {
"day": 18,
"month": 6,
"year": 1983
}
d2 = dict(bananas=3,apples=5,oranges=2,bag="basket")
d3 = dict([("street","Kronverksky pr."), ("house",
49)])
d4 = dict.fromkeys(["1","2"], 3)
print("Dict d1 = ", d1)
print("Dict d2 by dict()= ", d2)
print("Dict d3 by dict([])= ", d3)
print("Dict d4 by fr... |
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
def gs_save(driver):
time.sleep(1)
driver.find_element_by_xpath(".//*[@id='tbSave']/input").click()
time.sleep(10)
# print... |
import csv
import openpyxl
import xlrd
from collections import defaultdict
from scraper.download_zip import *
import os
class data_processor():
def __init__(self):
self.upzipped_file = download_zip()
#os.chdir(cwd)
pass
def parse_txt_file(self):
#input_txt = open('Data/foidevA... |
def submask(f):
print("subnetting now...")
return f
def calcsubmask(f) :
print("calculating now...")
if f == 24:
sm = "255.255.255.0"
elif f == 25:
sm = "255.255.255.128"
elif f==26:
sm = "255.255.255.192"
elif f==27:
sm = "255.255.255.224"
return sm
#su... |
#!/usr/bin/python
import os
import sys
import struct
def hexdump(data, length):
print "hexdump(%d):" % length,
for i in range(length):
print "%02x" % ord(data[i]),
print "\n"
def skip(data, length):
return data[length:]
def parse(data, length):
if len(data) == 0:
raise Exception("premature end in marker (e... |
#!/usr/bin/env python
#!-*-coding:utf-8 -*-
# Time :2020/5/19 14:13
# Author : zhoudong
# File : gmphd.py
import numpy as np
from copy import deepcopy
from util.gm_component import *
myfloat = np.float32
class Gmphd:
def __init__(self, model):
"""
:param birthgmm: GMM 的新生目标
:pa... |
#sıralama algoritması (bubble sort horon tepen video)
#a = [200, 3, 511, 72, 11, 13, 17, 19, 23, 249, 31, 37, 41, 43, 47]
#for j in range(len(a)-1):
# for i in range(len(a)-1):
# if(a[i]>a[i+1]):
# a[i], a[i+1] = a[i+1], a[i]
#print(a)
#ilk sıralamada en büyük değer herzaman en sağa yerleşir
#en... |
#!/usr/bin/env python3
'''Sends mail to address specified in config'''
import ssl
import smtplib
import email.utils
import email.message
import cfg
ssl_ctx = ssl.create_default_context()
server = smtplib.SMTP(cfg.smtpServer, cfg.smtpServerPort)
if cfg.smtpEncryption == 'ssl' or cfg.smtpEncryption == 'tls':
server.s... |
from rest_framework.decorators import api_view, permission_classes
from django.shortcuts import get_object_or_404
from django.utils import timezone
from rest_framework.response import Response
from .serializers import ItemSerializer, OrderSerializer, OrderItemSerializer
from .models import Item, Order, OrderItem
from r... |
#!/usr/bin/python
#Aplicacao cliente - Versao 7.0
import sys
import socket
import os
import time
#from rsvpclient import Rsvpclient
#host = sys.argv[1] #Endereco do servidor remoto obtido atraves da CLI
host = '10.0.0.8' #Endereco do servidor remoto obtido atraves da CLI
#port = int(sys.argv[2]) #Porta do servid... |
import json
import matplotlib.pyplot as plt
from scipy.stats import pearsonr
import numpy as np
import pandas as pd
plt.rcParams['font.sans-serif'] = ['SimHei']
bits = 2
ax1 = plt.subplot(3, 1, 1)
plt.xlabel("点赞")
plt.ylabel("概率")
ax2 = plt.subplot(3, 1, 2, sharey=ax1)
plt.xlabel("评论")
plt.ylabel("概率")
ax3 = plt.sub... |
import unittest
from safe_cli.api.gnosis_transaction import TransactionService
class TestTransactionService(unittest.TestCase):
def setUp(self) -> None:
self.transaction_service = TransactionService.from_network_number(4) # Rinkeby
self.safe_address = '0x7552Ed65a45E27740a15B8D5415E90d8ca64C109'... |
import scrapy
from yellowpages.items import YellowpagesItem
from scrapy_selenium import SeleniumRequest
class YellowSpider(scrapy.Spider):
name = 'yellow'
allowed_domains = ['yellowpagesofafrica.com']
start_urls = ['https://www.yellowpagesofafrica.com/']
def start_requests(self):
for url in s... |
from django.shortcuts import render
from .models import *
from rest_framework import viewsets,permissions
from .serializers import *
from rest_framework.pagination import LimitOffsetPagination,PageNumberPagination
from .pagination import PostPageNumberPagination
from rest_framework.filters import SearchFilter,OrderingF... |
class Rectangle:
def __init__(self,length, breadth):
self.length = length
self.breadth = breadth
def area(self):
return self.length * self.breadth
@property
def getData(self):
return (self.length, self.breadth)
r1 = Rectangle(10, 20)
print(f"Area = {r1.area()}")
print... |
import json
import re
import discord
def saveFile(Settings : dict, filename : str):
settings_file = open(filename, "w")
settings_file.write(json.dumps(Settings, ensure_ascii=False))
settings_file.close()
def discord_trim(str):
result = []
trimLen = 0
lastLen = 0
while trimLen <= len(str):
... |
from django.conf.urls import url, include
import views
urlpatterns = [
url(r'^index/', views.index),
url(r'^article_page/(?P<article_id>[0-9]+)', views.article_page, name='article_page'),
url(r'^edit_page/(?P<article_id>[0-9]+)', views.edit_page, name='edit_page'),
url(r'^edit_action/', views.edit_acti... |
#!/usr/bin/env python
# coding: utf-8
# 라이브러리 불러오기
from pandas import DataFrame
from datetime import datetime
import os
import cv2
import pyzbar
from pyzbar.pyzbar import decode
from pyzbar.pyzbar import ZBarSymbol
import winsound as ws
# 비프음 함수
def beepsound():
freq = 1000 # range : 37 ~ 32767
dur = 200... |
from datetime import datetime
import re
import csv
import click
def echo(message, quiet):
"""
Print the given message to standard out via click
unless quiet is True.
:param message: the message to print out
:param quiet: don't print the message when this is True
"""
if not quiet:
... |
## Automatically adapted for numpy.oldnumeric Jul 30, 2007 by
import Tkinter
from opengltk.OpenGL import GL
import unittest
import os
import numpy.oldnumeric as Numeric
class OGLTkWidget(Tkinter.Widget, Tkinter.Misc):
def __init__(self, master, cnf={}, expand=1, **kw):
if not kw.has_key('width'): kw['... |
#counties = ["Arapahoe","Denver","Jefferson"]
#if counties[1] == 'Denver':
#print(counties[1])
#temperature = int(input("What is the temperature outside? "))
#if temperature > 80:
# print("Turn on the AC.")
#else:
# print("Open the windows.")
#What is the score?
#score = int(input("What is your test score?... |
# coding=utf-8
try:
# py3
from urllib.request import Request, urlopen, URLError, HTTPError
#from urllib.parse import urlencode
except ImportError:
# py2
from urllib2 import Request, urlopen, URLError, HTTPError
#from urllib import urlencode
import re
import sys
def dataFromUrl(url, waittime):... |
from py2neo import Graph
graph = Graph()
|
s = '\xe5\x86\x96\xe7\x8e\x8b\xe5\xa4\xa7\xe4\xbb\xa4\xe6\x9e\xad\xe4\xba\xba\xe6\x9b\xb0\xe6\x9a\x82\xe5\x86\x96\xe7\x94\xb0\xe5\x85\xb6\xe5\x8f\x97\xe5\xb9\xb4\xe5\x86\x96\xe5\x8d\x81\xe4\xb8\x80'
sss = s.encode('raw_unicode_escape').decode()
print(sss)
""" import base64
import cv2
import numpy as np
import PIL.Image... |
import numpy as np
import cv2
import matplotlib.pyplot as plt
import os
import sys
import math
def skinToneData(img):
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
height, width, channel = hsv.shape
freq = np.zeros((180, 256)) # Hue: 0 - 179 | Sat: 0 - 255
for i in range(height):
for j in r... |
#쉽게 설명한 퀵정렬
#입력:리스트a
#출력:정렬된 새 리스트
def quick_sort(a):
n=len(a)
if n <= 1:
return a
pivot=a[-1]
g1=[]
g2=[]
for i in range(0,n-1):
if a[i]<pivot:
g1.append(a[i])
else:
g2.append(a[i])
return quick_sort(g1)+[pivot]+quick_sort(g2)
d=[6,8,3,... |
from TopEFT.Analysis.MCBasedEstimate import MCBasedEstimate
class estimatorList:
def __init__(self, setup, samples=['TTZ', 'WZ', 'TTX', 'TTW', 'ZG', 'rare', 'pseudoData', 'ZZ', 'XG','ZZZ','WZZ','WWZ','TZQ']): #rare_noZZ
for s in samples:
setattr(self, s, MCBasedEstimate(name="%s_%s... |
import time
import sys
import json
import os
from vectors import Vector
def step(cells, lines, columns):
create = []
die = []
for x in range(columns):
for y in range(lines):
position = (x, y)
neighbors = count_neighbors(position, cells)
is_cell = position in ce... |
'''
叮咚提示音
使用ha的tts服务进行回复
'''
import ha_api
def on_wake( va_config ):
"""唤醒后的处理函数"""
ha_api.play_audio_file(va_config["media_player"], "ding.wav")
def on_command( va_config ):
"""读入语音命定后的处理函数"""
ha_api.play_audio_file(va_config["media_player"], "dong.wav")
def on_react( speech_in, va_config ):
"""获得语音命令文本后... |
#########################################################################
# coding=utf-8
# File Name: sax.py
# Author: aaronbai
# e-mail: wangyibaimengbo@163.com
# Created Time: Thu 26 Mar 2015 11:08:22 AM CST
#########################################################################
#! /usr/bin/env python
"""
This... |
#!/usr/bin/env python
'''
Verification Bot
verification.py
Christopher Su
http://christophersu.net/
Checks Google Spreadsheet linked to form for new data and applies verification flair accordingly.
'''
import gspread
import praw
from praw.handlers import MultiprocessHandler
import logging
import json
import os
from ti... |
from rest_framework import generics, permissions
from rest_framework.response import Response
#from knox.models import AuthToken
from django.contrib.auth import login
from rest_framework.authtoken.serializers import AuthTokenSerializer
from rest_framework.renderers import TemplateHTMLRenderer
#from knox.views import Lo... |
from turtle import Turtle, Screen
import random
screen = Screen()
screen.setup(width=500,height=400)
user_bet = screen.textinput(title="make your bet", prompt = "which turetle will win the race, enter the colour")
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
all_turtles = []
y_position = 0
for i in ... |
'''
CECS 100
Project 5
Name: Newton Bao
I.D.#:018286708
Date: May 2, 2019
'''
import numpy as base
x=base.array([[1,3],[-2,4]])
print(x)
a=base.array([[2,1,0,3],[-1,0,2,4],[4,-2,7,0]])
print(a)
b=base.array([[-4,3,5,1],[2,2,0,-1],[3,2,-4,5]])
r=a+b
print(r)
A=base.array([[1,2,4],[2,6,0]])
print(A)
B=base.array([[4,1,... |
from parsing_exp import parse_reg_exp
from building_from_exp import build_automaton
def main():
exp = input()
parts = parse_reg_exp(exp, 0)
build_automaton(parts)
if __name__ == "__main__":
main()
|
# -*- coding: utf-8 -*-
""" Definition of callbacks that can be passed to the fit function. """
import torch
from torch import Tensor
from copy import deepcopy
class callback():
def __call__():
""" Called at each epoch. """
raise NotImplementedError
def end():
""" Called at t... |
from numpy import ndarray
_steps = {
"1.01": "Convert to Canonical Form for Base Indices of {}",
"1.02": "Basis:\n{}",
"1.03": "Corresponding Coefficient Entries: {}",
"1.04": "Basis Inverse:\n{}",
"1.05": "y Vector:\n{}",
"2.01": "Is {} Feasible?",
"2.02": "{} is Feasible:",
"2.03": "*... |
# Quiz 3
#
#
# Instrucciones: Dado un intervalo de tiempo en segundos, calcular los segundos restantes que
# corresponden para convertirse exactamente en minutos. Este programa debe funcionar para 5 oportunidades.
def get_segundos(S):
segundos = S % 60
return 60 - segundos
if __name__ == '__main__':
... |
#!/usr/bin/env python3.3
# -*- coding: utf8 -*-
#
# Management Interface
#
# Copyright (c) 2015 NorthernSec
# Copyright (c) 2015 Pieter-Jan Moreels
# Imports
import os
import sys
runpath=os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(runpath, '..'))
import argparse
from lib.DatabaseLay... |
# coding=utf-8
from django.db import models
from article.models import Article
class Author(models.Model):
author_nameFirst = models.CharField(max_length=30, verbose_name=u'Имя')
author_nameLast = models.CharField(max_length=30, verbose_name=u'Фамилия')
author_wiki = models.URLField(verbose_name=u'Wiki',... |
# -*- coding: utf-8 -*-
#############
#
# Copyright - Nirlendu Saha
#
# author - nirlendu@gmail.com
#
#############
from __future__ import unicode_literals
import sys
import inspect
from django.db import models
from libs.logger import app_logger as log
class UrlManager(models.Manager):
def store_url(
... |
age = int(input("Enter you age: "))
if age <= 1:
print("Infant")
elif 1 < age <= 10:
print("Child")
elif 10 < age <= 18:
print("Teen")
elif 18 < age <= 45:
print("Adult")
else:
print("Old")
|
list=[1,2,3,4,5]
for x in list1:
print(x)
print(list[2:5])
dict={0:'zero',1:'one',2:'two',3:'three',4:'four','repeat':{0:'zero',1:'one',2:'two',3:'three',4:'four'}}
print(dict['repeat'])
newlist=["11",'22',33,44,{0:'zero',1:'one',2:'two',3:'three',4:'four','repeat':{0:'zero',1:'one',2:'two',3:'three',4:'four'}}... |
from common.services.template_functions import all_template_functions_dict
# during docker build common is copied into each subproject
# specify the render_template method
# for flask this will the imported render_template instead of a standalone jinja2 render_template function
from src.template_base import render_te... |
# -*- encoding: utf-8 -*-
from pyramid.view import view_config
from pyramid.url import route_url
from pyramid.httpexceptions import HTTPFound
from pyramid.security import authenticated_userid
from tempus_ui.views.api import TemplateAPI
@view_config(
route_name='tempusroot',
renderer='tempus_ui:templates/tempu... |
from __future__ import unicode_literals
from django.db import models
# from django.contrib.auth.models import AbstructBaseUser
# from django.contrib.auth.models import BaseUserManager
from django.contrib.auth.models import User
# Create your models here.
class Account(models.Model):
MARITAL_STATUS = (
... |
from django.urls import path,include
from .views import show,bigshow
urlpatterns = [
path('detail/<int:productpk>',show,name='product'),
path('bigdetail/<int:productpk>',bigshow,name='bigshow'),
] |
a=[]
b=[]
for i in range(3):
c,d=input().split()
a.append(c)
b.append(d)
if a.count(a[0])==3 or b.count(b[0])==3:
print("yes")
else:
print("no")
|
import traceback
import json
from struct import *
import random
import math
from emailapp.decorate import login_required
from emailapp.sql_helpers import templates, authenticate, user, lists, \
campaign_helper, email_result, ready_to_send_email_helper, \
campaign_stats, campaign_winning_combination, emails_unsu... |
# encoding: utf-8
import time
import sys
import copy
class HumanPlayer(object):
def __init__(self, name, color, board, rulebook):
self.name = name
self.color = color
self.board = board
self.rulebook = rulebook
self.highlightBoard = 0
def copyBoard(self):
return copy.deepcopy(self.board)
def getHighl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.