text
stringlengths
38
1.54M
from keras.layers import Layer, InputSpec from keras import initializers, regularizers, constraints import keras.backend as K from keras_contrib.utils.test_utils import to_tuple class PELU(Layer): """Parametric Exponential Linear Unit. It follows: `f(x) = alphas * (exp(x / betas) - 1) for x < 0...
''' Function for extending pytorch. ''' import torch import torch.utils.data as data import torch.multiprocessing as multiprocessing from torch.utils.data.sampler import SequentialSampler, RandomSampler, BatchSampler from torch.utils.data.dataloader import ExceptionWrapper import collections import sys import traceback...
import sys sys.setrecursionlimit(10**8) N, M = (int(x) for x in input().split()) MOD = 998244353 cnt = 0 def f(n): if n == 2: return (M * (M-1)) % MOD return (M * pow(M-1, n-1, MOD) - f(n-1) + MOD) % MOD print(f(N))
# # xcPROJECTNAMEASIDENTIFIERxcAppDelegate.py # xcPROJECTNAMExc # # Created by xcFULLUSERNAMExc on xcDATExc. # Copyright xcORGANIZATIONNAMExc xcYEARxc. All rights reserved. # from Foundation import * from AppKit import * from threading import Thread from twisted.internet import reactor import sys from aether.serv...
from django.apps import AppConfig as DjangoAppConfig class AppConfig(DjangoAppConfig): name = "unplugged.services.api" verbose_name = "API Service" label = "services_api" def ready(self): from .handler import APIServicePlugin # NOQA
# -*- coding: utf-8 -*- """ Created on Mon Jun 10 15:26:43 2019 @author: Administrator """ import math class Jsteg: def __init__(self): self.sequence_after_dct=None def set_sequence_after_dct(self,sequence_after_dct): self.sequence_after_dct=sequence_after_dct self.available_info_l...
import sys _module = sys.modules[__name__] del sys config = _module eval_tvqa_plus = _module maskrcnn_voc = _module bounding_box = _module boxlist_ops = _module voc_eval = _module utils = _module inference = _module main = _module model = _module cnn = _module context_query_attention = _module encoder = _module model_u...
import os import subprocess import sys SOURCE_ROOT = os.path.dirname(os.path.dirname(__file__)) def main(): # Proxy all args to node script script = os.path.join(SOURCE_ROOT, sys.argv[1]) subprocess.check_call(['node', script] + [str(x) for x in sys.argv[2:]]) if __name__ == '__main__': sys.exit(main())
""" 用递归方法绘制谢尔宾斯基三角形 """ import turtle def sierpinski(degree, points): # degree表示阶数 colormap = ['red', 'blue', 'green', 'yellow', 'orange', 'white'] drawTriangle(points, colormap[degree]) # 填充本degree的三角 if degree > 0: sierpinski(degree-1, {'left':points['left'], ...
# file openemory/accounts/backends.py # # Copyright 2010 Emory University General Library # # 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/LIC...
import pandas as pd import numpy as np import matplotlib as plt from pandas import DataFrame,Series ''' plot data Series ''' data = Series(np.random.randn(1000),index=np.arange(1000)) data = data.cumsum() ''' DataFrame ''' data = DataFrame(np.random.randn(1000,4),index=np.arange(1000),columns=list(...
import inspect import logging import os import re import subprocess from datetime import timedelta, datetime from typing import List, Optional, Dict, Tuple, Union from pyhttpd.certs import CertificateSpec from pyhttpd.env import HttpdTestEnv, HttpdTestSetup from pyhttpd.result import ExecResult log = logging.getLogg...
# Copyright (c) 2020 Hassan Abouelela # Licensed under the MIT License import asyncio import json import logging import os import aiohttp import discord as discord import math from discord.ext import commands from python import articlesearch logger = logging.getLogger("galnet_discord") logger.setLevel(logging.INF...
# -*- coding: utf-8 -*- """ Created on Tue Feb 12 14:08:16 2019 @author: Manuel Camargo """ import itertools from support_modules import support as sup import os import random import time import pandas as pd import numpy as np # ============================================================================= # Support ...
from bs4 import BeautifulSoup import requests a = 'https://www.cricbuzz.com/live-cricket-scores/20714/eng-vs-ire-only-test-ireland-tour-of-england-only-test-2019' url=requests.get(a) b=url.text c=BeautifulSoup(b,'html.parser') #parse - take html functions for i in c.find_all('div',{'class':"cb-col cb-col-67 cb-scrs-wrp...
from django.shortcuts import render_to_response, render, get_object_or_404 from django.http import HttpResponseRedirect from django.contrib.auth import login,logout,authenticate from django.core.context_processors import csrf from django.contrib.auth.models import User from django.core.urlresolvers import reverse from ...
from pygame import mixer from datetime import datetime from time import time def speak(str): from win32com.client import Dispatch speak = Dispatch("SAPI.SpVoice") speak.Speak(str) if __name__ == '__main__': speak("Welcome to Stay Fit Management ...Please enter your name:") aa = inpu...
from Communication import Message class BaseModule: def power_up(self): print(f'Module {self.get_name()} powering up') def power_down(self): print(f'Module {self.get_name()} powering down') def process(self, message: Message): print(f'Module {self.get_name()} processing message {...
""" Helpers for interacting with DC/OS Docker. """ import subprocess import uuid from ipaddress import IPv4Address from pathlib import Path from shutil import copyfile, copytree, ignore_patterns, rmtree from typing import Any, Dict, Optional, Set import docker import yaml from retry import retry from ._common import...
import pandas as pd import time import matplotlib.pyplot as plt from keras.models import Sequential from keras.layers.core import Dense, Activation, Dropout from keras.optimizers import SGD def prep_data(filename, has_y=True): t0 = time.time() data = pd.read_csv(filename) X = data[["pixel%d" % x for x in ...
import logging from django.urls import reverse_lazy from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required from django.views.generic.base import TemplateView from django.views.generic import CreateView from django.contrib.auth.views import LoginView from . impo...
#plot general class #author: Juan Pablo Duarte, jpduarte@berkeley.edu #BSIM Group, UC Berkeley #import supportfunctions as sf import matplotlib.pyplot as plt from numpy import loadtxt import numpy as np from numpy.matlib import repmat from scipy.misc import factorial from scipy import sparse from scipy.sparse import ...
#Embedded file name: ACEStream\Core\DecentralizedTracking\pymdht\core\logging_conf.pyo import logging import os FORMAT = '%(asctime)s %(levelname)s %(filename)s:%(lineno)s - %(funcName)s()\n%(message)s\n' try: devnullstream = open('/dev/null', 'w') except: from ACEStream.Utilities.NullFile import * devnulls...
# -*- coding: utf-8 -*- ''' @author: kebo @contact: kebo0912@outlook.com @version: 1.0 @file: keras_metric.py @time: 2021/04/21 23:59:34 这一行开始写关于本文件的说明与解释 ''' import tensorflow as tf from cybo.metrics.metric import Metric class KerasMetric(tf.keras.metrics.Metric, Metric): def __init__( self, nam...
from rest_framework import permissions from rest_framework import serializers from rest_framework import viewsets from application.api import router from core.api import UserSerializer from like.models import Like from ugc.api import PostSerializer from ugc.models import Post class ContentObjectRelatedField(serializ...
import re from concurrent import futures from concurrent.futures import ThreadPoolExecutor from typing import List, Optional, Tuple, Iterator, Dict from typing_extensions import Protocol from ._sources.base_classes import FinancialSymbolsSource from ._sources.micex_stocks_source import MicexStocksSource from ._source...
from urllib import urlopen from file_handler import * from parse_html import * from bs4 import BeautifulSoup from directed_graph import Directed_Graph import urlparse class Crawler: base_url='' domain_name='' queue_file='' crawled_file='' queue = [] crawled = [] temp= [] graphq=[] g...
""" Function for calculating the simplest faction from a float. An alternative approach is to use: >>> from fractions import Fraction >>> x = .12345 >>> y = Fraction(x) >>> y.limit_denominator(10) Fraction(1, 8) >>> y.limit_denominator(100) Fraction(10, 81) But usually, we are interested ...
# -*- coding: utf-8 -*- import re some_str = """ 小说(5298252) 外国文学(1937844) 文学(1611318) 随笔(1132086) 中国文学(1049945) 经典(944029) 日本文学(826644) 散文(686198) 村上春树(437578) 诗歌(328662) 童话(292853) 儿童文学(238582) 古典文学(234851) 王小波(223395) 名著(222805) 杂文(216391) 余华(205153) 张爱玲(190301) 当代文学(149029) 钱钟书(105148) 外国名著(95686) 鲁迅(90101) 诗词(811...
# Load modules from inferelator import inferelator_workflow, inferelator_verbose_level, MPControl, CrossValidationManager # Set verbosity level to "Talky" inferelator_verbose_level(1) # Set the location of the input data and the desired location of the output files DATA_DIR = '../data/bsubtilis' OUTPUT_DIR = '~/bsub...
# from os import listdir # from os.path import isfile import os import json class TBlock: def __init__(self, blockHash, parentHash): self.Hash = blockHash self.Parent = parentHash self.Childs = [] def SetParent(self, parent): self.Parent = parent def AddChild(self, childHash): for i in xrange(len(self.C...
#!/usr/bin/python3.4 #-*- coding:utf8 -*- import myConf import logging import os import time import qrcode import qrcode.image.svg from PIL import Image import re import readline import pack8583 from ctypes import * import Security def GetSerial(): initSeq = '1' #从配置文件取出流水号 cfgFile = myConf.GetCombination('app_e...
# Copyright (c) 2017 lululemon athletica Canada inc. # # 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 o...
from weatherapp.core.abstract.command import Command class Configurate(Command): """ Helps to configure weatherapp providers. """ name = 'configurate' def get_parser(self): parser = super().get_parser() parser.add_argument('provider', help='Provider name') return parser ...
#!/usr/bin/env python import sys from datetime import datetime as dt def reducer(): # your code goes here for record in sys.stdin: try: # and here # dt.striptime(date, '%Y/%m/%d') returns a date object except: pass for x in top_n: print x if __n...
import unittest from n_gram import to_n_gram class TestNGram(unittest.TestCase): def test_n_gram_2(self): test_str = '札幌' expected = ['札幌'] actual = to_n_gram(test_str, 2) self.assertEqual(expected, actual) def test_n_gram_14(self): test_str = '北海道札幌市北区あいの里四条' ...
from os import listdir from os.path import isfile, join from itertools import combinations from nltk.corpus.reader import WordListCorpusReader import re from collections import Counter my_tagged_path = 'tagged_emails' test_tagged_path = 'test_tagged' list_of_patterns = ['<speaker>(.*?)</speaker>', '<stime>(....
import matplotlib.pyplot as plt import sys plttimeL = [] pltcwndL = [] with open("cwndL4S", "r") as file: for i in range(0, 40): file.readline() for line in file: plttimeL.append(int(line[3:].split(" ")[0])/250.0) pltcwndL.append(int(line.split(" ")[2])) plttimeC = [] pltcwndC = [] with open("cwndClass...
cena = input ("Podaj cenę") waga = input ("Podaj wagę") należność = float (cena) * float (waga) print ("Cena: " + cena) print ("waga: " + waga) print ("Należność: " + (str(należność))) print ("Należność:", należność))) print (f"Należność: {należność}, wyliczone na podstawie zmiennych: cena={cena}", waga={waga})
import jsl from snactor.registry.schemas import registered_schema @registered_schema('1.0') class DockerInfo(jsl.Document): path = jsl.ArrayField([ jsl.IntField(), jsl.StringField() ]) systemd_state = jsl.ArrayField([ jsl.IntField(), jsl.StringField() ]) info = jsl....
# print() is a function print("Hello World") print(25) # varibles don't have a dolar sign! # when naming we use snake_case, so no uppercase letters nor symbols other than underscore first_name = "John" last_name = "Smith" # we can print varibles or even text or veribles print(first_name) print("Hello", firstname)
''' README: Project Name: Reading Calculator Description: Given the user's reading speed and word count, this calculator will return the amount of minutes it will take to read a book. Language: Python 3.7.9 ''' # Print statement to welcome user to calculator print("Howdy, and welcome to the reading calculator! 🤠...
import os import sys def _get_paths(): # Get the path to jedi. _d = os.path.dirname _jedi_path = _d(_d(_d(_d(_d(__file__))))) _parso_path = sys.argv[1] # The paths are the directory that jedi and parso lie in. return {'jedi': _jedi_path, 'parso': _parso_path} # Remove the first entry, becaus...
#coding:utf-8 import MySQLdb,requests,time,re import sys,datetime reload(sys) sys.setdefaultencoding('utf-8') #把xml中的数据拿下来,根据lastmod判断是否是昨天发布的文章 url_item_list = []#url和/url之间的字符 yesterday_url_list = []#仅昨天发布的文章url列表 today = time.strftime("%Y-%m-%d",time.localtime(time.time())) #today = '2018-02-28' print today for i i...
from dio.share.entity import Entity from dio.delegate.core.option.option_http import OptionHttp from dio.delegate.abstract.aiohttp_delegate import AioHttpDelegate, AioHttpRequest from dio.delegate.core.source.source_base import SourceBase from dio.schemable.schemable_python.compiler import compile_schema class Foo(En...
# 0416 파이썬 # P. 251 #coffe = 0 #def coffee_machine (button) : # print() # if button == 1 : # print ("아메리카노 준비중") # elif button == 2 : # print ("라떼 준비중") # elif button == 3 : # print ("아이스티 준비중") # elif button == 4 : # print ("핫초코 준비중") # else : # print ("1~4 번 중 번...
''' Created on Jul 23, 2018 @author: ftd ''' from pathlib import Path class User_default_file_processor(object): @staticmethod def create_default_file(filename): ''' create the default file @param filename: the default file full path ''' Path(filename).touch() ...
#Python program to count the number of lines in a text file. file = open('text1.txt') c=0 for line in file: c=c+1 print(line) print("Total number of lines: ",c) file.close() #closing the file #program to count the frequency of words in a file file = open('text1.txt') d = dict() for line in file: line = lin...
import numpy as np import six import time import six.moves.cPickle as pickle import pylab input_layer_n = [784] hidden_layers_n = [100, 784] # 重みの値 W = pickle.load(open("W1.dump", "rb")) B = pickle.load(open("B1.dump", "rb")) if __name__ == '__main__': hidden_n = W[0].shape[0] # x = np.zeros((hidden_n, h...
''' Descripttion: version: Author: Jim Huang Date: 2021-02-19 21:32:13 LastEditors: CoderXZ LastEditTime: 2021-05-03 15:17:55 ''' #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: Jim Huang @contact:Jim_Huang@trendmicr.com @version: 1.0.0 @license: Apache Licence @file: 3-15.py @time: 2020/12/9 10:24 排序 ""...
#!/usr/bin/env python3 import random import sys # Set up some global variables. TODO: Add ability to play multiple games and move this into the Main function with open('hangmanwords.txt', mode='rt', encoding='utf-8') as w: word_list = [line.strip() for line in w] play_word = word_list[random.randint(0, len(word_...
1. Evaluate |DecimalEscape| to obtain an EscapeValue _E_. 1. If _E_ is a character, then 1. Let _ch_ be _E_'s character. 1. Let _A_ be a one-element CharSet containing the character _ch_. 1. Call CharacterSetMatcher(_A_, *false*) and return its Matcher result. ...
# only hold the first click per user per company per day import datetime start_date = datetime.date(2016,9,1) end_date = datetime.date(2016,9,30) source_path = '/Users/Miao/Documents/code/sec/fundamental/' dest_path = '/Users/Miao/Documents/code/sec/final/' def file_name_generate(start, end): days = [start + date...
# Encoding and decoding methods. CHARTIME = 0.2 min_freq = 100 step = 50 def char_to_ind(char): if 97 <= ord(char) <= 122: return ord(char) - 97 elif char == ' ': return 26 else: return 27 def ind_to_char(ind): if 0 <= ind < 26: return chr(ind + 97) elif ind == 27:...
# # code to parse the pla status page for the flow # # # Distributed under MIT License # # Copyright (c) 2020 Greg Brougham # # 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 restric...
import shutil import subprocess import traceback import qimage2ndarray as qimage2ndarray from PyQt5 import uic, QtCore, Qt, QtGui from PyQt5.QtWidgets import * from PyQt5.QtCore import * import sys import zmq import os import lyosha.first_task as graphics from datetime import datetime import time def resource_path(r...
import pablo as arm import UARTModule as uart import time def command2(): uart.initUART() while True: c = int(input("Enter Command")) uart.writeCommand(c) def createCommand( angle ,servoI): if angle < 0: return (int(angle)*100) -servoI else: return (int(angle)*100) +servoI def loopCommand(): uart.in...
# -*- coding:utf-8 -*- import heapq as p import random class MyHeap(object): def __init__(self, array): self.n = len(array) self.list = array def build_heap(self): n_hat = self.n for i in range(n_hat // 2 - 1, -1, -1): # 遍历所有的非叶子节点进行heapify self.h...
# coding: utf-8 # In[1]: import pandas as pd from pandas import DataFrame, Series import numpy as np import random from keras.models import load_model, Sequential, Model from keras.layers import Cropping2D import cv2 import os import socket import scipy from sklearn import preprocessing import shutil import skimage....
import pymysql # Connection connection = pymysql.connect(host='rds.chzi0a331csg.ap-south-1.rds.amazonaws.com', user='admin', password='rootroot', database='rds_sql') def handler(): cursor = connection.cursor() c...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'my_subjects.ui' # # Created by: PyQt5 UI code generator 5.15.2 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, ...
import pandas as pd import numpy as np from functools import partial from janitor import clean_names #Download Data # ------------------------------------------------------------ # Adelie penguin data from: https://doi.org/10.6073/pasta/abc50eed9138b75f54eaada0841b9b86 uri_adelie = "https://portal.edirepository.org/n...
# Generated by Django 2.2.4 on 2019-08-22 09:32 import django.db.models.deletion import wagtail.blocks import wagtail.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("images", "0002_customimage_file_hash"), ("programmes", "0007_add_fees_se...
import pandas as pd data = pd.read_csv("Twitter_SearchAPI_cleaned.csv") polarity = [] pwordsfreq = {} nwordsfreq = {} match = [] for x in data['Tweet']: matchwords = "" polar = 0 x = str(x).lower() words = x.split() bagofwords = {} for word in words: ...
from django.db import models class UsdRate(models.Model): btc_price = models.FloatField() eth_price = models.FloatField() usdc_price = models.FloatField(default=1) usd_price = models.FloatField(default=1) eur_price = models.FloatField() gbp_price = models.FloatField() chf_price = models.Fl...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class Hospital(models.Model): HospitalId = models.AutoField(primary_key=True) Name = models.CharField(max_length=250) UserName = models.CharField(max_length=250) Password = models.CharField(ma...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. from auth_log.models import User class Tags(models.Model): """分类表""" type=models.CharField(max_length=20) # 标签内容 addtime=models.IntegerField(default=0) # 添加时间 status = models.Inte...
# -*- coding: utf-8 -*- # Author :Yang Ming # Create at :2021/6/8 # tool :PyCharm from lxml import etree from loguru import logger from schema.crawler_abc import * class Crawler(CrawlerABC): def html_parser(self, html): ehtml = etree.HTML(html) rooms = ehtml.xpath('//li[@class="mortar-wra...
# Faça um Programa que peça os 3 lados de um triângulo. # O programa deve informar se os valores podem ser um triângulo. # Indique, caso os lados formem um triângulo, se o mesmo é: equilátero, isósceles ou escaleno. l1 = float(input('Informe o primeiro lado do triangulo: ')) l2 = float(input('Informe o segundo la...
from linked_list import LinkedList from stack import Stack from queue import Queue def linked_list_example(): print('------------------->> Linked List Example <<-------------------') llist = LinkedList() llist.append(0) llist.append(1) llist.append(2) llist.append(3) llist.prepend(-1) ...
#_*_coding:utf-8_*_ import unittest import shutil from testScenario import testScenarioCase from testInterface import testActivity,testCharge,\ testCoupon,testCredit,testDeal,testGrade,testManage,testProduct,\ testSearch,testTag,testUser import os,time,json from globalVar import gl from library import HTMLTESTR...
import sys from itertools import chain from itertools import product input_string = sys.argv[1] input_tuple = tuple(map(int, input_string.split("-"))) def rule_1(number): return any(map(lambda x: x[0] == x[1], [(i, j) for i, j in zip(number[:-1], number[1:])])) def rule_2(number): previous_digit = numbe...
n=int(input("enter a number")) r=0 while n>0: rem=int(n%10) r=(r*10)+rem n=int(n/10) print (r)
import graphene from account.mutations import AuthMutation from product.queries import ProductQuery from product.mutiaion import ProductMutations from graphql_auth.schema import UserQuery, MeQuery class Query(UserQuery, MeQuery, ProductQuery, graphene.ObjectType): pass class Mutation(ProductMutations, AuthMuta...
from selenium.webdriver.common.by import By from pages.page import BasePage class LoginPage(BasePage): url = BasePage.baseurl email_address_textbox = (By.XPATH, '//INPUT[@placeholder="Email address"]') email_right_arrow = (By.XPATH, "//DIV[@class='next-step ready']") password_textbox = (By.XPATH, '//...
#! /usr/bin/python ''' Text Justification Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when neces...
#定义错误状态码和相应Message USER_ALREADY_EXISTS = 20001 # 用户已经存在 PARAMETERS_INVALID = 20002 #参数不合法 PARAMETERS_NOTENOUGH = 20003#指定不能省略的参数不够 REQUEST_METHOD_ERROR = 20004#请求方法错误 INTER_NOT_IMPLEMENT_ERROR = 20005#=未实现 INTER_MACHINE_ERROR = 20006#内部错误 NOT_FOUND_ERROR =20404#未找到 #message和自定义状态码的映射字典 J_MSG = {USER_ALREADY_EXIST...
#!/usr/bin/env python ############################################################################ # # endTrimmer.py # 2015 James Stapleton # # Trims a specified number of nucleotides from each end of each # synthetic long read in a list, prints a new file # ################################################...
# Generated by Django 3.1.2 on 2020-10-19 16:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('auctions', '0039_auto_20201019_1833'), ] operations = [ migrations.AlterField( model_name='auction', name='available...
import sys sys.path.append("./") import setting import xmlrpclib import SimpleXMLRPCServer import socket import select import time import random class Sensor: ''' Represents any senors''' def __init__(self,name,serveradd,localadd): '''initialize a sensor, create a client to connect to server''' ...
import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import os import scipy from scipy import signal matplotlib.use("pgf") plt.rcParams.update({ "pgf.texsystem": "pdflatex", "font.family": "serif", "font.size": 6, "legend.fontsize": 5, "text.usetex": True, "p...
from google_trans_new import google_translator import streamlit as st translator = google_translator() st.title("Language Translator") text = st.text_input("Enter a text") translate = translator.translate(text,lang_tgt='fr') st.write(translate)
# Generated by Django 2.0 on 2018-08-15 12:04 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('Attitude', '0001_initial'), ] operations = [ migrations.RenameField( model_name='attitudecount', old_name='attitude_applause_n...
import datetime from flask_peewee.auth import BaseUser from peewee import * from app import db class User(db.Model, BaseUser): username = CharField() password = CharField() email = CharField() join_date = DateTimeField(default=datetime.datetime.now) active = BooleanField(default=True) admin = ...
#!/usr/bin/python #_*_coding:utf-8_*_ from __future__ import absolute_import from django.shortcuts import render,HttpResponseRedirect,render_to_response,HttpResponse from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse from django.shortcuts import render_to_response,Re...
#!/usr/bin/python """ Parse and relay a notification """ import sys import re import os def message(title, message, urgency='NORMAL'): os.system('notify-send "{}" "{}" --urgency={}'.format(title, message, urgency)) summary_replace = {' (Magazino)': '', 'Direct Message': ' '} body_replace = {'ma...
#-*-coding:utf-8-*- ''' 对角线遍历 https://blog.csdn.net/zzz_cming/article/details/81035354 https://leetcode-cn.com/explore/learn/card/array-and-string/199/introduction-to-2d-array/774/ ''' if __name__ == '__main__': A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] n = len(A) for i in range(n + n ...
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*- from moviepy.editor import VideoFileClip # UKULELE CLIP, OBTAINED BY CUTTING AND CROPPING # RAW FOOTAGE #class VideoManagerClass(): # listTitleAndFullVideo = [] # def __init__(self, ): # print("VideoManager Created") # return None # def test(): ...
# logging.py # implements Server Logger class import os from datetime import datetime class Logger: def __init__(self, caller): self.caller = caller.replace(".", "_").replace(":", "__") self.cache = [] self.maxCacheSize = 100 self.defaultFolder = ".log_entry" if not os.path....
people_am = int(input('Количество человек: ')) rhyme_num = int(input('Какое число в считалке? ')) print('Значит выбывает каждый', rhyme_num, 'человек.') guys_list = list(range(1, people_am + 1)) person_left = 0 while len(guys_list) > 1: print('\nТекущий круг людей:', guys_list) if person_left > len(guys_list) ...
#!/usr/bin/python3 from pathlib import Path import shelve def coordconv(x,y): y=ysize-y return(x,y) def line(x1,y1,x2,y2): x1,y1=coordconv(x1,y1) x2,y2=coordconv(x2,y2) dfile.write(f'<line x1="{x1}" y1="{y1}" x2="{x2}" y2="{y2}" stroke="black"/>\n') def circle(x,y,r): x,y=coordconv(x,y) df...
print("Calculator(simple)") x = int(input("Enter first number")) y = int(input("Enter second number")) operator = input("please enter: Add, Subtract, divide or multiply") if operator == "add": total = x + y print ("x + y =", total) if operator == "subtract": total = x - y prin...
from ..common import WQXException from .MeasureCompact import MeasureCompact from .SimpleContent import ( DetectionQuantitationLimitCommentText, DetectionQuantitationLimitTypeName ) from yattag import Doc class DetectionQuantitationLimit: """Information that describes one of a variety of detection or quantitatio...
#!/usr/bin/env python3 from glob import glob import PyPDF2, os import argparse import sys def add_file(pdf_file): print "Adding %s..." %(pdf_file) pdfFileObj = open(pdf_file, 'rb') pdfReader = PyPDF2.PdfFileReader(pdfFileObj) for pageNum in range(0, pdfReader.numPages): pageObj = pdfReader.getPage(pageNum...
''' # 1. problem.txt 파일을 생성 후, 다음과 같은 내용을 작성 0 1 2 3 # 2. problem.txt의 파일 내용을 다음과 같이 변경 3 2 1 0 # 3. reverse.txt의 파일 내용에 problem.txt의 파일 내용을 반대로 넣기 ''' ''' # 1 with open( 'problem.txt', 'w' ) as f: for i in range (0,4): f.write (str(3-i) + '\n' ) ''' ''' #2 textContents = [] with open( 'problem.txt', 'r'...
#!/usr/bin/env python #!-*- coding:utf-8 -*- import jieba import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras import Input,Model from tensorflow.keras import preprocessing from tensorflow.keras.layers import Layer from tensorflow.keras import initializers, reg...
# ----------------------------------------------------------------------------- # Copyright (C) 2019-2020 The python-ndn authors # # This file is part of python-ndn. # # 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 ...
from django.db import models from django.utils import timezone # Create your models here. class User(models.Model): username = models.CharField('username',unique=True, max_length=64) email = models.EmailField('email',unique=True) password = models.CharField('password', max_length=16, help_text="密码长度为8到16位字...
import unittest from src.compound_interest import CompoundInterest class CompoundInterestTest(unittest.TestCase): # Tests def test_100_10_20(self): compound_interest = CompoundInterest(100, 10, 20) self.assertEqual(732.81, compound_interest.compound_interest_calc()) # Should return 732.81...
# Drop every N'th element from a list def drop(l, n): return [e for i, e in enumerate(l) if (i+1) % n != 0]