text
stringlengths
8
6.05M
# coding=utf-8 '''返回不同格式的约拍模型 @author:黄鑫晨 @attention: Model为模型,model为模特 ''' import time from Database.models import get_db from Database.tables import AppointLike, AppointmentImage, CompanionImg, User, AppointEntry, WApCompanionImage, \ AppointmentInfo, UserImage from FileHandler.Upload import AuthKeyHandler from ...
money, c50000, c10000, c5000, c1000 = 0, 0, 0, 0, 0 money = int(input("고환할 돈은 얼마?")) c50000 = money // 50000 money %= 50000 c10000 = money // 10000 money %= 10000 c5000 = money // 5000 money %= 5000 c1000 = money // 1000 money %= 1000 print('\n 500원짜리 => %d개' % c50000) print(' 500원짜리 => %d개' % c10000) print(' 500...
#input # ;>;<>;<>-<>;<[->++<][->+<]>:<:>;<;[->+>+<<]>>[-<<+>>]<<[->+<];>++++<>;<>;<>;<>;<+:>-:<;[->+>+<<]>>[-<<+>>]<<>-<>;<>:<>;<>:<[->+>++<<];+:>-:<:[>+<-]>++++<>:<>:<[->+>++<<]>-<[->++<][->+<]>-<:[->+<]+:>-:<:>: # 7 14 11 4 2 7 7 10 12 17 5 2 11 14 2 class Brainfuck: def __init__(self): self.stack = [0] * 100 ...
# python 2.7.3 import sys import math [n, m, p] = map(int, sys.stdin.readline().split()) m = {} for i in range(n): s = raw_input() for c in s: m[c] = m.get(c, 0) + 1 for i in range(p): s = raw_input() for c in s: m[c] = m.get(c, 0) - 1 ans = [] for i, v in m.items(): ans.extend(i * v) ans.sort() print ''...
from django.conf.urls import patterns, url from accounts import views as accounts # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', url(r'^remind-me/(?P<single_event_id>\d+)/$', accounts.remind_me, name='remind_m...
import math for a in range(1,21): for b in range(1,21): c = math.sqrt(a**2+b**2) if c<=20: if c == math.floor(c): print "Side1 = %d\tSide2 = %d\tHypotenuse = %d" %(a, b, c)
from bs4 import BeautifulSoup import requests import random for i in range(1,4): html_text=requests.get('https://www.gettyimages.in/photos/telangana-indians?family=creative&license=rf&page='+str(i)+'&phrase=telangana%20indians&sort=mostpopular#license').text #This iterates over 4 pages of images soup=Beautiful...
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html from scrapy import Request from scrapy.pipelines.images import ImagesPipeline from scrapy.exceptions import DropItem import re i...
# -*- coding:utf-8- *- import numpy as np import cv2 img = np.zeros((512,512,3), np.uint8) cv2.line(img, (0, 0), (511, 511), (255, 0, 0), 5) cv2.rectangle(img, (384, 0), (510, 128), (0, 255, 0), 5) cv2.circle(img, (447, 63), 50, (0, 0, 255),-1) cv2.ellipse(img, (256, 256), (100, 50), 90, 0,360, (0, 255, 0), -1) ...
"""Author Arianna Delgado Created on June 18, 2020 """ """Create a Lambda that will return YES if a given number is even and NO if the given number is odd.""" f = lambda x: 'Yes' if x % 2 == 0 else 'No' print (f(2))
from __future__ import division import os import sys import pandas as pd import numpy as np pilot_sub = int(sys.argv[1]) final_sub = int(sys.argv[2]) sims = int(sys.argv[3]) conditions = int(sys.argv[4]) modality = sys.argv[5] adaptive = sys.argv[6] threshold = sys.argv[7] basefolder = sys.argv[8] outfolder = sys.argv...
""" Home Page application view. Loads the home page from React. """ from django.shortcuts import render def home(request): """Return React front-end.""" return render(request, 'index.html')
# -*- coding: utf-8 -*- # for python3 # # 特徴抽出した正例・負例の位置関係をグラフ化する # python chk_feature.py {pcsv} {ncsv} # pcsv : 正例のCSVファイル名 # ncsv : 負例のCSVファイル名 import sys import numpy as np import matplotlib.pyplot as plt import pandas as pd from pandas import DataFrame # Main if __name__ == '__main__': # 特徴量データを入力する # 1...
# -*- coding: utf-8 -*- # !/usr/bin/env python import itchat @itchat.msg_register(itchat.content.TEXT) def print_content(msg): message = msg['Text'] itchat.auto_login() itchat.run()
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI Limited # # 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 ...
VTABLE(_Main) { <empty> Main } VTABLE(_A) { _Main A } FUNCTION(_Main_New) { memo '' _Main_New: _T0 = 4 parm _T0 _T1 = call _Alloc _T2 = VTBL <_Main> *(_T1 + 0) = _T2 return _T1 } FUNCTION(_A_New) { memo '' _A_New: _T3 = 4 parm _T3 _T4 = call _Alloc _T5 = VTBL...
from __future__ import unicode_literals # from django.conf import settings
import pytest import pandas as pd @pytest.fixture def missing_data(): """Sample data for grouping by 1 column """ data_dict = {'a': [2, 2, None, None, 4, 4, 7, 8, None, 8], 'b': ['123', '123', '123', '234', '456', '456', '789', '789', '789', '...
# Write a function filter_long_words() that takes a list of words # and an integer n and returns the list of # words that are longer than n. def filter_long_words(num, listOfWords): out_list = [] for word in listOfWords: if len(word) > num: out_list.append(word) return out_list listOf...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('course_selection', '0009_remove_semester_name'), ] operations = [ migrations.AddField( model_name='section', ...
import os import webapp2 import jinja2 from google.appengine.ext import db import urllib from xml.dom import minidom template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape=True) class Handler(webapp2.RequestHandler...
import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, "Add Menu Items") p = wx.Panel(self) self.txt = wx.TextCtrl(p, -1, "new item") btn = wx.Button(p, -1, "Add Menu Item") self.Bind(wx.EVT_BUTTON, self.OnAddItem, btn) sizer = wx.B...
# -*- coding: utf-8 -*- """ Configuration file for the main ctip test suite. Created on Sat Jul 9 23:48:43 2016 @author: Aaron Beckett """ import sys, os import pytest sys.path.append(os.path.join(os.getcwd(), '.')) sys.path.append(os.path.join(os.getcwd(), '..')) pytest_plugins = ['helpers_namespace'] #######...
import os from flask import Flask, render_template, request, send_from_directory, jsonify from flask_mail import Mail, Message from flask_table import Table, Col import etherscan.accounts as accounts import config ''' Init ''' app = Flask(__name__) app.config['MAIL_SERVER'] = config.MAIL_SERVER app.config['MAIL_POR...
from django.shortcuts import render, render_to_response from django.http import HttpResponse, Http404, HttpResponseRedirect from django.core.urlresolvers import reverse # Create your views here. def teacher(r): return HttpResponse('这是teacher的一个视图') def v2_exception(r): raise Http404 return HttpResponse('ok') def ...
import csv """ Functions: create_portfolio() ---> creates a stock portfolio from user input best_investments() ---> finds the best x number of investments in a portfolio during a certain period worst_investments() ---> finds the worst x number of investments in a portfolio during a certain period ...
# -*- encoding:utf-8 -*- from mako import runtime, filters, cache UNDEFINED = runtime.UNDEFINED __M_dict_builtin = dict __M_locals_builtin = locals _magic_number = 5 _modified_time = 1281454040.870805 _template_filename='/Library/Python/2.6/site-packages/pcpbridge/templates/pcast_error.mako' _template_uri='/pcast_error...
from datetime import date, timedelta from django.contrib.auth.mixins import UserPassesTestMixin from django.contrib.auth.decorators import login_required from django.core.paginator import PageNotAnInteger, Paginator, EmptyPage from django.db.models import Q from django.http import Http404, HttpResponseRedirect, HttpRes...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # class BTree: class Node: def __init__(self): self.sons = [] self.keys = [] def __repr__(self): return 'Node' + str(self.keys) + str(self.sons) def _lower_bound(self, key): ...
import cv2 as cv import numpy as np img = cv.imread('../sample/affine.png') img2 = cv.imread('../sample/median.png') kernel = np.ones((5,5), np.float32)/25 dst = cv.filter2D(img, -1, kernel) # img_blur = cv.blur(img, (5,5)) img_blur = cv.GaussianBlur(img, (5,5), 0) median = cv.medianBlur(img2, 5) img3 = cv.imread...
from itsdangerous import TimedJSONWebSignatureSerializer from mall import settings from itsdangerous import BadSignature def verify_token(id,email): s = TimedJSONWebSignatureSerializer(settings.SECRET_KEY,expires_in=3600) token = s.dumps({'id':id,'email':email}) return token.decode() def decode_token(toke...
#coding=utf-8 from django.http import HttpResponse from django.utils import simplejson import logging import time logger = logging.getLogger(__name__) def grid_filter_toggle(request): # time.sleep(5) result=[] for i in range(10): result.append({'UV':'60','source' :'http://www.sina.com.cn','name':'...
# -*- coding: utf-8 -*- import tensorflow as tf import tensorflow_hub as hub import numpy as np import time import requests from flask import Flask, request, jsonify from elasticsearch import Elasticsearch # Flask Server 설정 app = Flask(__name__) flask_host = "localhost" flask_port = "5000" # ElasticSearch Address ...
from ._builtin import Page, WaitPage from .translator import system_start from .models import Constants from .utility import nanoseconds_since_midnight as labtime from django.core.cache import cache from django.conf import settings class PreWaitPage(WaitPage): pass # def after_all_players_arrive(self): ...
#!/usr/bin/python # -*- coding: utf-8 -*- from openravepy import * env = Environment() # create the environment env.SetViewer('qtcoin') # start the viewer env.Load('data/katanatable.env.xml') # load a scene robot = env.GetRobots()[0] # get the first robot raw_input("Press Enter to start...") manip = robot.GetActiveM...
# 自己的解法超时了,判断确实很僵硬 # 评论区有个思路我类似但是判断有优化的解法,见solution2 # solution3的大体思路是相同的,实现更妙一些 class Solution: def solveNQueens(self, n): """ :type n: int :rtype: List[List[str]] """ ans = [['.' for _ in range(n)] for _ in range(n)] ret = [] self.tback(n, ans, n, ret, -1)...
""" Django settings for quartz_project project. Generated by 'django-admin startproject' using Django 3.0.1. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ impor...
# Must install more_itertools and scikit-bio(need to run "python setup.py install" from source for skbio) # Written by Griffin Calme (2016) # Runs a Needleman-Wunsch global sequence alignment and iteratively merges the overlapping sequences # Takes a line-separated text file of overlapping peptide subsequences and o...
# Create your views here. from django.shortcuts import get_object_or_404, render_to_response from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from django.template import RequestContext from comptetence.models import Candidat def index(request): return render_t...
from flask import Flask, request, abort import numpy as np import cv2 import json import base64 app = Flask(__name__) @app.before_first_request def startup(): global face_cascade face_cascade = cv2.CascadeClassifier('cascade.xml') @app.route("/detect", methods=['POST']) def detect(): global face_cascade ...
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect from django.shortcuts import render, redirect from django.utils.http import is_safe_url from django.conf import settings from .models import Container, Item from .forms import ContainerForm, ItemForm ALLOWED_HOSTS = settings.ALLOWED_HOSTS def ...
from collections import namedtuple from webpreview import OpenGraph, TwitterCard def get_webpreview(url): """Gets the web preview for URL.""" WebPrev = namedtuple('WebPrev', ['title', 'description', 'image']) og = OpenGraph(url, {'og:title', 'og:description', 'og:image'}) tc = TwitterCard(url, {'twi...
from collections import namedtuple, deque from apscheduler.schedulers.asyncio import AsyncIOScheduler __all__ = [ 'CB_FUNC', 'CD_TIME', 'F_AT', 'F_MSG', 'F_PRIV_GRP', 'F_REGEX', 'WHITELIST', 'Holder' ] CB_FUNC = 0 CD_TIME = 1 F_PRIV_GRP = 2 WHITELIST = 3 F_REGEX = 4 F_MSG=5 F_AT=6 class Holder(object): ...
from time import time, sleep from random import randint import requests import numpy as np import pandas as pd from bs4 import BeautifulSoup from emails.send_emails import Email from src.general_functions import GeneralFunctions class IhubData(Email, GeneralFunctions): def __init__(self, verbose=0, delay=True): ...
""" @File: settings.py @CreateTime: 2019/12/9 下午8:45 @Desc: 数据库的配置信息 """ # mysql CONFIG = { 'default': 'mysql', 'mysql': { "driver": "mysql", "host": "127.0.0.1", "database": "test_one", "user": "root", "password": "123456", "prefix": "", "port": 3306 ...
#!/usr/bin/python3 # Why do we need to use functions? # 1. Because you can pass different parameters to the same function # 2. Because it represent a unit of computation, which can be reused # 3. Functions can be reused by other people # examples of functions def add(x,y): #here x and y are parameters of the functi...
"""Create Reply Table Revision ID: e1e764225513 Revises: eb3c24fa735b Create Date: 2018-12-07 23:56:29.728584 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = 'e1e764225513' down_revision = 'eb3c24fa735b' branch_labels = None...
# filters RNIE output by score, write file with RNIE scores over 20 and make scatterplots import argparse import os.path import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import collections import sys import os.path #############################################################...
fib = [0,1] print(fib[-1]) print(fib[-2]) for x in range(1,int(input('fib '))): fib.extend([int(fib[-1]+fib[-2])]) print(fib[-1]) input()
import math import time num_times = 3 v = 0 while v <= 2.0 * math.pi * num_times: ledpower = 0.1 * (-math.cos(v) + 1) #print ledpower setLEDBack(ledpower) v = v + .03 time.sleep(0.01) setLEDBack(0)
# Dwight Kappl # Word count def lengthSent(txt): temp = txt.split() tempLen = len(temp) print("There are " + str(tempLen) + " words.") return tempLen #usr = input("Enter a sentence: ") #lengthSent(usr)
# -*- mode:python; coding:utf-8; tab-width:4 -*- import Ice Ice.loadSlice('-I {} cannon.ice'.format(Ice.getSliceDir())) import Cannon import numpy as np import math import itertools def matrix_add(A,B): order=A.ncols C=Cannon.Matrix(order,[]) for i in range(order**2): C.data.append(sum([A.data[i]]+[B.data[i]]))...
''' Function: define the network Author: Charles 微信公众号: Charles的皮卡丘 ''' import numpy as np '''define the network''' class Network(): def __init__(self, fc1=None, fc2=None, **kwargs): self.fc1 = np.random.randn(5, 16) if fc1 is None else fc1 self.fc2 = np.random.randn(16, 2) if fc2 is None else fc2 self.fitn...
import re from lib.common.abc import Vulnerability class XSS(Vulnerability): name = 'CROSS-SITE SCRIPTING (XSS)' keyname = 'xss' def __init__(self, file_path): super().__init__(file_path) def find(self): return self._find(r'<.+>.*(\'|").*(\$[a-zA-Z0-9_]+).*(\'|").*</.+>|<.*(\'|").*...
""" Serialize data to/from CSV """ import os import csv from functools import partial from orun.core.serializers import python, base from orun.apps import apps from orun.db import connection class Deserializer(base.Deserializer): def deserialize(self, update=False): """ Deserialize a stream or st...
def pares_rango(lim_inf, lim_sup): def main(): lim_inf = int(input("Valor 1: ")) lim_sup = int(input("Valor 2: ")) pares_rango(lim_inf, lim_sup) if __name__=='__main__': main()
import sys import argparse from math import sqrt, pi, exp, fabs import matplotlib.pyplot as plt from scipy import integrate from .utils.numerical_integration import composite_trapezoidal, composite_simpson def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--a', type=float, default=0) ...
def two_teams(sailors): a = [] b = [] for i in sailors: a.append(i) if sailors[i] > 40 or sailors[i] < 20 else b.append(i) return [sorted(a),sorted(b)] print(two_teams({'Smith': 34,'Wesson': 22,'Coleman': 45,'Abrahams': 19}), [['Abrahams', 'Coleman'],['Smith', 'Wesson'] ]) print(two_teams({'Fernandes': 1...
print('Para finalizar o progama digite \033[34m999\033[m') cont = soma = n = 0 n = int(input('Digite um número: ')) while n != 999: soma += n cont += 1 n = int(input('Digite um número: ')) print(f'Foram digitados {cont} número(s) e a soma entre eles foi {soma}')
from PyQt5.QtWidgets import QWidget, QLabel from PyQt5.QtGui import QPainter, QColor from PyQt5.QtGui import QIcon, QPixmap class GameScreen(QWidget): def __init__(self, parent): super(GameScreen, self).__init__(parent) self._parent = parent self._music_on = False sel...
# 314 Binary Tree Vertical Order Traversal # # Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column). # # If two nodes are in the same row and column, the order should be from left to right. # # Examples: # Given binary tree [3,9,20,null,null,15,7],...
''' mortgage_loan_calc1.py calculate the monthly payment on a mortgage loan tested with Python27 and Python33 ''' import math def calc_mortgage_bank(bank_principal, bank_interest, bank_years): ''' given mortgage loan principal, interest(%) and years to pay calculate and return monthly payment amount '''...
from Login.LoginPage import * from PersonalCertificate.Certificate import * from selenium import webdriver import yaml driver = webdriver.Chrome() driver.maximize_window() driver.implicitly_wait(10) with open("../PersonalCertificate/certificate.yaml", "r", encoding="utf8") as file: data = yaml.load(file) usernam...
import matplotlib import numpy as np import tensorflow as tf import tf_agents import math from tf_agents.agents.dqn import dqn_agent from tf_agents.drivers import dynamic_step_driver from tf_agents.environments import suite_gym from tf_agents.environments import tf_py_environment from tf_agents.environments import py_...
#!/usr/bin/env python import time import pyrealsense2 as rs import numpy as np import cv2 from PIL import Image import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import json DS5_product_ids = ["0AD1", "0AD2", "0AD3", "0AD4", "0AD5", "0AF6", "0AFE", "0AFF", "0B00", "0B01", "0B03", "0B07"] def f...
"""this application deals with autocompletion. It needs to : - redis - redis python - python requests - Jquery autocomplete It also uses django_webpack. """ from django.apps import AppConfig class AutocompleteConfig(AppConfig): name = 'autocomplete'
from django import forms from .models import Table from site_web.models import Site class TableForm(forms.ModelForm): #sites = MultipleChoiceField(queryset=Site.objects.all()) class Meta: model = Table fields = "__all__"
from __future__ import unicode_literals, print_function, generators, division from manager import Manager from model import Message from utils import get_first_element from view import View __author__ = 'pahaz' view = View('main.html') manager = Manager('data.db') def index(method, get, post, headers): messages...
import requests import time from impl.submit_flag import submit_flag ''' 提交所有flag的函数,该文件不需要更改。 ''' def submit_all(flagset): success_submit = 0 fail_submit = 0 for pair in flagset: time.sleep(0.1) target = pair[0] flag = pair[1] if submit_flag(target=target,flag=flag) == True: print(" [√] 提交{}的{}成功!".for...
# coding: utf-8 import time import pymongo import logging import datetime import bisect from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from modules import Unimac, Init_sta1, init_db from sqlalchemy import or_, and_ from sqlalchemy import text from sqlalchemy import distinct import pymy...
from django.db.models import Q from haystack import indexes from .models import Profile class ProfileIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) name = indexes.EdgeNgramField(model_attr='name') surname = indexes.EdgeNgramField(model_attr='surna...
class Taxonomy: ''' Taxonomy represents a Linnean category (order, family, or genus) If a Taxonomy object's level is 'genus', then its item list contains strings of the form <species-name> [(<common-name>)] If the Taxonomy object's level is 'Order' or 'Family', then its item list contains T...
from jinja2 import Template from lxml import html import os template=''' cache_size={{ cache_size }}&nrbanks={{banks}}&rwports=0&read_ports=1&write_ports=1&ser_ports=0&output={{bits_out}}&technode=35&temp=300& data_arr_ram_cell_tech_flavor_in=0&data_arr_periph_global_tech_flavor_in=0&tag_arr_ram_cell_tech_flavor_in=...
from .unicycle_controller import UnicycleController
# Create your views here. from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt # import key from project settings.py from imagely.settings import CLARIFAI_API_KEY # import python ClarifaiApp from clarifai.rest import ClarifaiApp cf_app = ClarifaiApp(api_key=CLARIFAI_API_KEY) # Vi...
import serial import os import struct class PyRfid(object): RFID_STARTCODE = 0x02 RFID_ENDCODE = 0x03 __serial = None __rawTag = None def __init__(self, port = '/dev/ttyUSB0', baudRate = 9600): """ Constructor @param string port @param integer baudRate """ ...
# -*-coding:utf-8-*- # @ Auth:zhao xy # @ Time:2021/5/11 12:39 # @ File:user_sql.py from sqlalchemy.orm import sessionmaker # 用以创建session类 from sqlalchemy import create_engine # 保存数据库连接信息 url = "mysql+mysqlconnector://root:zxy19981013@172.18.0.3:3306/test" # 数据库用户名密码地址端口及库名 engin = create_engine(url,pool_size=5) # 数...
''' author: juzicode address: www.juzicode.com 公众号: juzicode/桔子code date: 2020.6.23 ''' print('\n') print('-----欢迎来到www.juzicode.com') print('-----公众号: juzicode/桔子code\n') import keyword print('keyword.kwlist:\n',keyword.kwlist) #调用kwlist,使用keyword.作为前缀
import scrapy import re import datetime import os from scrapy.exporters import CsvItemExporter ################################### URLname = 'loanURLs.csv' try: URLdir = os.path.join(os.getcwd(),'../../../',URLname) # please change to relative links to the loanURLs.csv file if necessary ex...
# # Text-related utilities # import os import string import sys import textwrap # This is not available on Debian 9, so if it isn't, roll our own. # DEBIAN: Go back to using secrets directly when Debian 9 goes away. try: import secrets SECRETS_CHOICE = secrets.choice SECRETS_RANDBELOW = secrets.randbelow...
parameters_v1 = { 'learning_rate': 0.003, 'boosting_type': 'gbdt', 'objective': 'cross_entropy', 'metric': 'binary_logloss', 'sub_feature': .684263, 'num_leaves': 6, 'max_depth': 3, 'min_data': 26, 'verbosity': 0, 'bagging_fraction': 0.85, 'lambda_l1': 0, 'lambda_l2': 0, ...
""" java error:java.lang.error 代表严重错误,比如:内存溢出-》死循环-》修改代码逻辑 exception:java.lang.Exception 1/0-》简易程序处理-》可以处理 error无法处理,异常是建议处理 异常是不正常程序的状态 异常处理: 错误: 错误是指由逻辑或者语法等导致一个程序无法正执行问题 特点: 有些错误是无法预知的 异常: 异...
a=[1,2,3,4,5,6] print (a) #adding one string with another string a=[1,2,3] b=a+[4,5,6] a=[1,2,3]*2
from time import time start = time() sum_list = [] for i in range(1,101): sum_list.append(i**2) print((sum(range(1,101))**2) - sum(sum_list)) print "1 : Seconds", time() - start
'''Utilities to help manage the various environments required in the LHCb software.''' import subprocess, select, timeit, exceptions, pprint, tempfile, os strippingDVVersions = {'stripping21' : ('v36r2', 'x86_64-slc6-gcc48-opt'), # Should be 'v36r1p3' but it crashes when importing anything Stripping related. ...
import configparser as ConfigParser import sys import pandas as pd import os from datetime import datetime import time import re import owners import datacleansing as dtc class csv: pcol = { "Indicator": [], "Type": [], #"Value": [], "Organization": [], "Rating": [], ...
import os import pygame import kezmenu from team import Team class Custom(object): running = True def main(self, screen): clock = pygame.time.Clock() background = pygame.image.load(os.path.join('img', 'background.png')) menu = kezmenu.KezMenu( ['Done!', lambda: Team().ma...
#!/usr/bin/env python2.7 from bottle import route, run, Bottle, request import random ''' Define the app ''' tile_calc_app = Bottle() @tile_calc_app.get('/') @tile_calc_app.get('/tilecalc') def main_page(): ''' Display main form ''' html = ''' <h1>Welcome to Tile Calc</h1> <p>Enter the ...
import pykov import numpy as np from multiprocessing import Pool from collections import OrderedDict def update_word_probabilities(word_probabilities, index, reward): word_probabilities[index] += reward summ = sum(word_probabilities) corrected_word_probabilities = list(map(lambda i: float(i) / summ, word_...
#_*_ coding:utf-8 _*_ def Questao21_Lista3(N): S = 0 for i in range(1, 100): if i % 2 != 0: S += (i /(float(i/2)+1)) print "%.2f" % S def main(): n=input("Insira N: ") Questao21_Lista3(n) if __name__=="__main__": main()
import requests from bs4 import BeautifulSoup import json from urllib import request, parse import os import time import lxml.html import re import urllib.parse from opencc import OpenCC import pandas as pd import numpy as np import jieba import csv cc = OpenCC('s2t') jieba.load_userdict('E:\YoutubeYear\...
#!/usr/bin/python import os import time from SpeechToTextEngine import SpeechToTextEngine from TextToSpeechEngine import TextToSpeechEngine """ This Python executable is for omega-desktop. The trigger word is omega. """ TRIGGER_WORD = "omega" class VoiceControl(): def __init__(self): self.stt = SpeechToTextE...
import nltk import numpy from fuel.transformers import AgnosticSourcewiseTransformer, Transformer, SourcewiseTransformer from .utils import sort_dict from PIL import Image, ImageOps class OneHotTransformer(AgnosticSourcewiseTransformer): def __init__(self, data_stream, nclasses, **kwargs): self.nclasses ...
from ED6ScenarioHelper import * def main(): # 卢安 CreateScenaFile( FileName = 'T2310 ._SN', MapName = 'Ruan', Location = 'T2310.x', MapIndex = 1, MapDefaultBGM = "ed60015", Flags = 0, Ent...
#!/usr/bin/python ''' Longest Substring with Same Letters after Replacement Problem Statement # Given a string with lowercase letters only, if you are allowed to replace no more than ‘k’ letters with any letter, find the length of the longest substring having the same letters after replacement. Example 1: Input: St...
""" This extends the HTMLCalendar class from calendar. All aesthetic adjustments should be made in the mdStyle.css function """ from calendar import HTMLCalendar import datetime # Extending HTMLCalendar class from calendar class mdCalendar(HTMLCalendar): def __init__(self,firstweekday=6): self.firstweekda...
import random import cv2 import gym import numpy as np class MinesweeperEnv(gym.Env): metadata = {'render.modes': ["ansi", "rgb_array", "human"]} reward_range = (-float(1), float(1)) def __init__(self, width=8, height=8, mine_count=10, flood_fill=True, debug=True, punishment=0.01, seed=...
## need this every time... i think? from unittest import TestCase ## import py file in the directory import area class TestShapeAreas(TestCase): def test_triangle_area(self): # a trianlge with a heaight of 4 and a base of 5 should have an area of 10 self.assertEqual(10, area.triangle_area(4,5))
import matplotlib.image as mpimg import os import sys sys.path.append('H:\programingProject\Python\TextBox\\') from ssd_test import visualization def save_detected_pic(img_dir,rclasses, rscores, rbboxes): img = mpimg.imread(img_dir) visualization.plt_bboxes(img, rclasses, rscores, rbboxes, ...
import cv2 import matplotlib.pyplot as plt import matplotlib.patches as patches import os import math import settings import torch from torchvision.transforms import Normalize from torchvision.ops import nms from PIL import ImageDraw, Image import numpy as np from jinja2 import Template from settings import BASE_DIR fr...