text
stringlengths
38
1.54M
import datetime, time def dateTimetoLargeInt(year, month, day): seconds_in_year = 31556900 epoch_time_no_subseconds = int(convertDate(year, month, day)) LargeIntTime = (seconds_in_year * (1969 - 1600) + (epoch_time_no_subseconds - 22500)) * 10000000 return LargeIntTime def convertDate(year, month, da...
#!/usr/bin/python3 def print_list(x): for i in range(len(x) - 1): print(x[i], end=", ") print(x[-1]) def bitonic_sort(up, x): if len(x) <= 1: return x else: print("Merging [{}/16] ({}):".format(len(x), "UP" if up else "DOWN")) print_list(x) first = bitonic_sort(...
#!/usr/bin/python global nuTypes nuTypes = {"nue" : 12} global hornCurrentModes hornCurrentModes = ["RHC"]
from PIL import Image import os import math import numpy as np import cv2 #0:left,1:up,2:right,3:down size = 58 num = 240 rn = range(0,num) pos = [[0]] keys = [] images = [] datas = [] print("欢迎使用拼图游戏,该程序用于以游戏的形式进行拼图。虽然效率不高,但起码能用\n规则:") print("1.使用左键点击一块拼图,可以在该块拼图周围的空白处拼上拼图") print("2.使用右键点击一块拼图,...
class Solution(object): def deleteNode(self, root, key): """ :type root: TreeNode :type key: int :rtype: TreeNode preorder """ def find_min(root): min_val = root.val while root: min_val = root.val root ...
#!/usr/bin/env python """Shotcast server Usage: [-h] [-t | --tcp-port 8888] [-u | --udp-port 8889] [--timeout 60] Options: -h --help Show this help. -t --tcp-port <port> Shotcast client listening port number [default: 8888] -u --udp-port <port> Shotcast server(this) listening port num...
from logic import Logic from sentence import Sentence def f(x): return x.ord_preds[0].ordered_args def test_merge(): sent1 = Sentence("P(x) | P(x) | ~P(y) | ~P(y) | T(x) | ~P(y) | \ T(x) | ~T(x) | P(y) | P(Bob)") Logic.merge_sentence(sent1) print(sent1) def test_factoring(): sent1 = Se...
import pandas as pd import numpy as np from typing import Optional from tqdm import tqdm TIME_WINDOWS_DEFAULT = ("60s", "1h", "1d", "5d", "30d", "365d") COUNTERS_DEFAULT = ("attempts", "wins") def encode_df( df: pd.DataFrame, exercises: Optional[tuple] = None, counters: tuple = COUNTERS_DEFAULT, tim...
import os import sys import time import argparse # Create parser and its driver props = ["sec", "s", "min", "m", "hrs", "H"] parser = argparse.ArgumentParser() parser.add_argument("--sec", type=int) parser.add_argument("-s", type=int) parser.add_argument("--min", type=int) parser.add_argument("-m", type=int...
#!/usr/bin/env python import json from view import View from controller import Controller from model import Model def main(): import os abspath = os.path.abspath(__file__) dname = os.path.dirname(abspath) os.chdir(dname) m = Model() v = View() c = Controller(m, v) v.MainLoop() if __...
import wave import bread as b from .vendor.six.moves import range from .bread_spec import lsdj_rom_kits, KIT_SAMPLE_NAME_LENGTH, \ SAMPLES_PER_KIT, KIT_NAME_LENGTH, SAMPLE_START_ADDRESS, MAX_SAMPLE_LENGTH from .utils import fixed_width_string EMPTY_SAMPLE_NAME = '\0--' # WAVs are 8 bits/sample PCM-encoded @ 1...
from django.db import models from django.contrib.auth.models import AbstractUser class Employee(AbstractUser): registration = models.IntegerField(default=123) def __str__(self): return self.username
import numpy import sys m=numpy.zeros((8,8)) temp=0 for i in range(0,8): for j in range(0,8): m[i][j]=temp temp=temp+1 print m #n=numpy.matrix([[int(sys.argv[1]),int(sys.argv[2])],[int(sys.argv[3]),int(sys.argv[4])]]) n=numpy.zeros((2,2)) n[0][0]=int(sys.argv[1]) n[0][1]=int(sys.argv[2]) n[1][0]=int(sys.argv[3])...
import datetime def fuzzy_time_diff(begin, end=None): """ Returns a humanized string representing time difference between now() and the input timestamp. The output rounds up to days, hours, minutes, or seconds. 4 days 5 hours returns "4 days" 0 days 4 hours 3 minutes returns "4 hours", etc...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- import unicodedata import os from debug import toASCII from textstructure import * class InputError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) def sanitize(content): content = ''.join(c for c in un...
import pygame import random class Game: def __init__(self): self.total_score = 0 self.width = 800 self.height = 600 self.fps = pygame.time.Clock() self.colours = {"Black": pygame.Color(0, 0, 0), "White": pygame.Color(255, 255, 255), "Red": pygame.Col...
from django.db import models class TodoList(models.Model): title = models.CharField(max_length=15) content = models.CharField(max_length=100)
import math def isTriangle(x): for n in range(1,x+1): if 2*x/n == n+1: return True return False def getCount(word): ret = 0 for c in word: ret += ord(c)-ord('A')+1 return ret count = 0 for word in open("p042_words.txt").read().split(","): word = word.str...
import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt # Data generator def linear_system(order,noise,timesteps): """ Generates a linear system with a given order (number of coefficients) and given level of noise (variance of a Gaussian, and the signal is some set number of timestep...
import math from copy import deepcopy import random import numpy as np from numba import double from numba.decorators import jit import pyximport pyximport.install() import cfunc #stone & stage reading #data = two stone #onedata = one stone #twostage = two stage #onestage = one stage data = cfunc.getdata() #stag...
from dominion import * def addCard(card, counter): cards.append(card) cardCounters.append(counter) def getCardByName(name): if name: for c in cards: if c.name == name: return c else: return None def countMoney(play): coins = 0 for c in play.hand: if c.name == "Copper": coins+=1 elif c.name =...
# -*- coding: UTF-8 -*- # 通过对unittest.TestCase进行子类化创建测试用例。 import unittest from .getpost import requestmethod class Testget(unittest.TestCase): # setUp():setUp()方法用于测试用例执行前的初始化工作。 def setUp(self): self.requestmethod = requestmethod() self.urlfirst = 'https://test-get99-vapi-m.xgo.city' #...
''' Author : Ki-Hwan Kim (wbkifun@korea.ac.kr) Kim, KyoungHo (rain_woo@korea.ac.kr) Written date : 2009. 7. 23 last update : Copyright : GNU GPL ''' from kufdtd.common import * def is_overlap( c1, c2, d1, d2 ): d = abs(c1 - c2) if ( 2*d > d1 + d2 ): return False elif ( 2*d <= d1 + d2 ): return True ...
import csv from collections import OrderedDict from django.http.response import HttpResponse from django.shortcuts import get_object_or_404, render from django.views.generic.edit import FormView from molo.polls.models import Question class QuestionResultsAdminView(FormView): def get(self, request, *args, **kwarg...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2018-04-15 09:00:00 # @Author : Canon # @Link : https://www.python.org # @Version : 3.6.1 from common import basepage from common import xml_utils from common.conf_utils import Gateway # 读取 xml 文件 xml_obj = xml_utils.XmlUtils(Gateway().read_path("xml", "h...
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
from torch.utils.data import Dataset import pandas as pd import warnings class Maude_dataset(Dataset): def __init__(self, json): self.dataset = json["results"] def __len__(self): return len(self.dataset) def __getitem__(self, idx): return self.dataset[idx] def get_entry(sel...
#!/usr/bin/env python # Copyright (c) 2015, NVIDIA CORPORATION. All rights reserved. """ Classify an image using a model archive file """ import argparse import os, re, sys import time import zipfile import tarfile import tempfile import json import math import PIL.Image from PIL import Image import numpy as np im...
from collections import OrderedDict from pypinyin import pinyin, lazy_pinyin, Style import tensorflow as tf import csv import opencc cc = opencc.OpenCC('t2s') transcript_dict = OrderedDict({}) with tf.gfile.Open("/data/albert/asr/test/trans_st_cmds.txt", "r") as csvfile: readCSV = csv.reader(csvfile, delimiter='\t...
# -*- coding: utf-8 -*- from __future__ import absolute_import import re import time import json import scrapy from urlparse import urljoin from tc.items import TcItem class TcSpiderSpider(scrapy.Spider): name = 'tc_spider' start_urls = ['https://www.sogou.com/sogou?site=news.qq.com&query=%E4%B8%AD%E5%8D%B0%...
import scrapy from qidian_spider.items import QidianSpiderItem from scrapy.http import Request import time import selenium from selenium import webdriver from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait f...
# -*- coding: utf-8 -*- # Generated by Django 1.11.8 on 2018-01-12 13:03 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('player', '0001_initial'), ('tou...
import socket s = socket.socket( socket.AF_INET, socket.SOCK_STREAM) s.connect(("svpdemandergentiment.unitedctf.ca", 42000)) s.recv(20000).decode() labyrinth = s.recv(20000).decode() print(labyrinth) print('Done')
# Author: Matthew Shelbourn | Student ID: 001059665 | mshelbo@wgu.edu | December, 2020 # routes.py includes various functions for calculating & executing delivery routes # The logic in this file will actually execute the truck delivery routes and deliver packages from datetime import datetime, timedelta import time fr...
from django import forms class ContactForm(forms.Form): title = forms.CharField(max_length=150) message = forms.CharField(max_length=200, widget=forms.TextInput) class SubscriptionForm(forms.Form): email = forms.EmailField() class CartUpdateForm(forms.Form): """ This form has a dynamic number of...
from flask import Flask, render_template, Response, redirect, url_for from flask_sqlalchemy import SQLAlchemy from os import getenv import random, string import requests app = Flask(__name__) @app.route('/service3', methods=['GET']) def service3(): num=random.randint(1,8) return Response(str(num), mimetype='text/...
a = int(input()) b = int (input()) if a!=1 and b!=1 or a==1 and b==1: print ('YES') else : print ('NO')
game_display = [["TL", "TM", "TR"], ["ML", "MM", "MR"], ["BL", "BM", "BR"]] def display(game_display): print(game_display[0] [0] + "|" + game_display[0] [1] + "|" + game_display[0][2]) print("__ __ __") print(game_display[1] [0] + "|" + game_display[1] [1] + "|" + game_displa...
#https://leetcode-cn.com/problems/clone-graph/ """ # Definition for a Node. class Node: def __init__(self, val = 0, neighbors = None): self.val = val self.neighbors = neighbors if neighbors is not None else [] """ class Solution: def cloneGraph(self, node: 'Node') -> 'Node': ...
from sqlalchemy import * from migrate import * from migrate.changeset import schema pre_meta = MetaData() post_meta = MetaData() kata_sambung = Table('kata_sambung', post_meta, Column('id', Integer, primary_key=True, nullable=False), Column('word', String(length=140)), ) kolom1 = Table('kolom1', post_meta, ...
#First come first serve implementation in python #taking proceeses as input from user print("Enter the number of processes: ") #creating array to store burst time b_t=[] num=int(input()) print("Enter the burst time of the processes: \n") #creating burst list b_t=list(map(int, raw_input().split())) #creating list to sto...
# -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoAlertPresentException...
from Tkinter import * sp=Tk() sp.title("START") sp.config(background="yellow") img1=PhotoImage(file="pic.gif") def fun(e): sp.destroy() import main L=Label(sp,image=img1,bg="maroon",bd=9) L.bind('<Motion>',fun) L.after(2000,fun) L.grid(row=0,column=0,columnspan=2) Label(sp,text="KARTIKEY CHANDRA",fo...
import random import math import copy import time def createarray(element,total): arr=[] for _ in range(total): arr.append(element) return arr _sysrand = random.SystemRandom() prioritynames=[] prioritiesmaximum=createarray([],2) prioritiesminimum=createarray([],2) maximumattributevalues=createarray...
from django.contrib import admin # import my models from .models import Blog # Register your models here. admin.site.register(Blog)
# -*- coding: utf-8 -*- # ------------------------------------------ # Le code de César # ------------------------------------------ # Chiffrement de César pour un chiffre def chiffrement_nombre(x, k): return (x + k) % 26 # Déchiffrement de César pour un chiffre def dechiffrement_nombre(x, k): return (x - k...
altura=int(input("Digite a sua altura: ")) largura=int(input("Digite a largura: ")) area=int(largura*altura) countn=1 i=1 for i in range(1,area+1): if countn==1 or countn==altura: print("$",end='') else: if ((countn-1)*largura+1)==i or (countn*largura)==i: print("$",end='')...
#!/usr/bin/env python # coding: utf-8 # <center> # <h1><b>Lab 11</b></h1> # <h1>PHYS 580 - Computational Physics</h1> # <h2>Professor Molnar</h2> # </br> # <h3><b>Ethan Knox</b></h3> # <h4>https://www.github.com/ethank5149</h4> # <h4>ethank5149@gmail.com</h4> # </br> # </br> # <h3><b>November 12, 2020</b></h3> # <hr> ...
# Copyright (c) 2019, Hans Jerry Illikainen <hji@dyntopia.com> # # SPDX-License-Identifier: BSD-2-Clause import io import warnings from typing import IO, List import dparse import packaging.version import pkg_resources class Package: def __init__(self, name: str, version: str) -> None: self._name = name...
# 定义分词函数preprocess_text # 参数content_lines即为上面转换的list # 参数sentences是定义的空list,用来储存分词后的数据 import random import jieba import pandas as pd import numpy as np from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import TfidfVectorizer import matplotlibp.pyplot as plt from sklearn....
# -*- coding: utf-8 -*- import sqlite3 class DataBase: def __init__(self, db_path, db_file): self.db_file = db_path + db_file self.db = None def create_db(self): """ Создание необходимых таблиц для работы с ботом """ self.db = sqlite3.connect(self.db_file) ...
#!/usr/bin/env python3 import argparse import sys # return next bed entry as vector of chr, b, e, CN def next_bed_entry(bedcn): line = bedcn.readline() if line != '': line.rstrip('\n') entry = line.split('\t') return([entry[0], int(entry[1]), int(entry[2]), float(entry[3])]) return...
import ssh class Cluster(): """ Cluster This is a compute resource that can be accessed via SSH. This class is the base class for which all clusters inerhit their function. """ def _executeCommand(self, remote_command): client = ssh.SSHClient() client.load_system_host_ke...
{ "id": "mgm4459541.3", "metadata": { "mgm4459541.3.metadata.json": { "format": "json", "provider": "metagenomics.anl.gov" } }, "providers": { "metagenomics.anl.gov": { "files": { "100.preprocess.info": { ...
''' Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. ''' i...
from django.test import TestCase import datetime from jango.utils import timezone from polls.models import Poll class PollMethodTests(TestCase): def test was_published_recently_with_future_poll(self): """ was_published_recently should return False for polls whose pub_date is in the future """ future_poll =...
x = "There are %d types of people. " %10 #Declaring of x binary = "binary" #Declaring of binary do_not = "don't" #Declaring of do_not y = "Those who know %s and those who %s. " %(binary, do_not) #This is the string concatenation to add the sentences together. print x #printing x print y ...
from __future__ import unicode_literals, print_function from django.db import models from .data_type import DataType, DataTypeField as _DataTypeField try: from south.modelsinspector import add_introspection_rules, add_ignored_fields except ImportError: add_introspection_rules = add_ignored_fields = None clas...
import re; condition1 = re.compile(r"(..).*\1") condition2 = re.compile(r"(.).\1") count_nice = 0 with open("input.txt", 'r') as f: for line in f.readlines(): line = line.rstrip() print("Testing `%s`... " % line, end="") if None != condition1.search(line) \ and N...
import pytest from pycaption import MicroDVDReader, CaptionReadNoCaptions from pycaption.exceptions import CaptionReadSyntaxError, CaptionReadTimingError from pycaption.base import DEFAULT_LANGUAGE_CODE from tests.mixins import ReaderTestingMixIn class TestMicroDVDReader(ReaderTestingMixIn): def setup_class(self...
from __future__ import annotations from rsyscall.tests.trio_test_case import TrioTestCase from rsyscall.tasks.stub import * import rsyscall.nix as nix from rsyscall import local_thread from rsyscall.tests.utils import do_async_things from rsyscall.command import Command from rsyscall.stdlib import mkdtemp import os...
#!/usr/bin/env python from __future__ import print_function import sys import numpy as np from time import time from lxml import etree from random import sample, choice __author__ = 'anton-goy' def arg_parse(): return sys.argv[1] def generate_features_endchar(char, pos, paragraph): n_sentences = len(para...
New = Callable( 'XmuNewArea', Area, ['x', X.Integer, 0], ['y', X.Integer, 0], ['width', X.Integer, 0], ['height', X.Integer, 0] ) Area.Duplicate = Callable( 'XmuAreaDup', Area, ['self', Area] ) Area.Copy = Callable( 'XmuAreaCopy', Area, ['self', Area], ['other', Area] ) Area.Not = Callable( 'XmuAreaNo...
from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User from django.contrib.auth import get_user_model from django.core.cache import cache from rest_framework.authentication import SessionAuthentication # authenticated_user_cache = 'authenticated_user:{0}' # # # def get_au...
import urllib2 from bs4 import BeautifulSoup # Parse website into soup format rock_chart = 'https://www.billboard.com/charts/rock-songs' page = urllib2.urlopen(rock_chart) soup = BeautifulSoup(page, 'html.parser') # Extract Top Song top_song_title = soup.find('div', attrs={'class': 'chart-number-one__title'}) title =...
import numpy as np import pandas as pd from sklearn.svm import SVC import sklearn.metrics as metrics from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier from sklearn.metrics import roc_auc_score from sklearn.preprocessing import RobustScaler from sklearn.metrics import roc_curve, auc from sklearn.mo...
try: import os import csv from zcrmsdk.src.com.zoho.api.authenticator.store.token_store import TokenStore from zcrmsdk.src.com.zoho.api.authenticator.oauth_token import OAuthToken, TokenType from ....crm.api.util.constants import Constants from zcrmsdk.src.com.zoho.crm.api.exception.sdk_excepti...
import numpy as np import sys from PIL import Image from numpy import copy import pandas as pd np.set_printoptions(threshold=sys.maxsize) # TODO # lav labyrinter og set start og target path = '/home/frederik/Pictures/maze.jpg' #her skriver man filplacering på ens labyrint im = Image.open(path) matrix = np.asarray(i...
from predictor import WordComplexityPredictor from xmlrpc.server import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer import constants # Restrict to a particular path. class RequestHandler(SimpleXMLRPCRequestHandler): rpc_paths = ('/RPC2',) server = SimpleXMLRPCServer(("localhost", constants.PORT_NUMBER), ...
# # Actions around managing distributed workers and their status. # import asyncio import datetime import os import psutil import re import signal import shutil import socket import time import traceback import yaml from flask import Flask, jsonify, abort, request, flash from web import app, db, utils from common.mo...
import pandas as pd from .plant import Producer, Plant from etm_tools.utils.utils import cached_property class CHPProducers(): '''Wraps the chp inputs csv in the data folder and makes them into Plants and Producers''' # Special treatment BIO_ICE = 'Biogas CHP' COAL_GAS_PLANT = 'Coal gas CHP' GAS_...
# When a closing symbol does appear, the only difference is that we must check to be sure that # it correctly matches the type of the opening symbol on top of the stack. If the two symbols # do not match, the string is not balanced. If the entire string is processed # and nothing is left on the stack, the string is cor...
import dlib reshape = dlib.shape_predictor('face_landmarks.dat') facemod = dlib.face_recognition_model_v1('face_model.dat') detector = dlib.get_frontal_face_detector()
import collections from dsl_parser.exceptions import DSLParsingLogicException VERSION = 'tosca_definitions_version' DSL_VERSION_PREFIX = 'cloudify_dsl_' DSL_VERSION_1_0 = DSL_VERSION_PREFIX + '1_0' DSL_VERSION_1_1 = DSL_VERSION_PREFIX + '1_1' DSL_VERSION_1_2 = DSL_VERSION_PREFIX + '1_2' DSL_VERSION_1_3 = DSL_VERSION_...
# Generated by Django 3.2 on 2021-04-15 23:06 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('blog', '0008_sobre_likes'), ] operations = [ migrations.AddField( model_name='faq', name=...
from pathlib import Path from copy import deepcopy from time import sleep def main(): data_folder = Path(".").resolve() data = data_folder.joinpath("input.txt").read_text().split("\n") data = [list(line) for line in data] p = Packet(data) p.move() print("Part 1") print(f"The packet will see...
from flask_restful import Resource from .parsers import up_parser from app.services import db_services from flask_jwt_extended import create_access_token, create_refresh_token class UserLogin(Resource): def post(self): try: data = up_parser.parse_args() user = db_services.find_by_u...
from profileapi.helpers.ProfileView import ProfileView from profileapi.models import ProfileTemplate from django.shortcuts import redirect from page.models import Page from django.views.generic import View class DeletePage(ProfileView): def get(self, request, page_id): # Fetch Page page = Page.objects.get(pk=pa...
#precip 0.4 only. Hist and Box one plot. import matplotlib matplotlib.use("Agg") from matplotlib import pyplot as plt import pandas as pd import sys target = '/exports/csce/datastore/geos/users/s1134744/LSDTopoTools/Topographic_projects/full_himalaya_5000/' source= '0_4_ex_MChiSegmented_bur...
# 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 # # 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢? # # 注意:给定 n 是一个正整数。 # # 示例 1: # # 输入: 2 # 输出: 2 # 解释: 有两种方法可以爬到楼顶。 # 1. 1 阶 + 1 阶 # 2. 2 阶 # # 示例 2: # # 输入: 3 # 输出: 3 # 解释: 有三种方法可以爬到楼顶。 # 1. 1 阶 + 1 阶 + 1 阶 # 2. 1 阶 + 2 阶 # 3. 2 阶 + 1 阶 # # Related Topics 动态规划 # 👍 1258 👎 ...
from leetcode_problem import LeetCodeProblem, GitHubFile, NameUtil class GolangLeetCodeProblem(LeetCodeProblem): def extract_class_docs(self): if self.code_snippet.startswith('/**'): docs = self.code_snippet[ self.code_snippet.index('/**'):self.code_snippet.index('*/') + le...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompan...
# 1 # import requests # import json # # key = 'ecb65c5b4cab1e093e9b71fdd6020bbe' # lat = 55.5 # lon = 100 # cnt = 50 # payload = {'appid': key, 'lat': lat, 'lon': lon, 'units': 'metric', 'cnt': cnt} # r = requests.get('http://api.openweathermap.org/data/2.5/find', params=payload) # print(r.status_code) # pri...
# Generated by Django 3.0.3 on 2020-11-01 22:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('bagel_site', '0015_auto_20201029_2216'), ] operations = [ migrations.AddField( model_name='menuitem', name='price', ...
from flask import Flask, send_file, request, render_template from deferredvotes import * from sampleData import genData app = Flask(__name__) vote_fields = ("name", "vote", "defer") data_fields = ("placeholder") @app.route("/") def graph(): return render_template('index.html', src="data") @app.route("/sample") ...
# -*- coding: utf-8 -*- """ Created on Sat Mar 27 12:51:32 2021 @author: DELL """ from tkinter import * from tkinter import ttk from tkinter import filedialog from pytube import YouTube #pip install pytube3 from tkinter import messagebox from googleapiclient.discovery import build Folder_Name = "" #https://www.youtu...
class Solution: def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]: rtn = [0] * n for s, e, b in bookings: rtn[s-1] += b if e < n: rtn[e] -= b return itertools.accumulate(rtn)
from datetime import datetime from django.http import JsonResponse, HttpResponseRedirect from django.shortcuts import render, get_object_or_404, redirect from .forms import CreateQuizForm, CreateQuestionForm from .models import Quiz, Riddle from django.views.generic import ListView from users.models import Profile fr...
import numpy as np from sympy import Matrix import string import random dim = 2 #n차원 행렬 cipher = string.ascii_uppercase def main(): mode = input("Select Encrypt or Decrypt:") if mode == 'Encrypt': encrypt() elif mode == 'Decrypt': decrypt() def encrypt(): key = np.matrix([[1, 2], [2, 5]...
""" 22 minutes. Accepted. Runtime beats 34.77 % of python submissions """ class Solution(object): def count_decodings(self, s, memo): if memo[len(s)] != -1: return memo[len(s)] number_of_ways = 0 if int(s[-1:]) > 0 and len(s) - 1 >= 0: number_of_ways += self.count_d...
from __future__ import division from corpus import Document, NamesCorpus, ReviewCorpus, BagOfWords, Name, BagOfWordsBigram from maxent import MaxEnt from unittest import TestCase, main, skip from random import shuffle, seed import sys def accuracy(classifier, test, verbose=sys.stderr): correct = [classifier.clas...
import os import argparse import tarfile from tqdm import tqdm import numpy as np import pandas as pd from keras.models import load_model from keras.preprocessing import image from keras.preprocessing.image import ImageDataGenerator from PIL import Image Image.MAX_IMAGE_PIXELS = None os.environ['HDF5_USE_FILE_LOCKING'...
from django.urls import path from django.conf.urls import url from django.views.generic import RedirectView from .utils.tftp_serv import tftp_run import threading from .views import index, devices, snmp, login, set_snmp, netflow_setting from .views import save_conf, set_conf, restore_os, reset_pass urlpatterns = [ p...
# # disk area - preserving mapping # # Contribution # Author: Yanshuai Tu # Created: 2018 / 05 / 07 # Revised: # CIDSE, ASU, http: // gsl.lab.asu.ed from algebra.face_area import * from algebra.compute_bd import * from algebra.compute_edge import * import scipy.sparse as sp def dot(A,B, axis = 0): return np.su...
# Licensed Materials - Property of IBM # Copyright IBM Corp. 2016 import unittest import sys import itertools import test_vers from streamsx.topology.topology import * from streamsx.topology.tester import Tester from streamsx.topology import schema import streamsx.topology.context from streamsx.topology.schema import...
class Solution: """ @param x: An integer @return: The sqrt of x """ def sqrt(self, x): # write your code here if x == 0: return 0 index = 1 while index * index < x: index *= 10 nums = range(index+1) start, end = 0, len...
from aiogram import Bot, Dispatcher from aiogram.bot.api import TelegramAPIServer from aiogram.dispatcher.storage import BaseStorage from aiogram.types import BotCommand, ParseMode from aiohttp import BasicAuth from asyncpg.pool import Pool from ..models.base import startup_db from ..utils import config from .filters....
#!/usr/bin/env python ''' Release management for an LCATR package. It assumes to be run from top-level of the package source. ''' import os from subprocess import check_call from pkg_resources import parse_version default_git_remote = 'origin' def find_srcdir(): pkgdir = os.path.realpath('.') pkgname = ...
import datetime import pymongo from ..v2 import mongo class WorkerManager(object): def __init__(self): self.collection = mongo.db.workers self.collection.create_indexes([ # 设置对应的机型 pymongo.IndexModel( [ ('hostname', pymongo.ASCENDING),...
import pandas as pd import random # Excel Parser def createdf(filename, sheetname): try: xlsx = pd.ExcelFile(filename) dataframe = pd.DataFrame(pd.read_excel(xlsx, sheetname, index_col=False)) return(dataframe) except FileNotFoundError: print("File not found") # Fitness Funct...