text
stringlengths
38
1.54M
N = int(input()) ans = N-1 def get_steps(a, b): return (a-1) + (b-1) for i in range(1, int(N**0.5)+1): if N % i == 0: d = N // i ans = min(ans, get_steps(i, d)) print(ans)
import requests from bs4 import BeautifulSoup import os f = requests.get('http://tieba.baidu.com/p/3181528205').text #用BS解析html s = BeautifulSoup(f,'lxml') print(s) s_imgs = s.find_all('img', pic_type = "0") i=0 if not os.path.exists('北理校花'): os.makedirs('北理校花') path = os.path.join(os.getcwd(),"北理校花") for s_img in...
#-*- coding: UTF-8 -*- __author__ = 'Childe' #数组最大和 #输入一个数组A,求其连续子数组的最大和 def max_sub_array(A): if len(A)==0: return 0 curr_max=A[0] max_value=A[0] i=1 while i<len(A): curr_max=max(A[i],curr_max+A[i]) max_value=max(max_value,curr_max) i+=1 return max_value print(...
from openerp.osv import osv, fields class res_users(osv.Model): _inherit = "res.users" def im_search(self, cr, uid, name, limit=20, context=None): """ search users with a name and return its id, name and im_status """ result = []; # find the employee group group_employee = sel...
# -*- encoding: utf-8 -*- """ @File : prac1371.py @Time : 2020/5/20 7:53 下午 @Author : zhengjiani @Email : 936089353@qq.com @Software: PyCharm 不重复遍历子串的前提下,快速求出区间字母出现的次数->前缀和 一个区间可以用两个前缀和的差值,得到某个字母的出现次数 [(00000)2,(11111)2] """ class Solution: def findTheLongestSubstring(self, s: str) -> int: res = 0 ...
class Scene(object): def enter(self): pass class Engine(object): def __init__(self, scene_map): pass def play(self): pass class Death(Scene): r def enter(self): pass class CentralCorridor(Scene): def enter(self): print "You wake up after being knocked out by an alien." print "directly in front ...
def LED(number_repeat, teste_one, teste_two, teste_three): res_teste_one = list(map(int, str(teste_one))) sum = 0 for item_one in res_teste_one: if((item_one == 1)): sum += 2 elif((item_one == 2)): sum += 5 elif(item_one == 3): sum += 5 eli...
from torchvision import datasets, models, transforms import torch import os from dataloader import get_loader from model import * import pickle import numpy as np from tqdm import tqdm import matplotlib import cv2 import matplotlib.pyplot as plt from PIL import Image device = torch.device('cuda' if torch.cuda.is_avail...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys sys.path.append("../") import rospy import socket from std_msgs.msg import Int32, ColorRGBA import sensor_msgs.point_cloud2 as pc2 from sensor_msgs.msg import PointCloud2 import geometry_msgs.msg import moveit_msgs.msg import moveit_commander from supervisor.ms...
# Generated by Django 3.0.5 on 2020-04-25 22:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('payment_gateway', '0002_auto_20200425_1228'), ] operations = [ migrations.AddField( model_name='payment', name='amou...
#! /usr/bin/env python # -*- coding:utf-8 -*- """ 项目启动入口 """ import sys, os.path from wsgiref.simple_server import make_server sys.path.append(os.path.dirname(__file__)) from kyger.kgcms import App if __name__ == '__main__': httpd = make_server('', 8000, App()) httpd.serve_forever()
import kNN """ test_data_set = [[0, 0], [1, 1], [2, 3], [5,-1]] data_set, labels = kNN.create_simple_data_set() for i in range(len(test_data_set)): t = kNN.classify0(test_data_set[i], data_set, labels, 3) print(t) """ d, l = kNN.file2matrix('datingTestSet2.txt') print(d) print(l)
from pytest import mark from leetcode.wiggle_sort_ii import Solution from . import read_csv @mark.timeout(2) @mark.parametrize('nums', read_csv(__file__, parser=eval)) def test_wiggle_sort(nums): Solution().wiggleSort(nums) for i, num in enumerate(nums): if i % 2 == 0: if i == 0: ...
from abc import ABCMeta, abstractmethod import csv import json from ast import literal_eval as le class Searchclient: def execute(): a = input('Search by author, title, or year? -> ') b = input() class Interface: def __init__(self): self.__modes = {'none': None, 'add': AddClient, '...
# Can we find the lowest common ancestor of two nodes given the root of a binary tree? # Definition for a Node. class Node: def __init__(self, val): self.val = val self.left = None self.right = None self.parent = None def lowestCommonAncestor(self, root, p, q): # Purpose: Recursi...
import codecs import functools import json import os from dataclasses import dataclass from typing import Optional, Dict, Any from pyconfr_2019.grpc_nlp.protos import TweetFeaturesService_pb2_grpc from pyconfr_2019.grpc_nlp.tools.find_free_port import find_free_port from tweet_features.tweet_features_server import se...
# coding: utf-8 from procset import ProcSet from oar.lib.hierarchy import find_resource_hierarchies_scattered from oar.kao.slot import intersec_itvs_slots, Slot def find_resource_hierarchies_job(itvs_slots, hy_res_rqts, hy): ''' Find resources in interval for all resource subrequests of a moldable instanc...
import logging import textwrap import time from dataclasses import dataclass from datetime import datetime from typing import List, Dict, Any import feedparser from bs4 import BeautifulSoup from feedparser import FeedParserDict as FeedDict from .enums import PostStatus from .models import Post, Feed DataDict = Dict[...
import scipy.io as sio import matplotlib.pyplot as plt import seaborn as sns import os os.environ['CUDA_DEVICE_ORDER'] = "PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = "1" import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from sklearn.decomposition import PCA def run(ratio): input_...
from frmwk import flask_framework, orm_db from flask.ext.login import login_required, current_user from flask.ext.babel import gettext from flask import render_template, flash, request, redirect, url_for, g from frmwk import administrator_permission # from flask import Response from frmwk.model.mdRole import Role fro...
# -*- coding: utf-8 -*- """ Created on Tue Feb 25 19:39:55 2020 @author: juliu """ from os import chdir, mkdir from urllib.request import urlopen from datetime.datetime import today def build_archive(): months = ['January','February','March','April','May','June','July', 'August','Septe...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Aug 4 21:35:16 2019 @author: george """ import numpy as np def make_supervised( states_matrix, value = 0): """ takes a matrix with values (in general 0 or 1) and produces a matrix with 1 and -infinities replacing the value "val...
def findShift(encrypted): import os.path file = os.path.join("data", "lowerwords.txt") f = open(file) wordsClean = [w.strip() for w in f.read().split()] max_shift = 0 max_value = 0 for sh in range(26): setShift(sh) print(sh, encrypt(encrypted)) n = 0 for word ...
from fastdtw import fastdtw, dtw from scipy.spatial.distance import euclidean import scipy.io.wavfile as wav from DTW.extract_features import extract from utility import * from proj_paths import * models = dict() def load_models(): for raw_model_name, model_path in collect_files(DTW_MODELS_PATH): models[...
from django import forms class AddForm(forms.Form): product=forms.ChoiceField(choices=[('valve','Valve')]) oee = forms.IntegerField() quality = forms.IntegerField() volume = forms.IntegerField()
# -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- # Copyright © 2021, Spyder Bot # # Licensed under the terms of the MIT license # ---------------------------------------------------------------------------- """ Custom toolbar plugin. """ # Third-party imports from...
# Solution to https://leetcode.com/problems/roman-to-integer/ class Solution: def romanToInt(self, s): """ :type s: str :rtype: int """ symbol_to_val = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 5...
import lxml.etree from file_path_collect import feed_broken_xml_path as path try: tree1 = lxml.etree.parse(path) except lxml.etree.XMLSyntaxError as err: print(err) print() parser = lxml.etree.XMLParser(recover=True) tree = lxml.etree.parse(path, parser) print(parser.error_log) print() print(tree.findall('{...
ulang = str while ulang: print ("PROGRAM CEK HARGA\n") print ("MERK YANG TERSEDIA\n 1.IMP\n 2.Prada\n 3.Gucci\n 4.Louis Vuitton\n") print ("Size yang tersedia: s, m, l\n") print("masukan pilihan anda: ") pilihan = int(input()) print("masukan size yang diinginkan: ") size = input() if pil...
""" Copyright (C) 2018-2020 Intel Corporation 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 i...
import numpy as np class DataGen: """ class tha represent data generator for iter over large amount of data """ def __init__(self, X: np.ndarray, y: np.ndarray, shuffle=False, batch=32) -> None: """ :param X: data in shape (number of training examples X number fo attributes X dimensio...
from django.db.models import Q from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import permissions, status from django.contrib.auth.models import User from main.serializers import UserSerializer from rest_framework.authtoken.models import Token from main.model...
#library managment system class Library: def __init__(self,listofbooks): self.listofbooks = listofbooks def books_availabel(self): print("Books available") print() for books in self.listofbooks: print(books) def lend_books(self): if requestedbo...
import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow import keras def plot_series(time,series,format="-",start=0,end=None): plt.figure(figsize=(10,6)) plt.plot(time[start:end],series[start:end],format) plt.xlabel("time") plt.ylabel("value")...
import heapq def kthSmallest(mat, n, k): min_heap=[] for i in range(n): for j in range(n): heapq.heappush(min_heap,mat[i][j]) while k: x=heapq.heappop(min_heap) k-=1 return x
"""Bài 08: Viết chương trình đếm số lần xuất hiện các từ đơn trong một đoạn văn bản""" str=input("Nhập đoạn văn: ") dem=0 a=str.split(" ") for i in range(len(a)): if len(a[i])==1: dem+=1 print( dem) str.split()
from django.conf.urls import url from . import views app_name ='pdf_reducer' urlpatterns = [ url(r'^$', views.FileUploadView.as_view(), name="index"), url(r'^test_upload', views.test_upload, name="test_upload") ]
from manager import * if __name__ == '__main__': manager = ZooManager() manager.test_zoo()
from __future__ import print_function from datetime import date import os import unittest from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # noinspection PyPep...
from PySide import QtCore, QtGui from p4_q2_ui import * from library import * import re, datetime class MagazineRow(object): def __init__(self, index, table, item, magazine): self.index = index self.item = item self.magazine = magazine self.iid = self.item['iid'] self.titleField = QtGui.QTableWidgetItem(sel...
import datetime import json class Curtida: def __init__(self): self.id = 0 self.data_insercao = datetime.datetime.now() self.data_alteracao = datetime.datetime.now() self.usuario_id = '' self.postagem_id = '' self.operacao = '' def definir_por_tupla(self, tupla...
import DiskUsage as DU import datetime import importlib.util spec = importlib.util.spec_from_file_location("Teamcity", "..\TA_TestReport\Teamcity.py") TC = importlib.util.module_from_spec(spec) spec.loader.exec_module(TC) if __name__ == '__main__': DU.DiskUsage.__init__(DU.DiskUsage, username="adacc", ...
from django import forms from blog.models import Article # Create the form class. class Article(forms.ModelForm): class Meta: model = Article fields = ('title', 'text') widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), 'text': forms.Textarea(at...
import math lis = [] for k in range(1, 76576501): a = (k*(k+1))/2 lis.append(a) #print lis #lis is the list of all the triangular numbers # cnt = 0 # answer = 0 # cnt = [] # for i in lis: # #print i # b = range(2, (i+1)) # #print b # for number in b: # del cnt[:] # if (i % number == 0): # cnt.append(nu...
import asyncio import io from datetime import datetime, timedelta import pandas as pd import requests import streamlit as st from openbb_terminal.core.plots.plotly_helper import OpenBBFigure, theme from openbb_terminal.core.session.current_system import set_system_variable from openbb_terminal.dashboards.stream impor...
#!/usr/bin/python3 import pygame from classes.wall import Wall from classes.block import Block from classes.player import Player from classes.ghost import Ghost black = (0,0,0) white = (255,255,255) blue = (0,0,255) green = (0,255,0) red = (255,0,0) purple = (255,0,255) yellow = (255,255,0) # Commands print("") pri...
#1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. # Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль. def my_dev(x,y): try: z = x / y except ZeroDivisionError: return return z x = int(input('Введите числител...
# Generated by Django 2.2.6 on 2020-04-15 16:08 from decimal import Decimal from django.conf import settings import django.contrib.postgres.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrati...
from generate_json_from_grid import findPath import json import numpy as np path = '../data/setting/LA/' moves = [(1,0), (0,1), (-1,0), (0,-1)] typemap = {"l": "turn_left", "s": "go_straight", "r": "turn_right"} turnmap = {"l": 1, "s": 0, "r": -1} LANE_WIDTH = 4 LANE_MAX_SPEED = 16.67 NMIDPOINTS = 5 BRANCH_LENGTH ...
from . import views from django.urls import path from .views import BlogPageView # #urlpatterns = [ # path('/blog/', BlogPageView.as_view(), name='blog'), #] #
"""woof""" class Dog: """woof woof""" def __init__(self, name, age): """initialise name & age attributes""" self.name = name.title() self.age = age def sit(self): """simulate dog sitting""" print(self.name + " is now sitting.") def roll_over(self): ""...
from django.core.mail import send_mail def email(message, message2): messages = f'Код регистрации: \n{message2}' send_mail( 'Код авторизации', messages, f'{message}', # почта куда [f'{message}'], # Это поле Кому: fail_silently=False, )
import pylibmc as memcache import logging from django.core.urlresolvers import reverse from django.conf import settings from django.http import HttpResponsePermanentRedirect from django.http import HttpResponseRedirect from core.api.resources import Site from core.api.exceptions import APIException from requests imp...
import pyautogui import time # for timer def invertMouse(seconds, minutes): currentMouseX, currentMouseY = pyautogui.position() pyautogui.moveTo def toFirstTab(seconds, minutes): # This returns you to your first tab on chrome pyautogui.hotkey('ctrl', '1') exit(); def alertMessages(seconds, minutes...
# -*- coding: utf-8 -*- # Generated by Django 1.11.23 on 2019-09-07 02:19 from __future__ import unicode_literals from django.db import migrations from chroma_core.migrations import ( build_tables, forward_trigger_template, backward_trigger_template, join, forward_function_str, backward_function...
#!/usr/bin/env python from __future__ import print_function import sys from lxml import etree import epitran import epitran.vector def main(fn): epi = epitran.Epitran('uig-Arab') vwis = epitran.vector.VectorsWithIPASpace('uig-Arab', ['uig-Arab']) tree = etree.parse(fn) root = tree.getroot() for t...
class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: count = Counter(nums) unique = list(count.keys()) n = len(unique) self.quickselect(n - k, 0, n - 1, count, unique) return unique[n - k:] def quickselect(self, k, left, right, count, unique): ...
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/thumby/flask-thumbor/wiki # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2015 thumby.io dev@thumby.io class FlaskThumbor: __name__ = "FlaskThumbor" def __init__(self,...
""" A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1,2,3 and 4. If all permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0,1, and 2 are 012, 021, 102, 120, 201, 210. What is the mi...
# Generated by Django 2.2b1 on 2019-02-14 03:12 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Character', fields=[ ...
N, K = map(int, input().split()) MOD = 10 ** 9 + 7 # 繰り返し自乗法 def power(x, n): if n == 0: return 1 tmp = power(x * x % MOD, n // 2) if n % 2 == 1: tmp = tmp * x % MOD return tmp # nCk def nCk(n, k): res = 1 for i in range(n - k + 1, n+1): res *= i res %= MOD ...
from django.contrib import admin from .models import Noticia,TipoNoticia # Register your models here. admin.site.register(Noticia) admin.site.register(TipoNoticia)
"""Write a program which accepts a string as input to print "Yes" if the string is "yes", "YES" or "Yes", otherwise print "No". Hint: Use input () to get the persons input""" string_input =input("Enter the String: ") if string_input == "yes" or "YES" or "Yes" : print("Yes") else: print("No")
#!/usr/bin/python #coding:utf-8 """ 详细见: https://ygobbs.com/t/lexusl%E4%B8%8E%E6%B8%B8%E6%88%8F%E7%8E%8B%EF%BC%881%EF%BC%89%EF%BC%9A%E5%8D%A1%E7%BB%84%E6%9E%84%E5%BB%BA%E7%9A%84%E6%A6%82%E7%8E%87%E5%AD%A6/102771 总数(Population Size)(N):卡组数量 成功数(Number of successes in population)(K):卡组里同名卡a的数量 样本大小(Sample Size)(n):抽卡...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Required - requests (必须) - pillow (可选) Info - author : "ZachBergh" - email : "berghzach@gmail.com" - date : "2016.6.21" ''' import requests import re import time import sys import json import rsa import os.path import binascii import datetime from bs4 import Bea...
import pandas as pd import numpy as np from sklearn.linear_model import LogisticRegression from load_data import load_train_data, load_test_data SAMPLE_SUBMIT_FILE='../input/sample_submission.csv' DIR='result_tmp' if __name__=='__main__': df=load_train_data() x_train=df.drop('target', axis=1) y_train=d...
#Django rest_framework from rest_framework import mixins, viewsets #Serializers from colegio.serializers.cursos import CursosModelSerializer #Models from colegio.models import Curso class CursoViewSet(viewsets.ModelViewSet): """Curso view set.""" queryset = Curso.objects.all() serializer_class = CursosMod...
import itertools import math import os import uuid from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.utils import timezone from django.contrib.auth import get_user_model from .conf import settings ...
import requests import json import time from modules.redis_functions import set_data, set_volatile_data from modules.misc import to_uuid from modules.config import influx_read_users, influx_timeout, influx_database_batch_size import logging logger = logging.getLogger(__name__) # Note: If two accounts share hosts with ...
from enum import Enum class LabelMode(Enum): AddFeature = "Feature" IgnoreFeature = "Ignore" class FactorUtils(object): @staticmethod def extract_factors(string_factors): string_factors = string_factors.strip() if not string_factors: return {} list_factors = [] ...
"""Lapis is an adaptable, performant, and interactive scheduling (Lapis) simulator""" __version__ = "0.3.0"
import numpy as np # 生成 4*4 的对角矩阵 print(np.eye(4)) """ ndarray 内部由以下内容组成: 一个指向数据(内存或内存映射文件中的一块数据)的指针。 数据类型或 dtype,描述在数组中的固定大小值的格子。 一个表示数组形状(shape)的元组,表示各维度大小的元组。 一个跨度元组(stride),其中的整数指的是为了前进到当前维度下一个元素需要"跨过"的字节数。 """
from django.urls import path from . import views from django.conf import settings from django.contrib.auth import views as auth_views app_name = 'account' urlpatterns= [ # url(r'^login/$',views.user_login,name="user_login"), # url(r'^login/$',LoginView,name="user_login"), path('login/', auth_views.LoginView.as_view...
import requests import json from bs4 import BeautifulSoup Steamkey = '9D8034447FC4F77028B94766E25A58C7' def achieve(game): soup = BeautifulSoup(requests.get('https://steamdb.info/search/?a=app&q=' + game + '&type=1&category=0').content, 'lxml') first = soup.find("tr", class_= "app") achievements = js...
import flask from flask import Flask, render_template, request import numpy as np import keras from keras.models import load_model from flask import Flask, request, jsonify import pickle app = Flask(__name__) @app.route('/') @app.route('/index.html') def index(): return flask.render_template('index.html') @ap...
__author__='lataman' import utilities, scheme import re, copy class schemeContainer(object): def __init__(self, lang): self.lang=lang #self.schemeList={"PL": "E:\\Skrypty\\PyVer\\standardRegex1.txt"} self.schemeList={"PL": "C:\\Users\\lataman\\Documents\\OCR\\PyVer\\ABIscript\\standardRege...
# -*- coding: utf-8 -*- """ Created on Sun Jan 28 2018 @author: Phillip """ import scrapy #import pandas as pd #scrapy crawl craig -o items.csv -t csv #Item class with listed fields to scrape class CraigslistItem(scrapy.Item): date = scrapy.Field() title = scrapy.Field() link = scrapy.Field() price...
# argv[1]: Arquivo com todos os atributos. # argv[2]: Arquivo com os atributos escolhidos. # argv[3]: Arquivo com dados para triagem. from sys import argv import io def ler_arquivo (path): try: with open (path, 'r') as content_file: content = content_file.read().split('\n') content.pop() return content ex...
from service.slack_service import SlackService as Slack from service.logging_service import LoggingService from service.node_service import NodeService _node_service = NodeService(Slack(), LoggingService()) _node_service.update_node()
from . import TargetMatcher from spacy.tokens import Token class ConceptTagger: """ConceptTagger is a component for setting an attribute on tokens contained in spans extracted by TargetRules. This can be used for semantic labeling for normalizing tokens, making downstream extraction simpler. """ n...
#!/usr/bin/env python import unittest, operator, random import numpy as MATH from numpy.random import randint, uniform from CGAPreprocessing import Utilities class DataFunction(object): """Simple container for keeping track of data or function (unbound method) - for simplicity, self.function contains the data or ...
#!python3 # -*- coding: utf-8 -*- """ @author: yanbin Any suggestion? Please contract yanbin_c@hotmail.com """ import os import wx import sys import time,datetime import numpy as np import math from time import clock from threading import Thread from wx.lib.embeddedimage import PyEmbeddedImage class ...
from __future__ import unicode_literals import base64 import datetime from django.db import models from django.utils import timezone from ckeditor.fields import RichTextField # SAMPLE DATA PLATFORM_BRAND_POSITION = ( ('0', 'Luxury'), ('1', 'Mid rage'), ('2', 'Discount') ) LOGISTICS_MODELS = ( ('0', ...
__author__ = 'Hannah' # Given an odd number, tests whether or not it is a prime number def is_prime_number(number): # Iterate through every possible odd factor for possible_factor in range(3, number, 2): # If something divides evenly into the number, then it is NOT prime if number % possible_factor == 0: retu...
from fairseq.models.roberta import XLMRModel import torch import torch.nn as nn import torch.nn.functional as F class XLMRForTokenClassification(nn.Module): def __init__(self, pretrained_path, n_labels, hidden_size, dropout_p=0.2, label_ignore_idx=0, head_init_range=0.04, device='cuda'): s...
""" WSGI config for DjangoDemo project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/ """ import os import sys from django.core.wsgi import get_wsgi_application # +++++...
D, G = map(int, input().split()) arr = [] n = 0 for i in range(D): arr.append([int(c) for c in input().split()]) n += arr[i][0] ans = 1e9 for bit in range(1 << D): sum = 0 num = 0 rest_max = -1 for i in range(D): if bit & 1 << i: sum += 100 * (i + 1) * arr[i][0] + arr[i][1]...
''' Created on 06/03/2012 @author: Evandro ''' class Poker(object): ''' classdocs ''' def __init__(self): ''' Constructor ''' def _converte_para_numero(self, carta): if carta == 'J': return 11 elif carta == 'Q': ...
""" Image Converter class that takes an image in RGB/CMYK and returns a similar image made of only ASCII chars. alternatively one can opt to only pixelate the image. Created by Trevor Dalton on 8/28/19 """ from PIL import Image, ImageDraw, ImageFont from concurrent.futures import ProcessPoolExecutor import fu...
# -*- coding: utf-8 -*- class Solution: def longestValidParentheses(self, s: str) -> int: if len(s) == 0: return 0 while len(s) > 0 and (s[:1] == ')' or s[-1:] == '('): s = s[1 if s[:1] == ')' else 0 : -1 if s[-1:] == '(' else len(s)] validString="" #当前有效的字符串 ...
from cms.apps.media.models import File from django.shortcuts import get_object_or_404 from django.views.generic import RedirectView from sorl.thumbnail import get_thumbnail class ImageView(RedirectView): # If they change the source image, we don't want to be showing the old image. # Sorl uses memcached to ret...
try: x=int(raw_input()) y=int(raw_input()) except ValueError: print("enter the integers only") else: print(pow(x,y))
from hashlib import sha256 import json import time import os,ast from flask import Blueprint,render_template,request,Response,jsonify import base64 from Crypto.Cipher import AES class Block: def __init__(self,data,t=time.time(),prev=0,index=0): self.index=index self.timestamp=time.ctime(t) ...
from numpy import ndarray from typing import List from ..path.sampling import SamplingSetting from .types import SolveMethod, CostFuntionType class OptSettings: """ Settings for the numerical optimization based planners. """ def __init__( self, q_init: ndarray = None, max_iter...
class Constants: RICHNESS_NULL = 0 RICHNESS_POOR = 1 RICHNESS_OK = 2 RICHNESS_LUSH = 3 TREE_SEED = 0 TREE_SMALL = 1 TREE_MEDIUM = 2 TREE_TALL = 3 TREE_BASE_COST = [ 0, 1, 3, 7 ] TREE_COST_SCALE = 1 LIFECYCLE_END_COST = 4 DURATION_ACTION_PHASE = 1000 DURATION_GATHER_PHASE = 200...
from defs import * # he's at 465k into rcl5 i'm at 161k into rcl 4 # 102k into rcl 5 i'm at 388k into rcl 4 js_global.USERNAME = 'Lisp' js_global.VERSION = 1842 js_global.CONTROLLER_SIGN = 'Territory of Lisp [' + str(js_global.VERSION) + ']' js_global.CREEP_SAY = False js_global.BUILD_ORDER = [STRUCTURE_SPAWN, STRU...
# -*- coding:utf-8 -*- import os import copy import json from verify_new22 import stringdiffanalysis temp_file_name = "./~compaer_tools_null_file.tmp" class Compare(object): """ 比对类 """ def __init__(self, is_atom=False): """ Init :param is_atom:是否为原子级比对, 如果为是将不进行更低级别的比对 ...
import pickle from CONFIG import * import os with open(os.path.join(LINK_DATA,"data.picke"),"rb") as out_put_file: user_dict, item_dict, event_dict, ui_dict, iu_dict, ur_dict,ir_dict = pickle.load(out_put_file) print(ui_dict)
import socket hostname = socket.gethostname() IPAddr = socket.gethostbyname(hostname) def socket_create(): try: global host global port global s global IPAddr host = IPAddr port = 9999 s = socket.socket() except: print('socket creation error') ...
from projects.inflection.scripts.lib.clear_dir import clear_out_dir if __name__ == '__main__': clear_out_dir('py')