text stringlengths 8 6.05M |
|---|
# -*- coding: utf-8 -*-
# @Time : 2019.9.18
# @Author : Xie Junming
# @Licence : bio-totem
from PIL import Image
import numpy as np
from skimage import io
from imutils import paths
import os
from tqdm import tqdm
import re
import cv2
import concurrent.futures
import time
step = 512
patch_size = 512
... |
#!/usr/bin/env python
"""Script to import 'sys' module and investigate some of its properties"""
__author__ = 'Saul Moore (sm5911@imperial.ac.uk)'
__version__ = '0.0.1'
import sys
print "This is the name of the script: ", sys.argv[0] # Prints the name of the module
print "Number of arguments: ", len(sys.argv) # Sho... |
import os
from json import loads
def getEnv(key):
try:
path = os.path.abspath('env.json')
arq = open(path,'r')
j = loads(arq.read())
return str(j[key])
except:
try:
return os.environ[key]
except:
raise Exception(f'Environment variable {key... |
from flask import request
from flask_restx import Namespace, Resource, fields, reqparse, marshal
from src.api.users.views import extract_token
from src.api.users.crud import get_user_by_session_token
from src.api.reviews.crud import (
get_all_reviews,
get_review_by_id,
get_reviews_by_place,
... |
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
import uuid
import os
def image_file_path(instance, filename):
"""Generate file path for new image"""
ext = filename.split('.')[-1]
filename = f'{uuid.uuid4()}.{ext}'
return os.path... |
from flask import Flask, render_template, request, session
from flask_session import Session
from werkzeug.wrappers import Request, Response
app=Flask(__name__, template_folder='template')
app.config["SESSION_PERMANENT"]=False
app.config["SESSION_TYPE"]="filesystem"
Session(app)
notes=[]
@app.route("/", methods=["GET",... |
sum = 0
for x in range(1,1001):
sum+= x**x
sum = str(sum)
print sum[len(sum)-10:len(sum)]
|
#!/usr/bin/env python3
# encoding: utf-8
"""
@version: 0.1
@author: lyrichu
@license: Apache Licence
@contact: 919987476@qq.com
@site: http://www.github.com/Lyrichu
@file: test_GA.py
@time: 2018/06/06 16:45
@description:
test for GA
"""
from time import time
import sys
sys.path.append("..")
from sopt.GA.GA import GA
f... |
import turtle
def drawCurve(turtle, l,order):
if order==0:
turtle.forward(5)
return
else:
l/=3
drawCurve(turtle,l,order-1)
turtle.left(60)
drawCurve(turtle,l,order-1)
turtle.right(120)
drawCurve(turtle,l,order-1)
turtle.left(60)
dr... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from ..login.models import User
# Create your models here.
class LocationManager(models.Manager):
def validate_and_create(self, data, id):
print data, "\n woo we have data"
errors = []
if len(dat... |
import pygame
from random import randrange
import os
import pandas as pd
import fonts
def spawn_food(snake):
x_spawn = randrange(0, 510 - snake.width, snake.velocity)
y_spawn = randrange(0, 510 - snake.height, snake.velocity)
while [x_spawn, y_spawn] in snake.rectangles:
x_spawn = randrange(0, 510 - snake.width,... |
ano = int(input("Digite o ano: "))
mes = int(input("Digite o mês em numero: "))
if (ano % 4 == 0) and (ano % 100 != 0):
if (mes == 1)or(mes == 3)or(mes == 5)or(mes == 7)or(mes == 8)or(mes == 10)or(mes == 12):
print("Esse mês tem 31 dias")
elif (mes == 4)or(mes == 6)or(mes == 9)or(mes == 11):
... |
"""User model"""
from sqlalchemy import Column, Integer, BigInteger, ForeignKey, DateTime, Float, VARCHAR
from models.db import Model
from models.base_object import BaseObject
class Task(BaseObject, Model):
id = Column(Integer, primary_key=True)
UserNo = Column(Integer)
TrialNo... |
#coding=utf-8
#__author__ = 'cclin'
#write by cclin 2021.03.24
import sys
import os,os.path
import re
import codecs
import xml.dom.minidom as minidom
from xml.etree import ElementTree as ET
# ==由于minidom默认的writexml()函数在读取一个xml文件后,修改后重新写入如果加了newl='\n',会将原有的xml中写入多余的行
# ==因此使用下面这个函数来代替
def fixed_writexml(self... |
def getInv(N):
nums = [1]*(N + 1)
inv = [0] * (N + 1)
inv[0] = 1
inv[1] = 1
for i in range(2, N + 1):
inv[i] = (-(Q // i) * inv[Q % i]) % Q
nums[i] = nums[i-1]*i%Q
return nums, inv
K, N = map( int, input().split())
Q = 998244353
fuct, invs = getInv(N+K)
c = fuct[N+K-1]*invs[N]*i... |
acronym_list = []
for line in open('datasets/output/AnonymizedClinicalAbbreviationsAndAcronymsDataSet.txt', 'r', encoding="utf8"):
acronym = line.split('|')[0]
full_wordphrase = line.split('|')[1]
both_acronym_and_wordphrase = acronym+'|'+full_wordphrase
both_acronym_and_wordphrase = both_acronym_and_w... |
from viola.core.event_loop import EventLoop
from viola.wsgi.server import WSGIServer
from viola.core.scheduler import Scheduler
# from wsgi_flask_test import app
from wsgi_bottle_test import app
# import os
if __name__ == '__main__':
event_loop = EventLoop.instance(Scheduler.instance())
server = WSGIServer(ev... |
from plays import *
import sys
playbook_config_newVrf_fp = { "validatePlays": [ play_validate_newVrf_fp ], "playGroups": [ [ { "play": play_configBuild_newVrf_fp, "printHostName": True } ] ] }
playbook_config_newOspfL3Out_dsFw_fp = { "validatePlays": [ play_validate_newOspfL3Out_dsFw_fp ], "playGroups": [ [ { "play"... |
# !/usr/bin/env python
# tasks: fit SB, fit kT, estimate Mass, csb, w, ErrorCenterX
# Obs.: don't forget to activate the ciao enviroment!
from astropy.io.fits import getdata
from astropy.table import Table
import astropy.io.ascii as at
import matplotlib.pyplot as plt
import matplotlib
import astropy.units as u
from a... |
#https://leetcode-cn.com/contest/weekly-contest-218/problems/concatenation-of-consecutive-binary-numbers/
#只要求得 最后长度在 len(modBinBase) 范围内的值即可,然后取异或
class Solution:
modBinBase = '111011100110101100101000000111'
def concatenatedBinary(self, n: int) -> int:
ss=""
for i in range(n+1):
... |
pounds = float(input("Enter number of pounds: "))
kg= pounds*0.454
print("Number of Kilograms: ",kg) |
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
# Create your models here.
LANGUAGES = (
('J', 'JavaScript'),
('H', 'HTML5'),
('C', 'CSS3'),
('P', 'Python'),
('S', 'SQL'),
('M', 'MongoDB')
)
class Project(models.Model):
project_name ... |
# ticker ticks every 1/rate seconds, default 1/1000 s, and provides time for the world
import time
import threading
class Ticker(threading.Thread):
def __init__(self, rate=1000, max_ticks=5000, world=None):
threading.Thread.__init__(self)
self.rate = rate
self.max_ticks = max_ticks
... |
#因为参与了笑来老师管理的BOX定投,所以想知道长期稳定定投下来的收益是多少?
#下面是我的思考,长期更新
x = 3470 #初始资金,单位美元
y = 57.38 #每期投入资金
y_2 = 186.8 #测试用
mo = int() #目标资金数
num = int() #投资期数,一年52期
#money()这个函数的只实现了部分功能,需将week()函数的功能添加进来
def money(mo, num):
gth = (mo - x - num*y) / (x + num*y) #gth为growth的缩写,代表收益率
gth_y = (365*gth) / (7*num)
return ... |
import cv2
from matplotlib import pyplot
original_image = cv2.cv2.imread("pexels.jpeg")
cv2.cv2.imshow("original image", original_image)
rgb_image = cv2.cv2.cvtColor(original_image, cv2.cv2.COLOR_BGR2RGB)
pyplot.imshow(rgb_image)
pyplot.show()
cv2.cv2.waitKey(0)
cv2.cv2.destroyAllWindows() |
# -*- coding: utf-8 -*-
import scrapy
import re
class MalaysiaSomdomSpider(scrapy.Spider):
name = 'malaysia_somdom'
allowed_domains = ['www.somdom.com/malay/t6411']
start_urls = ['http://www.somdom.com/malay/t6411/',
'http://www.somdom.com/malay/t6411-2',
'http://www.som... |
import os
print(os.path.abspath(os.curdir)) |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-23 17:43
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='User',... |
from reporter_app import db
from flask_security import UserMixin, RoleMixin
from sqlalchemy import create_engine
from sqlalchemy.orm import relationship, backref
from sqlalchemy import Boolean, DateTime, Column, Integer, String, ForeignKey, UnicodeText, UniqueConstraint
from sqlalchemy.sql import func
import datetime
... |
import json
import matplotlib.pyplot as plt
import torch
import os
import numpy as np
# save the training parameters in a txt at the beginning of training
def save_params(par, model_dir, name):
data = {}
for att in dir(par):
if not att.startswith('__'):
data[att] = par.__getattribute__(at... |
#!/usr/bin/env python
#-*-coding:utf-8-*-
'''
Let d(n) be defined as the sum of proper divisors of n
(numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a ≠ b, then a and b are
an amicable pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 are
1... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
import re
# def multiple_replace(dict, text): #this have error when they're sticked e.g. && ||
# # Create a regular expression from the dictionary keys
# regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
# # For each match, l... |
from placement import Placement
from campaign import Campaign
from copyback import Copyback
from rebuild import Rebuild
from batch import Batch
from poisson import Poisson
from exponential import Exponential
from server import Server
from state import State
from disk import Disk
from heapq import *
#-------------------... |
from rest_framework import routers
from rest_framework.urlpatterns import format_suffix_patterns
from site_manage.views import Assign
from django.urls import path
from . import views
router = routers.SimpleRouter(trailing_slash=False)
router.register(r'site', views.SiteViewSet)
urlpatterns = [
path('assign', Ass... |
from bs4 import BeautifulSoup
import requests
import argparse
import requests.exceptions
from urllib.parse import urlsplit
from collections import deque
import re
'''
A script to scrape youtube links from a predefined website of choice.
'''
ap = argparse.ArgumentParser()
ap.add_argument("-w", "--website", ... |
from unittest import TestCase, main
from os import remove
from os.path import exists, join, basename
from shutil import move
from biom import load_table
from pandas.util.testing import assert_frame_equal
from functools import partial
import numpy.testing as npt
from qiita_core.util import qiita_test_checker
from qiit... |
"""
This is the pseudocode of the framework
It will be rewrited by python follow
These cases are good and need not to wait for the pedestrians according to the rule
#1.If (Pedestrians are detected but not overstepping the lane line)
#2.If (Pedestrians are waiting out of the lane line)
#3.If (Pedestrians are moving cro... |
"""
textbook example: double ended queue.
use cyclic array structure, change size if necessary.
"""
class Empty(Exception):
pass
class ArrayDoubleEndedQueue:
"""double-ended-queue, both ends can add or delete"""
DEFAULT_CAPACITY = 10
def __init__(self):
self._data = [None] * self.DEFAULT_CAP... |
from django.shortcuts import render
from django.http import HttpResponse
from tour.models import *
from activity.models import Activity
from training.models import Training
from organizer.models import Organizer
from django.shortcuts import get_object_or_404
import smtplib
from Wactop.mail import *
import smtplib
# s... |
from property_price_model import create_app, db
from property_price_model.models import Sale
app = create_app()
@app.shell_context_processor
def make_shell_context():
return {"db": db, "Sale": Sale}
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)
|
import numpy as np
__author__ = 'syao'
# file HEADER
HEADER_MI1B2T_URL = 'ftp://l5eil01.larc.nasa.gov/MISR/MI1B2T.003/'
HEADER_MI1B2T_FILENAME = 'MISR_AM1_GRP_TERRAIN_GM_P'
HEADER_MIL2ASAE_URL = 'ftp://l5eil01.larc.nasa.gov/MISR/MIL2ASAE.002/'
HEADER_MIL2ASAE_FILENAME = 'MISR_AM1_AS_AEROSOL_P'
HEADER_MIL2ASAF = 'ftp:... |
## Python 3
prev2 = 1
prev1 = 1
fibList = [1, 1]
def Fibby(prev1, prev2):
nextFib = prev1 + prev2
if(nextFib < 4000000):
fibList.append(nextFib)
Fibby(prev2, nextFib)
Fibby(prev1,prev2)
answer = sum(filter(lambda x: x % 2 ==0 , fibList))
print("The sum of the even-valued terms i... |
from flask import request
from gateway.app import app
from gateway.http_client import requirementmanager_http_client
from gateway.utils.handle_api import (
get_client_username, handle_request_response
)
@app.route('/requirement/archive/tree/list', methods=['GET'])
@handle_request_response
@get_client_username
de... |
test_str = "UAqwertyuiopasdfghjklPl;p[/"
result = []
for symbol in test_str:
if symbol.lower() not in "eyuioa" and symbol.isalpha():
# print(f"symbol: {symbol}")
result.append(symbol)
print(result)
join_str = "".join(result)
print(join_str)
# split_str = list(test_str)
# print(split_str)
# # tuple - ... |
from pratice.files02.Car import Car
car = Car('BMW', 'M3')
print(car.data()) |
"""
问题描述
给定n个正整数,找出它们中出现次数最多的数。如果这样的数有多个,请输出其中最小的一个。
输入格式
输入的第一行只有一个正整数n(1 ≤ n ≤ 1000),表示数字的个数。
输入的第二行有n个整数s1, s2, …, sn (1 ≤ si ≤ 10000, 1 ≤ i ≤ n)。相邻的数用空格分隔。
输出格式
输出这n个次数中出现次数最多的数。如果这样的数有多个,输出其中最小的一个。
样例输入
6
10 1 10 20 30 20
样例输出
10
---------------------
"""
if __name__ == '__main__':
n = eval... |
import mock
import unittest
from flask import Flask
from flask_testing import TestCase
from flask_watchman import Watchman, Environment
class TestWatchman(TestCase):
"""
Test flask apps that are using class based views
"""
def create_app(self):
app = Flask(__name__, static_folder=None)
... |
from tkinter import *
window = Tk()
b1 = Button(window, text="첫번째 버튼")
b2 = Button(window, text="두번째 버튼")
b1.pack(side=LEFT)
b2.pack(side=LEFT)
window.mainloop() |
import os
import re
import glob
import pickle
import pandas as pd
from utils.transform_utils import *
# Get all posts within the data directory
posts = glob.glob('data/posts/*.p')
# Iterate over all posts within a class
for fp in posts:
# Load each post into a DataFrame and store its networkid
df = pd.DataFr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
class HtmlDownloader(object):
def download(self,url):
if url is None:
return None
url_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36'
... |
import pygame
import random
#dimesion fenetre#
largeur=650
hauteur=700
#police#
pygame.font.init()
ma_police=pygame.font.SysFont('Comic Sans MS',30)
ecran=pygame.display.set_mode((largeur,hauteur))
clock=pygame.time.Clock()
FPS=20
#Couleurs RGB (rouge vert bleu)#
White=(180,238,180)
Green=(0,255,0)
Black=(0,0,0)
Red=(... |
punctuations=',./;:?"}{[]@!#$%^&*()'
string=input('enter the string')
nopunctuation=''
for i in string:
if i not in punctuations:
nopunctuation=nopunctuation+i
print(nopunctuation) |
# -*- coding: utf-8 -*-
""""
Tool Name: Avalanche paths to 3D
Source Name: AvalanchePathsTo3d.py
Version: ArcGIS 10.3.1
Author: Icelandic Meteorology Office/Ragnar H. Thrastarson
Created: 2016-10-28
Description: A python script tool that takes pre-defined avalanche
paths with pre-defined fields and converts them to 3D ... |
#/usr/bin/env python
import sys
from helper import *
from playbooks import *
from group_vars import *
def run():
#
#
#Variable initialization
#
#
yamlFileName = ""
input = {}
#
#
# Check the input arguments.
#
try:
argslen = len(sys.argv)
... |
from threading import Timer
class Highlight:
def __init__(self):
self.element = None
self.original_style = None
self.timer = None
def apply_style(self, style):
try:
self.element._parent.execute_script("arguments[0].setAttribute('style', arguments[1]);"... |
from OOP.PlanetSystem_Euler import solarsystem, planet
import numpy as np
import matplotlib.pyplot as plt
#use 100000 steps to see long term effects
n = 1000
tf = 100
ti = 0
h = 0.01
Earth_mass = 0.0001
Sun_mass = 1
Jupiter_mass = 0.001
Earth_posx = 1.0
Earth_posy = 0
Jupiter_posx = 2
Jupiter_posy = 0
Sun_posx = 0
S... |
import os
SECRET_KEY = '123qwe456ghj'
pg_host = os.environ.get('POSTGRES_PORT_5432_TCP_ADDR', '192.168.99.100')
pg_port = os.environ.get('POSTGRES_PORT_5432_TCP_PORT', '5432')
SQLALCHEMY_DATABASE_URI = 'postgresql://postgres:postgres@{}:{}/brotherhood'.format(pg_host, pg_port)
SQLALCHEMY_TRACK_MODIFICATIONS = True
|
from rest_framework import serializers
from . import models
class PostSerializer(serializers.ModelSerializer):
class Meta:
fields = ('id', 'name', 'age','gender','country','remarks', 'created_at', 'updated_at',)
model = models.StudentModel
|
''' VARIABLES EXPECTED:
a) Trade-Off Parameter (Alpha)
b) Weight/Reputation Score (Gamma)
c) Last Time The Agent was selected (b)
RETURNS a LIST of addresses of SAMPLED AGENTS
'''
#agents_record = {"ETH_ADDRESS":[GAMMA,B_VAL]}
from dataForAgentSelection import agents_record
from collections import defaultdict,OrderedD... |
favorite_language='python '
print(favorite_language.rstrip())
favorite_language=' python '
print(favorite_language.lstrip())
print(favorite_language.strip())
|
#!/usr/bin/python
import datetime
import time
import serial
import serial.tools.list_ports
import requests
import json
from const import Constant
from logmessages import LogMessage
class ReadTemperature:
const = ''
logMessage = ''
def __init__(self):
self.const = Constant()
self.logMe... |
# Generated by Django 2.2.4 on 2020-03-22 11:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("budget", "0008_auto_20200223_2124")]
operations = [
migrations.CreateModel(
name="QuarterTotal",
fields=[
(
... |
from django.contrib.auth import logout, login
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.views import LoginView
from django.http import HttpResponse, HttpResponseNotFound
from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from dja... |
from tremendous.client import Tremendous
from tremendous.version import __version__
__all__ = ['Tremendous', '__version__']
|
# Generated by Django 3.2.5 on 2021-08-08 12:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog_app', '0002_auto_20210808_1745'),
]
operations = [
migrations.AlterModelOptions(
name='blog',
opt... |
# Generated by Django 3.0.8 on 2020-08-12 22:46
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('data', '0001_initial'),
migrations.swappable_dependency(setting... |
import subprocess
import basetest
import time
class TestCaseEmitMetrics(basetest.BaseTest):
def setUp(self):
self.setUpCF('sample-6.2.0.mda')
subprocess.check_call(('cf', 'set-env', self.app_name, 'METRICS_INTERVAL', '10'))
self.startApp()
def test_read_metrics_in_logs(self):
... |
from replit import clear
from art import logo
#HINT: You can call clear() to clear the output in the console.
print(logo)
print("Welcome to the Secret Auction Program")
ans=True #Flag
bidders={}
while ans:
name=input("What's your name?\n")
bid=int(input("What's your bid?\n"))
bidders[name]=bid #adding key,value... |
from urllib import quote as url_quote
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from spellcorrector.views import Spellcorrector, tokenize_text, remove_stopwords
spellcorrector_instance = Spellcorrect... |
import glob
import math
import os.path as osp
import numpy as np
import torch.utils.data as data
"""# Data Loader"""
def make_data_path_list(phase="train"):
"""
Parameters
----------
phase : 'train' or 'val'
Returns
-------
path_list : list
"""
rootpath =... |
from lxml import etree
tree = etree.parse("nlp.txt.xml")
root = tree.getroot()
docment = root[0]
sentences = docment.find("sentences")
coreferences = docment.find("coreference")
def sentence_text(sentence):
return " ".join([token.find("word").text for token in sentence.find("tokens")])
def replaced_sentence(s... |
if True:
print("c'est vrai")
x = True
if x:
print(" X est vrai")
else:
print(" X n'est pas vrai")
loc = "banque"
if loc == "auto":
print("Bienvenu au magasin auto")
elif loc == "banque":
print("Bienvenu à la banque")
else:
print("Au revoir")
|
from itertools import permutations
from itertools import combinations
def dist(a,b):
return abs(a[1]-b[1])**2 + abs(a[0]-b[0])**2
[n,m,k] = list(map(int,str(input()).split(" ")))
vol = []
med = []
for x in range(n):
vol.append(list(map(int,str(input()).split(" "))))
for y in range(m):
med.ap... |
import os
import logging
import logging.handlers
def SetupLogs(path):
"""
Helper function for creating a logs for whole client.
"""
# Create logging
logger = logging.getLogger("miner_watchdog")
# Switch files each day. Save backup for last 7 days
file_handler = logging.handlers.TimedRota... |
"""
Configuration of syllabus server.
Edit to fit development or deployment environment.
"""
PORT=5000
DEBUG = True # Set to False for production use
schedule="data/schedule.txt"
|
from django import forms
from .models import Modify_Result
class First_Form(forms.ModelForm):
class Meta:
model = Modify_Result
fields = '__all__'
label = {'Person_Name' : 'Name ' , 'Pull_Ups' : 'Pull Ups' , 'Push_Ups' : 'Push Ups','Chin_Ups' : 'Chin Ups'}
# required widgets label initial... |
import pika
connection = pika.BlockingConnection(
pika.ConnectionParameters('localhost')
)
channel = connection.channel() # 声明一个管道
# 声明queue
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!'
... |
# -*- coding: utf-8 -*-
from django.conf import settings
from modeltranslation.translator import TranslationOptions
class BaseTranslationOptions(TranslationOptions):
required_languages = (settings.DEFAULT_LANGUAGE,)
fallback_languages = {'default': settings.LANGUAGE_CODES}
empty_values = ''
def get_mod... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class AppledailyItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
#日期
date = scrapy.Field()
#... |
import bisect as bisect
N = int(input())
*A, = map(int, input().split())
B = [0]
for x in A:
B.append(B[-1]+x)
ans = 10**15
for i in range(2, N-1):
print(i)
m = sum(A[:i])/i
M = sum(A[i:])/(N-i)
n = bisect.bisect(B,m)
l = bisect.bisect(B,M)
if abs(B[i]-B[n]-B[n]+B[0]) <= abs(B[i]-B[n-1]-B[n... |
day = 0
q1 = 'Is your Birthday in Set 1?\n \
1 3 5 7\n\
9 11 13 15\n \
17 19 21 23\n \
25 27 29 31\n \
\nEnter Yes or No: '
answer = input(q1)
if answer == 'Yes':
day += 1
q2 = 'Is your Birthday in Set 2?\n \
2 3 6 7\n \
10 11 14 15\n \
18 19 22 23\n \
26 27 30 31\n \
... |
from django.urls import path
from rest_framework.authtoken.views import obtain_auth_token
from .views import (mainPageData,
messageBox,
messages,
addMessages,
addFeedback,
signupAsProvider,
logout,
... |
#!/usr/bin/env python3
import logging
import signal
from sonosco.inference.las_inference import LasInference
from sonosco.ros1.server import SonoscoROS1
from roboy_cognition_msgs.srv import RecognizeSpeech
from roboy_control_msgs.msg import ControlLeds
from mic_client import MicrophoneClient
# from std_msgs.msg import... |
# Generated by Django 3.2.6 on 2021-08-23 15:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bot', '0002_alter_customer_id'),
]
operations = [
migrations.AlterField(
model_name='cart',
name='id',
f... |
import collections
import copy
import pprint as ppr
_printer = ppr.PrettyPrinter(indent=2)
def pprint(x):
_printer.pprint(x)
return x
def fmap(f, d):
m = {}
for k, v in d.items():
m[k] = f(v)
return m
def group_by(coll, f):
d = {}
for x in coll:
k = f(x)
lst = d.g... |
import numpy as np
import scipy
import scipy.special
gamma = scipy.special.gamma
# this is a function to make a GARCH(1,1) timeseries of length N
def generateX(N, omega, alpha ,beta, nu, sigma1):
X = np.zeros(N)
sigmasquared = sigma1 * np.ones(N)
Z = np.sqrt((nu - 2) / nu) * np.random.standard_t(nu, N)
... |
# Copyright 2018 Nicholas Li
#
# 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 writing, ... |
import sys
from rosalind_utility import hamming_dist
if __name__ == "__main__":
'''
Given: Two DNA strings s and t of equal length (not exceeding 1 kbp).
Return: The Hamming distance dH(s,t).
'''
input_lines = sys.stdin.read().splitlines()
s1 = input_lines[0]
s2 = input_lines[1]
print(h... |
#import sys
#input = sys.stdin.readline
def main():
N = int( input())
P = list( map( int, input().split()))
ans = 0
now = P[0]
for p in P:
if now >= p:
ans += 1
now = p
print(ans)
if __name__ == '__main__':
main()
|
from PiSearchStrategy import *
import pygame
from pygame.locals import *
class IntroScreen(object):
def __init__(self, surface):
self.surface = surface
def Show(self):
self.Draw()
return self.HandleEvents()
def Draw(self):
# First, fill the whole screen with black
... |
#!/usr/bin/env python
from subprocess import check_output
import flask
from flask import request, redirect, url_for, make_response
from os import environ
import os
from flask import jsonify
from werkzeug import secure_filename
from clean_data import *
from create_csv import *
from datetime import datetime
## Build - ... |
from tkinter import filedialog
from tkinter import *
import time
root = Tk()
root.filename = filedialog.askopenfilename(initialdir=r"C:\Users\Dom\Desktop", title="Select file")
file = open(root.filename, "rb")
root.destroy() # kill it
print("Processing file...")
text = file.read()
totalsize = len(text)
fil... |
# Author: Nathan Shelby
# Date: 3/11/20
# Description: Create a working digital version of the game Xiangqi
# Create a class called XiangqiGame that initializes a board (which is a list of lists), a move counter to see whose
# Turn it is, the game state, and the check status of both players.
# The board has the short... |
import tensorflow as tf
import numpy as np
import os
import time
import datetime
import data_helper_new
import word2vec_helpers
import pandas as pd
# Parameters
# ==================================================
# Data Parameters
#./是当前目录 ../是父级目录 /是根目录
tf.flags.DEFINE_string("input_text_file", "G:/data_test.csv",... |
# -*- coding: utf-8 -*-
# @Time : 2018/9/27 17:06
# @Author : HLin
# @Email : linhua2017@ia.ac.cn
# @File : data_utils.py
# @Software: PyCharm
import os
import sys
sys.path.append(os.path.abspath('..'))
from tqdm import tqdm
import numpy as np
from datasets.Voc_Dataset import VOCDataLoader
from datasets.city... |
""" Quick RTMP connection client """
# Info:
# Credits:
# Structure:
# Predominantly consisting of a class structure with 3 main classes:
# - Pre-connection settings
# - Normal packet handling via NetConnection
# - Other packet handling via NetStream
# AMF Encoding/Decoding:
# The process of enco... |
import struct
from Crypto.Cipher import AES
## Constants for packet decoding fields
# Frame Control Field
DOT154_FCF_TYPE_MASK = 0x0007 #: Frame type mask
DOT154_FCF_SEC_EN = 0x0008 #: Set for encrypted payload
DOT154_FCF_FRAME_PND = 0x0010 #: Frame pending
DOT154_FCF_ACK_REQ ... |
N = input()
N = int(N)
count = 0
min = -1
f = 0;
#python에서 //은 몫을 나타냄~
if N % 5 == 0 :
count = N / 5
N = N % 5
min = count
while N > 5*f :
Num = N
count = 0
count += f
Num = Num - 5*f
if Num % 3 == 0 :
count += Num // 3
if min == -1 :
min = count
e... |
from django.db import models
# Create your models here.
class Preguntas(models.Model):
pregunta = models.CharField(max_length=200)
pub_date = models.DateTimeField()
def __str__(self):
return self.pregunta
class Opciones(models.Model):
Pregunta = models.ForeignKey(Preguntas)
opcion_texto =... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 12 17:04:58 2018
@author: kai
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 8 17:18:49 2018
@author: kai
"""
import numpy as np
import matplotlib.pyplot as pt
from scipy.spatial.distance import cdist
def SAW(length... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.