text
stringlengths
38
1.54M
class Node: def __init__(self, value): self.value = value self.next = None def add(self, value): self.next = Node(value) def middle_node(self): current_node = self if not current_node.next: return current_node.value else: double_node...
from flask import Flask, request, session, redirect, url_for, render_template, flash app = Flask(__name__) app.secret_key = 'hello' @app.route('/login', methods = ["POST", "GET"]) def login(): if request.method == 'POST': session['user'] = request.form['nam'] return redirect(url_for('user')) e...
import json import typing import itertools import collections import numpy as np from real_human_team.util import print_board class State: # Note: By subclassing namedtuple, we get efficient, immutable instances # and we automatically get sensible definitions for __eq__ and __hash__. # This class stores ...
from decimal import Decimal as D, getcontext getcontext().prec = 100 def contfrac_to_frac(seq): num, den = 1, 0 for u in reversed(seq): num, den = den + num * u, num return num, den def CF(num1, n=10): a = [int(num1)] num = num1 % 1 # Mantissa while num != 1: ...
"""Definitions for an algebra on spin (angular momentum) Hilbert spaces, both for integer and half-integer spin""" from abc import ABCMeta from collections.__init__ import OrderedDict import sympy from sympy import sqrt, sympify from ..core.hilbert_space_algebra import LocalSpace from ..core.operator_algebra import L...
num = int(input("请输入")) if (num %2) == 0: print("%d偶数"%(num)) else: print("%d奇数"%(num))
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-24 05:06 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('inventory_email_support', '0003_auto_20170323_2255'), ] operations = [ migr...
def recProduct(a, b): if a == 0 or b == 0: return 0 if b > 0: return a + recProduct(a, b - 1) elif a > 0 and b < 0: return b + recProduct(a - 1, b) else: return 0 - a + recProduct(a, b + 1) print(recProduct(-10, -2))
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from collections import namedtuple import random import matplotlib import matplotlib.pyplot as plt import math #data duration=3000; Ilength=10; ts=torch.arange((duration+Ilength-1)); amplitude=2; ys=(amplitude*(torch.cos(ts/...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # from https://robertvandeneynde.be/ from OpenGL.GL import * from OpenGL.GL import shaders import ctypes import pygame from vecutils import * pygame.init() vertex_shader = """ #version 330 in vec4 position; void main() { gl_Position = position; } """ fragment...
import contextlib import matplotlib import matplotlib.pyplot as plt import numpy as np import scipy.stats from sklearn.linear_model import LinearRegression matplotlib.style.use('classic') plt.rcParams['axes.prop_cycle'] = plt.cycler('color', 'bgrcmyk') matplotlib.rcParams['savefig.dpi'] = 60 matplotlib.rcParams['figu...
from datetime import datetime import os from flask import Flask, request, render_template, jsonify from werkzeug.exceptions import HTTPException from app import database, routes, brand from app.helpers import user_manager def create_app(): app = Flask(__name__) app.config.from_mapping( SECRET_KEY=o...
# in the previous sections, we assumed a linear relationship between # explanatory and response variables but we can have sth like : # y = w0 + w1x + w2x²x² + ... + wdx^d # we will use PolynomialFeatures transformer class from scikit # to add a quadratic term (d = 2) to a simple reg problem with # one explanatory var...
import asyncio from aiohttp import web import sys import json def get_throughput(output_file): rps_value = [] with open(output_file, 'r') as ufile: for rpsline in ufile.readlines(): rps=rpsline.split("Throughput(ops/sec),")[-1] try: rps_value.append(float(rps)) ...
import configparser def read_configs(): config = configparser.ConfigParser() config.read('config.ini') config.add_section('MODEL_WEIGHTS') for model_section in filter(lambda x : x.endswith('MODELS'), config.sections()): for model in config[model_section]: items = config[model_sectio...
while True: # Choice Collection choice = int(raw_input( "1 Thing\n2 Thing\n3 Thing\n0 Exit\n\n>>" )) if choice not in range(4): continue if choice == 1: print "Thing 1" elif choice == 2: print "Thing 2" elif choice == 3: print "Thing 3" # Terminate Operations - Must hold value 0 at this point else: ...
# coding:utf8 from PyQt4.QtGui import * import sys import os reload(sys) sys.setdefaultencoding('utf-8') class Remind: def __init__(self): self.app = QApplication(sys.argv) def remind_success(self,file_number): QMessageBox.information(None, 'INFORMATION', file_number + u'上传成功,请查看Renderbus网站!'...
import os, sys sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../')) from constants import CRConstants from s3 import S3Agent class FileSystemFactory(object): ''' Factory implementation which can be used to instantiate concrete file storage system agents. ''' file...
# -*- coding: utf-8 -*- import codecs import os from nltk import ParserI, TaggerI, word_tokenize from inco.nlp.freeling_base import FreeLingBase from inco.nlp.parse.tree.freeling_tree_builder import FreeLingTreeBuilder __author__ = 'Matias Laino' class FreeLing(FreeLingBase, ParserI): """ Wrapper class fo...
class Solution: def longestPalindrome(self, s): """ :type s: str :rtype: str """ flag = False max_str = main_max = '' text3 = s[0:] for index, value in enumerate(s): # print(text[index:], end='=') # print(text[:-index]) ...
from .models import Restaurant from django import forms class RestaurantForm(forms.ModelForm): class Meta: model=Restaurant fields='__all__'
''' ''' import sys import os import configparser import random import urllib.request import datetime import time import re from locale import str from bs4.tests.test_docs import __metaclass__ from bs4 import BeautifulSoup import asyncio pwd=os.getcwd() #get pwd cnf_path=os.path.join(os.path.dirname(os.getcwd()),'Co...
import numpy as np import pytest from pysweep import sweep from pysweep.data_storage.webui_writer import WebUIWriter def test(): param = lambda s, n, v: {"x": {"unit": "V", "value": v, "independent_parameter": True}} measure_values = np.linspace(-1, 1, 4) g = (i for i in measure_values) measure = ...
# Спортсмен занимается ежедневными пробежками. # В первый день его результат составил a километров. # Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. # Требуется определить номер дня, на который общий результат спортсмена составить не менее b километров. # Программа должна принимать значени...
#SOURCE:https://github.com/hay/wiki-text-nlp/blob/master/wiki-text-nlp.ipynb import urllib.request import re import nltk import operator from bs4 import BeautifulSoup import spacy import textacy import requests import json # nltk.download('punkt') # nltk.download('stopwords') scraped_data = urllib.request.urlopen('http...
# # earthquake_tsunami function # """This function returns a callable object representing an initial water displacement generated by a submarine earthqauke. Using input parameters: Required length along-stike length of rupture area (km) width down-dip width of rupture area (km) strike azimuth (degrees, mea...
import os import tempfile from detect_secrets import SecretsCollection from detect_secrets.settings import default_settings from prowler.lib.check.models import Check, Check_Report_AWS from prowler.providers.aws.services.awslambda.awslambda_client import awslambda_client class awslambda_function_no_secrets_in_code(...
# This code snippet is adapated from AWS ECS Documentation # The plan is 'create' environments by uploading Secrets to AWS Secrets Manager # and retrieve the secrets upon deployment. # The idea is the container runner will have an assumed IAM role granting access # specifically to the secret import os import logging f...
from django.contrib import admin from import_export.admin import ImportExportModelAdmin from lifequotesbot.models import Questions, Answers, ChatRecord, NoRecordFoundResponse # Register your models here. class AdminQuestions(ImportExportModelAdmin): list_display = ('question_keyword',) search_fields = ('quest...
def evenOdd(number): if number%2 == 0: print('Even Number') else: print('Odd Number') def factorial(number): f = 1 for i in range(1,number+1): f = f * i print(f)
import tensorflow as tf #from tensorflow.python.ops import ctc_ops as ctc import numpy as np import random import time import datetime from PIL import Image from tools import DataLoader from tools import CharactorSource input_image_path = '/home/melt61/PictureGenerator/GenImage10/423.jpg' input_image = Image.open...
import logging import numpy from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity class CosineSimilarity(): def cosinesimilarity(self,doc1,doc2): logging.basicConfig(level=logging.DEBUG,filename='logs/cosine.logs', filemode='w') doc1 = op...
#继承 class Animal(): def eat(self): print("好吃") def drink(self): print("好喝") def __haode(self): print("私有") class Dog(Animal): def tiao(self): print("tiao") dog=Dog(); dog.eat(); dog.tiao(); class Cat(object): def __init__(self, name, color="白色"): self.name =...
import tkinter import segyio from threading import Thread from time import sleep from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import matplotlib.pyplot as plt import numpy as np '''Создаем граффический интерфейс, и вставляем в него 5 окон из матплотлиба''' root = tkinter.Tk() root.wm_title("Track plo...
from pathlib import Path import pytest import fpdf from fpdf.errors import FPDFException from fpdf.html import px2mm from test.conftest import assert_pdf_equal HERE = Path(__file__).resolve().parent class MyFPDF(fpdf.FPDF, fpdf.HTMLMixin): pass def test_html_images(tmp_path): pdf = MyFPDF() pdf.add_...
import FWCore.ParameterSet.Config as cms subjet_variables = ["px", "py", "pz", "e", "pt", "m", "eta", "phi"] Subjetter = cms.EDProducer("SubjetProducer", src=cms.InputTag("ca12PFJetsCHS"), nSubjets=cms.uint32(4), )
import os, cv2 def rename(file_path, new_file_path): os.rename(file_path, new_file_path) def delete(file_path): os.remove(file_path) def getFiles(folder_path, full_path=True): files = [] for f in os.listdir(folder_path): path = os.path.join(folder_path, f) if os.path.isfile(path): ...
class Node: # membuat class node terlebih dahulu def __init__(self, data=None): # membuat konstruktor dengan atribut data, left dan right self.data = data self.left =None self.right = None class Tree: # membuat class tree def __init__(self): # konstruktor dengan atribut root se...
import pickle import sqlite3 class DefaultTablesTable(object): def __init__(self): self.table_name = self.__class__.__name__ def get_create_query(self, **kwargs): return f"CREATE TABLE {self.table_name} (id INTEGER PRIMARY KEY," \ f"table_name VARCHAR(255),kwargs BLOB);" ...
from django.urls import re_path from channels.routing import URLRouter from django.core.asgi import get_asgi_application from . import consumers urlpatterns = URLRouter([ re_path(r'events/', consumers.ServerSentEventConsumer.as_asgi()), re_path(r'^.*$', get_asgi_application()) ])
#!/usr/bin/python # -*- coding: utf-8 -*- """ Usage example: $ python gen.py ru.txt result.txt 10 """ import argparse import random parser = argparse.ArgumentParser(description='String generator.') parser.add_argument('alphabet', type=str, help='path to the alphabet file') parser.add_argument(...
import numpy as np import matplotlib.pyplot as plt N = 55 for i in range(1,N+1): Rres = np.loadtxt('./Rres/Rres'+str(i)+'.txt') Vres = np.loadtxt('./Vres/Vres'+str(i)+'.txt') sigDfft = np.loadtxt('./sigDfft/sigDfft'+str(i)+'.txt') plt.contourf(Rres,Vres,sigDfft) plt.title('Range-Doppler Map') p...
# -*- coding=utf-8 -*- from app import db from werkzeug.security import generate_password_hash, check_password_hash from flask_login import UserMixin, AnonymousUserMixin from app import login_manager import datetime from flask import current_app from itsdangerous import TimedJSONWebSignatureSerializer as Serializer imp...
import json import time import unittest import datetime from dataserv_client import cli from dataserv_client import api from dataserv_client import exceptions fixtures = json.load(open("tests/fixtures.json")) addresses = fixtures["addresses"] url = "http://127.0.0.1:5000" class AbstractTestSetup(object): def s...
import inspect import logging from functools import wraps logger = logging.getLogger("app.client") logger.setLevel(logging.INFO) fh = logging.FileHandler("logs/app.client.log", encoding="utf-8") formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s") fh.setFormatter(formatter) logger.addHandler(fh) de...
from __future__ import absolute_import import collections, json, re from django.contrib.contenttypes.models import ContentType from django.db import transaction class JSONLD(object): subject_re = re.compile('^</(?P<content_type>\d+)/(?P<object_id>.+)/>$') rdfa_re = re.compile('^<http://viejs.org/ns/(?P<prop...
# -------------------------------------------------------- # PYTHON PROGRAM # Here is where we are going to define our set of... # - Imports # - Global Variables # - Functions # ...to achieve the functionality required. # When executing > python 'this_file'.py in a terminal, # the Python interpreter will load...
# Utils from Utils.file import write_json from Utils.preprocessing import remove_seen def inference(question_data, model, result_path) : question_data = question_data[0] like_data = [question_data['like']] dislike_data = [question_data['dislike']] like = model.inference(like_data, save=False)[0] ...
import requests from datetime import datetime api_key = '758093beb3bd2776951491e29bcab162' city = input("Enter the city name: ") complete_api_link = "https://api.openweathermap.org/data/2.5/weather?q="+city+"&appid="+api_key api_link = requests.get(complete_api_link) api_data = api_link.json() #variables to ...
from hiveminder.flower import Flower from hiveminder.utils import (distance_between_hex_cells, nearest_hex_cell, furthest_hex_cell, apply_command_and_advance, is_on_course_with) import pytest from hiveminder.game_params import DEFAULT_GAME_PARAMETERS @pytest...
from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * from delete_dialog import Ui_delete_dialog as Ui_Delete_Dialog from add_book import Ui_Dialog as Ui_Add_Dialog from Edit_dialog import Ui_Dialog as Ui_Edit_Dialog from library import Ui_MainWindow import my_functions as lib class Add_...
from datetime import datetime, timedelta from threading import Timer import requests import json import webbrowser from pprint import pprint import arrow #testing boy TELEGRAM_URL = 'https://api.telegram.org/bot{}'.format('large string') # the large string is the bmsqbot token TELEGRAM_SEND_MESSAGE_URL =...
from fastapi import Form import json import requests_async as requests from config import configs from serving import Controller, mapping from serving.controller import json_wrapper class ReviewPredictionController(Controller): def __init__(self, fast_api): super().__init__(fast_api, base_url='/review'...
from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib.auth.forms import AuthenticationForm from .forms import RegisterForm from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout # Create your views here. def login(request): ...
# -*- coding: utf-8 -*- # @Time : 2020/12/12 18:47 # @Author : fcj11 # @Email : yangfit@126.com # @File : browser.py # @Project : crm自动化测试 from selenium import webdriver def chrome(): #谷歌 driver = webdriver.Chrome() driver.maximize_window() driver.implicitly_wait(30) return driver
def orderinglogicForThreadFromEXPID(i): # id1=int(s1.split("/")[-1].split("-")[6]) # ratelist1=s1.split("/")[-1].split("-")[7].split(".") # ratelist1.pop() # rate1=float(".".join(ratelist1)) # # return id1-rate1 expID = i.split("/")[-1].split("-")[-2] print expID return int(expID) d...
import numpy ARCHIVO_BANCOS = 'bancos.txt' ARCHIVO_CUENTAS = 'cuentas.txt' ARCHIVO_NOVEDAD = 'novedad.txt' def subir_bancos(): bancos = {} with open(ARCHIVO_BANCOS, 'r') as f: for line in f: reg = line.split(',') bancos[reg[0]] = reg[1] return bancos def subir_cuentas(): ...
""" @file @author John C. Linford (jlinford@paratools.com) @version 1.0 @brief This file is part of the TAU Performance System @section COPYRIGHT Copyright (c) 2013, ParaTools, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that t...
#! /usr/bin/env python # coding=utf-8 # ================================================================ # # Author : miemie2013 # Created date: 2020-06-10 10:20:27 # Description : 配置文件。 # # ================================================================ class YOLOv4_Config_1(object): """ ...
from __future__ import annotations from typing import Any import sys # 保存するキャッシュの数XはX=3としました class Node(object): def __init__(self, data: Any, next_node: Node = None, prev_node: Node = None) -> None: self.data = data self.next = next_node self.prev = prev_node class LinkedList(object): ...
import sys def solution(n, lines): answer = -1 l, r = 1, max(lines) while l < r: total = 0 mid = (l + r) // 2 for line in lines: total += (line // mid) if total >= n: answer = mid l = mid + 1 elif total < n: r = mid - ...
""" Program name: animated_color_wheel_1.py Objective: Draw a progressive arc of a circle while mixing controlled amounts of red, green and blue. Animate the display of corresponding hex color value. Keywords: circle, arc, progressive color wheel, hex color, animation =========================================...
# -*- coding: utf-8 -*- import time import threading import Queue class TasksRunner(object): tq = Queue.Queue(maxsize = -1) def __init__(self): t = threading.Thread(target=self.run, args=()) t.start() def put(self, task): self.__class__.tq.put(task) def run(self): ...
from tkinter import * from quiz_brain import QuizBrain THEME_COLOR = "#375362" class QuizInterface: def __init__(self, quiz: QuizBrain): self.quiz = quiz self.window = Tk() self.window.title("Quiz GUI") self.window.config(padx=20, pady=20, bg=THEME_COLOR) self.score_labe...
# Generated by Django 3.1.5 on 2021-01-29 08:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('libraryapp', '0003_book_description'), ] operations = [ migrations.AddField( model_name='book', name='count', ...
import cv2 import face_recognition import pyttsx3 import os import numpy as np from keras.preprocessing.image import img_to_array from keras.models import load_model engine = pyttsx3.init() voices = engine.getProperty('voices') engine.setProperty('voice', voices[1].id) path='trainingData' detection_model_path = 'haarc...
''' Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. O programa vai perguntar o valor da casa, o salário do comprador e em quantos anos ele vai pagar. Calcule o valor da prestação mensal, sabendo que ela não pode exceder 30% do salário ou então o empréstimo será negado. ''' casa = flo...
# Simple program for correcting mistake values in a list odd = [2, 4, 6, 8] # change the 1st item odd[0] = 1 print(odd) # change 2nd to 4th items odd[1:4] = [3, 5, 7] print(odd)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #a test for traverse directory __author__ = 'AlbertS' import os import os.path f = open('outline.txt','w') def dfs_showdir(path, depth): if depth == 0: print("root:[" + path + "]") temp="root:[" + path + "]"+'\n' f.write(temp) for item i...
# RBFNN import numpy as np import matplotlib.pyplot as plt import pandas as pd import xlrd from pandas import DataFrame from numpy.linalg import pinv import math from sklearn.cross_validation import train_test_split from sklearn.cluster import KMeans def find_max(x): index = 0 maxi = x[index] for i in ran...
#이 파일은 nester.py모듈이며 print_lol()함수 하나를 제공합니다. 이 함수는 포함된 리스트가 있을 경우 그것을 포함해서 리스트의 모든 힝목을 화면애 츌력합니다 def print_lol(the_list, ident=False , level=0): """이 함수는 the_list한 이름의 인자를 갖고 있으며, 파이썬 리스트를 받습니다. 이 리스트는 항목으로 포함할 수 있습니다. 매 라인마다 리스트에 있는 항목이 하나씩 재귀적으로 화면에 출력됩니다. """ for each_item in the_list: if isinstance...
import pexpect, sys, time, re def setcommand( s ): print "setting the debug command" s.sendline('shelltimeout -1') s.expect('DEBUG>', timeout = 90) #s.sendline('debug sip-reg-state') #s.expect('DEBUG>', timeout = 90) #s.sendline('sdump') #s.expect( pexpect.EOF, timeout = 60) #print s.before # s.sendline('debu...
from googleapiclient.discovery import build from google.auth.transport.requests import Request from google_auth_oauthlib.flow import Flow, InstalledAppFlow from googleapiclient.http import MediaFileUpload from googleapiclient.errors import HttpError from time import sleep from threading import Thread from tzlocal impor...
import frappe from frappe.desk.moduleview import get_desktop_settings, get @frappe.whitelist() def get_menu(parent=None, is_root=False): if is_root: return get_desktop_settings() elif parent: return get(parent)
#!/usr/bin/env python import sys import re def is_number(n): """This is an implementation of `is_number` and is not needed in this exercise ;). >>> is_number('44') True >>> is_number('44.0') # tricky :D False >>> is_number('44.5') False >>> is_number('not a number') False """...
import json from css_html_js_minify import html_minify import re from os import path from PIL import Image import base64 from subprocess import Popen, PIPE pattern = re.compile('{image:[a-zA-Z0-9-_]*}') def beautify_css(style): sass = Popen( ['sass', '--stdin', '--no-source-map'], stdin=PIPE, ...
import codecs from json import JSONDecoder, JSONDecodeError import requests # import ujson as json import re import time import datetime import json import threading import os ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%d-%m %H:%M:%S') # small byte to mb gb etc convertor suffixes = ['B',...
#!/usr/bin/env python3 import sys def parse_in(std_in): return [s.strip() for s in std_in] def plus(a, b): return a + b def times(a, b): return a * b OPER_DICT = {'+': plus, '*': times} def add_parens(text): _open = 1 for idx, l in enumerate(text): if l == '(': _open += 1 ...
import cv2 from pykinect2 import PyKinectV2 from pykinect2.PyKinectV2 import * from pykinect2 import PyKinectRuntime import numpy as np import Kinect.const as const import time from kivy.graphics.texture import Texture import imutils class SimpleCalibrator(object): def __init__(self): self.xyratio=1.0 ...
# Generated by Django 3.0 on 2020-01-03 14:57 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0033_auto_20200103_2022'), ] operations = [ migrations.AlterField( model_name='work_exp', name...
import streamlit as st import pandas as pd # naziv temeljen na nazivu dataseta st.title("Cardiovascular disease prediction") st.write('') st.write('') st.markdown("**To choose attributes, click on the arrow in the upper left corner of the screen**") st.subheader("Data information: ") st.write("Systolic ...
# Copyright The OpenTelemetry Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
#proyecto final - BDD en Python - Fritz, Mariano from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, Sequence, ForeignKey, Table, Text from sqlalchemy.orm import sessionmaker, relationship #para exportar los datos import csv eng...
#!/usr/bin/env python import socket from time import sleep import MySQLdb as mysql import time host = '192.168.1.116' port = 6789 def setupSocket(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) return s def sendReceive(s, message): s.send(str.encode(message)) re...
from app.base.func import CSVToList from sqlalchemy.sql import func from sqlalchemy.orm import relationship from sqlalchemy import or_ from flask import current_app from werkzeug.security import generate_password_hash, check_password_hash from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from flask...
""" 1.While Loop Basics a.create a while loop that prints out a string 5 times (should not use a break statement) b.create a while loop that appends 1, 2, and 3 to an empty string and prints that string c.print the list you created in step 1.b. 2.while/else and break statements a.create a while loop that does...
from Flask_project.sweater import app if __name__ == '__main__': # если программа запускается через этот файл, т-е. app = Flask(этот файл) app.run(debug=True) # запуск Flask(вывод ошибок на сайт)
import time print("Welcome to the Prime Number App") flag = True while flag: print("Enter 1 to determine if a specific number is prime.") print("Enter 2 to determine all prime numbers within a set range.") choice = int(input("Enter your choice 1 or 2: ")) if choice == 1: num = int(input(...
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: left = 0 right = 0 ans = 0 dict = {} while right<len(s): pos = dict.get(s[right], -1) if pos<left: # 未重复-1;或者重复值在滑动窗口左端边界外 dict[s[right]] = right ans =...
import numpy as np def g_str(x): str = hex(x).partition('x')[2].partition('L')[0] while len(str) < 2: str = '0' + str return(str) def main(start, end, steps): r_min = int(start[:2], 16) r_max = int(end[:2], 16) r_grad = [int(a) for a in np.linspace(r_m...
#!/usr/bin/env python ################################################################################ # COPYRIGHT(c) 2018 STMicroelectronics # # # # Redistribution and use in source and binary forms, w...
""" samplefunction8 class3 return if a number is even or odd """ def returnEO(number): if number % 2 == 0: strout = "Even" else: strout = "Odd" return strout print (returnEO(5)) print (returnEO(6)) print (returnEO(-4)) print (returnEO(-1.2))
from django.shortcuts import render from django.http import HttpResponse from docker import Client import os import datetime import json # Create your views here. def home(request): date = datetime.datetime.now() messages = 'Hi ' hours = int(date.strftime('%H')) if hours<12: messages+= 'Good Mo...
import heapq n, m = map(int, input().split()) day = [[] for _ in range(10**5+1)] for _ in range(n): a, b = map(int, input().split()) day[a].append(b) benefit = [] heapq.heapify(benefit) ans = 0 for i in range(1, m+1): for j in day[i]: heapq.heappush(benefit, -j) print(benefit) if benefit: ...
#coding: UTF-8 archivo = open("CPdescarga.txt", "r") archivo.read(512) print archivo while True: linea = archivo.readline() if not linea: break print linea
# Dev's Journey # Terrance Corley import cmd import textwrap import sys import os import time import random screen_width = 100 #### Player Setup #### class player: def __init__(self): self.name = '' self.job = '' self.location = 'b2' self.game_over = False myPlayer = player() #### Title Screen ##...
__all__ = () from datetime import datetime as DateTime from hata import Embed from hata.ext.slash import Button, InteractionResponse, Row from .calendar_events import CALENDAR_EVENTS from .constants import ( COLOR_CODE_RESET, BUTTON_BACK_DISABLED, BUTTON_CLOSE, BUTTON_NEXT_DISABLED, DAY_NAMES_SHORT, EMOJI_BACK, ...
import pathlib import re import requests import pandas from pkg_resources import parse_version # Minimum number of available spaces spaces = 2 # Comment out trailheads you'd like to start from exclude = [ # 'HI → LYV', # 'HI → Sunrise/Merced Lakes (Pass through)', # "Glacier Point → LYV", ...
"""URL definition for the beer site""" from django.urls import path, include from beers.views import user, validation, contest import beers.api.views as api_views api_patterns = [ path('players/', api_views.PlayerList.as_view(), name='player-list',), path('players/<slug:user__username>', api_views.PlayerDeta...
#!/usr/bin/python3 # Copyright (c) 2018, 2019 Peter Palfrader # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, m...