text
stringlengths
8
6.05M
from _typeshed import Incomplete from collections.abc import Generator class ISMAGS: graph: Incomplete subgraph: Incomplete node_equality: Incomplete edge_equality: Incomplete def __init__( self, graph, subgraph, node_match: Incomplete | None = None, edge_mat...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ############################################################################# # # # Scripts de configuracion para Server tomar los datos de las # # peticiones enviadas desde la p...
import scraperwiki import lxml.html import datetime """Scrapes Yahoo Finance Stock Page and builds data set for daily \ stock information. Modify HTML as needed for different stock pages.""" #Website definition html = scraperwiki.scrape("http://finance.yahoo.com/q?s=NYX") root = lxml.html.fromstring(html) def sto...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # tadretangulo.py import tadreta import tadponto def criarVtx(xsupE, ysupE, xinfD, yinfD): alt = yinfD - ysupE larg = xinfD - xsupE return [[xsupE, ysupE],[xinfD, yinfD]] # def criarDim(xsupE, ysupE, larg, alt): return [[xsupE, ysupE],[xsupE + larg,ysupE + alt]] #...
''' # will be randomly generated and spoken ''' import time import random as r t = 0 rNumber = r.randint(10000, 99999) while t < 1000000: t = t + 1 rWait = r.randint(0, 60) print('Number is', rNumber) time.sleep(rWait)
import cv2 import numpy as np from matplotlib import pyplot as plt##optional from imglib import *#optional from motion import *#optional # comment here def detectCellVal(img_gray,grid_map): for i in range(0,2): # print i imgname='digits/'+str(i)+'.jpg' template = cv2.imread(imgname) temp_gray = cv2.cvtColo...
from sisyphus import * import gzip from recipe.lib.corpus import Corpus class BlissExtractRawText(Job): """ Extract the Text from a Bliss corpus into a raw gziptext file """ def __init__(self, corpus, segments=None, segment_key_only=True): self.corpus_path = corpus self.out = self.output_path("text.g...
import sunspec2.mb as mb import pytest def test_create_unimpl_value(): with pytest.raises(ValueError): mb.create_unimpl_value(None) with pytest.raises(ValueError): mb.create_unimpl_value('string') assert mb.create_unimpl_value('string', len=8) == b'\x00\x00\x00\x00\x00\x00\x00\x00' a...
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2013-2015 Marcos Organizador de Negocios SRL http://marcos.do # Write by Eneldo Serrata (eneldo@marcos.do) # # This program is free software: you can redistribute it and/or modify # it un...
#%% [markdown] # # Recommender systems #%% [markdown] # ***Описание задачи*** # # Небольшой интернет-магазин попросил вас добавить ранжирование товаров в блок "Смотрели ранее" - в нём теперь надо показывать не последние просмотренные пользователем товары, а те товары из просмотренных, которые он наиболее вероятно купи...
import random def throw_die(): # random.randrange(a, b) geeft een getal tussen a (inclusief) en b (exclusief) return random.randrange(1, 7) def probability_of_sum_higher_than(dice_count, minimum_sum, samples): raise NotYetImplemented()
from sqlalchemy.dialects.mysql import json import json from app import app import requests from flask_babel import _ def translate(text, source_language, dest_language): if not (not ('MS_TRANSLATOR_KEY' not in app.config) and app.config['MS_TRANSLATOR_KEY']): return _('Error: the translation service is no...
""" Fixes duplicates on the DLLs files """ import argparse import pandas as pd def fixer_func(dlls): """ Removes duplicated dll entries and sorts dlls """ if type(dlls) is str: return ';'.join(sorted(set(dlls.split(';')))) return dlls def dll_fixer(input_csv, output_csv): """...
# Generated by Django 3.0.3 on 2020-10-02 13:30 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Diabetes', fields=[ ('id', models.AutoField...
#!/usr/bin/python """ Output lines selected randomly from a file Copyright 2005, 2007 Paul Eggert. Copyright 2010 Darrell Benjamin Carbajal. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either v...
import logging import requests class DoubanAPI: logger = logging.getLogger(__name__) @classmethod def get_user_info(cls, uid): """获得用户基本信息""" url = "https://api.douban.com/v2/user/{}".format(uid) r = requests.get(url, timeout=10) return r.json() @classmethod def ...
import csv from flask import Flask, render_template app = Flask(__name__) @app.route("/") def hello(): with open('/var/lib/misc/dnsmasq.leases', 'rb') as leasesFile: leasesReader = csv.reader(leasesFile, delimiter=' ') return render_template('default.html', leases=leasesReader) if __name__ == "__main__":...
from socket import * from os import listdir from os.path import isfile, join onlyfiles = [f for f in listdir('./files') if isfile(join('./files', f))] serverAddress = ("127.0.0.1",12000) # a tuple containing the IP Address of the Server and Socket ID (Port) serverSocket = socket(AF_INET,SOCK_DGRAM) # Datagram because...
'''• 2! = 2.1 = 2 • 3! = 3.2.1 = 3.2! = 3.2 = 6 • 4! = 4.3.2.1 = 4.3! = 4.3.2! = 4.3.2 = 24 • 5! = 5.4.3.2.1 = 5.4! = 5.4.3! = 5.4.6 = 20.6 = 120 • 6! = 6.5.4.3.2.1 = 6.5! = 6.120 = 720 • 7! = 7.6.5.4.3.2.1 = 7.6! = 7.720 = 5040 ''' def factorialz(number): if number == 0: return 1 return number * fac...
#!/usr/bin/python """ The main script of gess, the generator for synthetic streams of financial transactions. @author: Michael Hausenblas, http://mhausenblas.info/#i @since: 2013-11-07 @status: init """ import logging import os from fintrans import FinTransSource DEBUG = False CONFIG_FILE = 'gess.conf' if DE...
# -*- coding: utf-8 -*- # # This file is part of Python-ASN1. Python-ASN1 is free software that is # made available under the MIT license. Consult the file "LICENSE" that # is distributed together with this file for the exact licensing terms. # # Python-ASN1 is copyright (c) 2007-2016 by the Python-ASN1 authors. See th...
import os import sys import read_tree sys.path.insert(0, 'tools/trees') """ This function assumes that both input trees have the exact same rooted topology, and only differ by their branch lengths and internal node labels. It loads tree_to_relabel_path, changes its internal node labels to match the ones fr...
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:hua from flask import Flask from Machine_Learning.KNN import KNN_blue from Machine_Learning.test import test_blue app = Flask(__name__) # 将蓝图注册到app app.register_blueprint(KNN_blue, url_prefix='/KNNS') app.register_blueprint(test_blue, url_prefix='/test') if __nam...
from statistics import mean, pstdev amount = 10 loss = 2 profit = 8 class Bollinger: def __init__(self, name, fx): self.name = name self.fx = fx self.arr5 = fx.get_candles(instrument=self.name, period='m1', number=20) self.arr15 = fx.get_candles(instrument=self.name, period='m5', ...
import warnings import numpy as np import matplotlib.pyplot as plt import pandas as pd from time import time from sklearn.model_selection import train_test_split from sklearn.metrics import precision_score, recall_score, accuracy_score from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay import tenso...
# -*- coding: utf-8 -*- from sefaria.model import * from sefaria.tracker import add import urllib import urllib2 from urllib2 import URLError, HTTPError import json def post_index(index): url = 'http://www.sefaria.org/api/index/' + index["title"].replace(" ", "_") indexJSON = json.dumps(index) print indexJSON v...
import boto3 def create_instance(instance_name, avail_zone, image_name, os_name, bundle): """ A function to create a lightsail instance """ conn = boto3.client('lightsail', region_name='ap-south-1') # get blueprint ids to verify the image number response = conn.get_blueprints()['blueprints'] ...
#!/usr/bin/env python import sys, re from unidecode import unidecode import bibtexparser from bibtexparser.bwriter import BibTexWriter import http.client as httplib import urllib # Search for the DOI given a title; e.g. "computation in Noisy Radio Networks" # Credit to user13348, slight modifications # http://tex.sta...
import logging import os import sqlalchemy as sa from sqlalchemy.orm import scoped_session, sessionmaker from settings import * from models import Base, ChatMessage logger = logging.getLogger('chat_message_parser') def create_mysql_pool(): mysql_host = MYSQL_HOST mysql_port = MYSQL_PORT mysql_db = MY...
from django.conf.urls import url, include from rest_framework import routers from . import views, api_views, serializers router = routers.DefaultRouter() router.register(r'users', api_views.UserViewSet) router.register(r'groups', api_views.GroupViewSet) router.register(r'category', serializers.CategoryViewSet) router...
#!/usr/bin/python """ check_updates - A tool for checking whether a local repository is in-sync with a remote repository. The script assumes the classic NVR format for the remote repository and NVrR format for local. NVrR format is where the upstream release is tagged on to the end of the version. This allows a local ...
# Copyright 2020 Pulser Development Team # # 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 unittest from katas.beta.super_duper_easy import problem class ProblemTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(problem('hello'), 'Error') def test_equals_2(self): self.assertEqual(problem(1), 56)
def calculateState(inputConnections, recurrenceConnection): """ Performs state calculation given a list of|inputConnections| and an optional |recurrenceConnection|, which can be provided as None. """ # Calculate sum of products for input connections state = sum(connection.calculate() for co...
class OrderedLinkedList(object): class _Node(object): def __init__(self, data, next=None): self.data = data self.next = next def __init__(self, lst=[]): self.head = OrderedLinkedList._Node(0) def add(self, value): def _add(node, value): # recursi...
# a simple script used for webscrapping chosen funds data from a website for a # specific day and save/append it to a json file # script can be set up in windows scheduler to run everyday automatically from bs4 import BeautifulSoup import requests import pandas as pd import json # website for scrapping url = "https...
import numpy as np import tensorflow.keras as keras import pickle class DataGenerator(keras.utils.Sequence): def __init__(self, file_list, y_list,shape = (53, 63, 52, 53), batch_size = 32): self.file_list = file_list self.y_list = y_list self.batch_size = batch_size self.dim = shape...
import asciinema import sys from setuptools import setup if sys.version_info[0] < 3: sys.exit('Python < 3 is unsupported.') url_template = 'https://github.com/asciinema/asciinema/archive/v%s.tar.gz' requirements = [] setup( name='asciinema', version=asciinema.__version__, packages=['asciinema', 'asci...
import getpass import json import requests import shutil import subprocess import sys import os def checkFlaky(slugs, pnumber): projects = [] idx = 0 for project in slugs: gitlink = 'https://github.com/' + project + '.git' # print("gitlink", gitlink) p = project.split(...
/Users/daniel/anaconda/lib/python3.6/_bootlocale.py
import re import json import pandas as pd import matplotlib.pyplot as plt tweets_data_path = 'twittermi.txt' tweets_data = [] tweets_file = open(tweets_data_path, 'r') for line in tweets_file: try: tweet = json.loads(line) tweets_data.append(tweet) except: continue pri...
import json i = 0 with open('mood.json') as data: data = json.load(data) email = data['embassies'][i]['email'] print(email)
# Given two arrays arr1 and arr2, the elements of arr2 are distinct, # and all elements in arr2 are also in arr1. # # Sort the elements of arr1 such that the relative ordering of items # in arr1 are the same as in arr2. Elements that don't appear in arr2 # should be placed at the end of arr1 in ascendin...
s = '0' i = int(s) print(10 / i) # 利用python -m pdb .py 文件 # 然后按n进行单步调试
# In this program we define a class and its attributes. # will call the class in file import_test.py class importTest: def test (self, name): self.name = name return self.name
n, t = map(int, input().split()) sequence = input() for i in range(t): sequence = sequence.replace('BG', 'GB') print(sequence)
from django.db import models # Create your models here. #번호,제목,작성자,등록일,조회수,글,첨부파일 class Notice(models.Model): #num=models.IntegerField() #번호 model.id로 대체 가능 title=models.CharField(max_length=100) #제목 writer=models.CharField(max_length=25) #작성자 pub_date=models.DateField(auto_now=True) #등록일 hit=...
from flask import g, session class Auth(object): """ This is just a simple app extension to handle basic authentication as used by this specific application. """ def __init__(self, app=None): self.app = app if self.app is not None: self.init_app(app) def init_app(...
n = int(input()) for i in range(n): li = sorted(map(int, input().split())) if(pow(li[0], 2) + pow (li[1], 2) == pow(li[2], 2)): print('YES') else: print('NO')
#RDC algorithym simulation import numpy as np from scipy import signal from fxpmath import Fxp import matplotlib.pyplot as plt from functools import reduce RAW = Fxp(None,dtype='S1.15') DATA = Fxp(None,dtype='S1.15') ANGLE = Fxp(None,dtype='S4.20') PANGLE = Fxp(None,dtype='S1.23',overflow='wrap') CONST = Fxp(None,dty...
from MulLayer import * orange = 1000 orange_num = 3 tax = 1.5 mul_orange_layer = MulLayer() mul_tax_layer = MulLayer() # forward orange_price = mul_orange_layer.forward(orange, orange_num) price = mul_tax_layer.forward(orange_price, tax) # backward dprice = 1 dorange_price, dtax = mul_tax_layer.backward(dprice) do...
import numpy as np import argparse import imutils import pickle import cv2 import os ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to input image") ap.add_argument("-d", "--detector", required=True, help="path to OpenCV's deep learning face detector") ap.add_argument("-m...
from . import home_user from flask import render_template, request, redirect, session, flash, jsonify, url_for, current_app from .forms import UserBaseForm, ModifyPassowrd, UserImg from app.utils.response_code import RET from app.utils.qiniu.image_storage import storage from app import constants # /user # user的默认界面 @...
# -*- coding: utf-8 -*- """ Created on Mon Jan 19 22:17:08 2015 @author: lenovo """ """ if 问题足够简单: 直接解决问题 返回解 else: 将问题分解为与原问题同构的一个或多个更小的问题 逐个解决这些更小的问题 将结果组合为,获得最终的解 返回解 """ ##循环的方式# #def p(n): # x=1 # i=1 # while i <= n: # x=x*i # i=i+1 # return x # ##递归的方式# ##掐头去尾留中...
import json a = input() dict_json = json.loads(a) dict_result = {} def add_parents(key_glob, key, d): d_copy = d.copy() for child in d_copy[key]: d[key_glob].add(child) add_parents(key_glob, child, d) for obj in dict_json: for parent in obj["parents"]: if not dict_result.get(par...
import time def countdown(func): def some_time(): for i in range(1, 4): time.sleep(1) print(i) func() return some_time() @countdown def what_time_is_it_now(): print(time.strftime('%H:%M'))
""" Description of program """ import numpy as np from astropy.table import Table as table from astropy.io import fits import matplotlib.pyplot as plt # ============================================================================== # Define variables # ==================================================================...
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2017-01-09 15:14 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("elections", "0015_rename_mayor_type")] operations = [ migrations.AlterField( ...
l = ['hello', 'world', 'my', 'name', 'is', 'Anna'] for x in l: for new in x: if new.endswith('o'): print x l = ['hello', 'world', 'my', 'name', 'is', 'Anna'] char = 'o' for find in l: for new in find: if new == char: print find
import numpy import pytest from helpers import * from tigger.elementwise import Elementwise import tigger.cluda.dtypes as dtypes def test_errors(ctx): argnames = (('output',), ('input',), ('param',)) elw = Elementwise(ctx).set_argnames(*argnames) code = dict(kernel=""" ${input.ctype} a1 = ${inp...
import tornado.web from tornado.web import RequestHandler from tornado.httpclient import AsyncHTTPClient import json import time class StaticFileHandler(tornado.web.StaticFileHandler): def __init__(self, *args, **kwargs): super(StaticFileHandler, self).__init__(*args, **kwargs) self.xsrf...
from __future__ import print_function ,division import os import torch from skimage import io,transform import numpy as np import matplotlib.pyplot as plt from torch.utils.data import Dataset,DataLoader from torchvision import transforms,utils import warnings import cv2 import random warnings.filterwarnings("ignore")...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render, redirect from .models import Username from django.contrib import messages def index(request): return render(request, 'user_validation/index.html') def create(request): if len(Username.objects.filter(username=r...
from selenium import webdriver from lxml import etree import os import time import random COMMENT_FILE_PATH = '02_jd_commentsBySelenium.txt' # 有头模式 #driver = webdriver.Firefox() #无头模式 options = webdriver.FirefoxOptions() options.add_argument('-headless') driver = webdriver.Firefox(options=options) driver.get("htt...
from django.conf.urls import url, include from django.urls import path, re_path from django.contrib.auth import views as auth_views from django.contrib.auth import forms as auth_forms from django.contrib.auth.views import PasswordResetCompleteView from django.contrib.auth.views import PasswordResetConfirmView from dja...
#!/usr/bin/env python import time, unittest, os, sys from selenium import webdriver from utils.function.setup import * from main.activity.desktop_v3.activity_wishlist import * class TestWishlist(unittest.TestCase): dict = { "site" : "beta", "loop" : 1, "domain_shop" : "alvin", "until_page" : 500, "shop_k...
#!/usr/bin/env python """A tiny tool used to test the `convert` plugin. It copies a file and appends a specified text tag. """ import sys import locale # From `beets.util`. def arg_encoding(): try: return locale.getdefaultlocale()[1] or 'utf-8' except ValueError: return 'utf-8' def convert...
# -*- coding: utf-8 -*- """ Created on Sat Feb 15 17:11:46 2020 @author: MERT """ from sklearn.datasets import load_files import os import nltk import pandas as pd import xlrd import re from nltk.corpus import stopwords import sklearn import pickle konumum = os.getcwd() print("konumun :",konumum) # Openning the ...
# Напишите reducer, который реализует симметричную разность множеств A и B (т.е. оставляет только те элементы, которые есть только в одном из множеств). # На вход в reducer приходят пары key / value, где key - элемент множества, value - маркер множества (A или B) # Sample Input: # 1 A # 2 A # 2 B # 3 B # Sam...
# -*- coding: utf-8 -*- from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class ChloroformAppConfig(AppConfig): name = 'chloroform' verbose_name = _('Chloroform Contact form builder') def ready(self): import chloroform.checks # noqa
#!/usr/bin/env python # # Copyright (c) 2019 Opticks Team. All Rights Reserved. # # This file is part of Opticks # (see https://bitbucket.org/simoncblyth/opticks). # # 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...
import cv2 import numpy as np from faceplusplus_api import faceplusplus_api from PIL import Image, ImageDraw import math def load_api_data(filepath): data = faceplusplus_api(filepath) left_eye = [data['faces'][0]['landmark']['left_eye_center']['x'], data['faces'][0]['landmark']['left_eye_cente...
# -*- coding: utf-8 -*- """ Created on Wed Dec 9 10:23:54 2020 @author: Alex """ import numpy as np import matplotlib.pyplot as plt #To validate the newton 2D method, hardcode an example function def f(u): return -np.exp(-u[0]**3/3 + u[0] -u[1]**2) #Hardcode the analytic partial derivatives so that the grad ve...
from . import article, admin article.populate() admin.populate()
#Python program to get the least common multiple (LCM) of two positive integers: a=int(input("Enter first number: ")) b=int(input("Enter second number: ")) for m in range(1,a*b+1): if m%a == 0 and m%b == 0: print("LCM between two no. is: ",m) break
import json from Edition import Edition from Card import Card from lib import clean_unicode ###Need to change flat cards into an edition on its own. That way I can call find card give an edition and if i dont specify it then it uses the default flattening. this might be better. class Magic(object): #This is a Clas...
#!/usr/bin/env python3 # import emoji # print(emoji.emojize('Ola :thumbs_up:')) # import flask # # app = flask.Flask(__name__) # # dados = { # 'acesso':'OK' # } # Configurando rotas # @app.route('/') # def index(): # return flask.jsonify(dados) # configurando tipos de requisicao # @app.route("/api?<any('id'...
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2016-07-29 17:08 from __future__ import unicode_literals from django.db import migrations, models import posts.models class Migration(migrations.Migration): dependencies = [ ('posts', '0005_auto_20160728_2010'), ] operations = [ mig...
# libraries import numpy as np import matplotlib.pyplot as plt # set width of bar barWidth = 0.17 # set height of bar bars1 = [7, 18, 19, 4, 35, 4, 11, 7] bars2 = [0, 11, 21, 5, 13, 0, 2, 6,] bars3 = [1, 7, 11, 1, 7, 2, 3, 5] bars4 = [3, 5, 6, 2, 12, 2, 7, 5] # Set position of bar on X axis r1 = np.arange(len(b...
# # Copyright (C) 2020-2030 Thorium Corp FP <help@thoriumcorp.website> # from odoo import models, fields class ThoriumcorpSpecialty(models.Model): _name = 'thoriumcorp.specialty' _description = 'Medical Specialty' _sql_constraints = [ ('code_uniq', 'UNIQUE(code)', 'Code must be unique!'), ...
import numpy as np import pandas as pd import keycode FALLBACK_WEIGHT = 0.25 # weight of fallback observations M_MIN_FREQUENCY = 3 # min frequency per sample for feature fallback OUTLIER_DISTANCE = 2 # outliers outside +/- std devs OUTLIER_ITERATIONS = 2 # no. iterations to do recursive outlier removal def tran...
import support_functions import vm_functions import unittest version_good = "6.1.26r145957" vm_good = "ws2019" vm_bad = "bad" snapshot_good = "live" snapshot_bad = "bad" file_good = "./firefox.exe" file_bad = "./bad.exe" file_dst = "C:\\windows\\temp\\file.exe" user_good = "Administrator" pass_good = "12345678" user_b...
from PIL import Image # change as per need TEST_IMAGE_LOCATION = "test.jpg" TRAINING_FILE_LOCATION = "training_sheet.txt" OUTPUT_IMAGE_NAME = "output_image.png" OUTPUT_IMAGE=[] MY_HASH_LIST = {} im=Image.open(TEST_IMAGE_LOCATION, "r") # read image from image location pix_val=list(im.getdata()) ...
# %load q03_linear_regression/build.py from greyatomlib.linear_regression.q01_load_data.build import load_data from greyatomlib.linear_regression.q02_data_splitter.build import data_splitter from sklearn.linear_model import LinearRegression dataframe = load_data('data/house_prices_multivariate.csv') X, y = data_splitt...
from django.db import models from django.utils import timezone class Customer(models.Model): customer_id = models.PositiveIntegerField() customer_username = models.CharField(max_length=20) customer_first = models.CharField(max_length=100) customer_last = models.CharField(max_length=100) customer_em...
def main(): monthly_sales = get_sales() advanced_pay = get_advanced_pay() commission_rate = get_commission_rate(monthly_sales) monthly_pay = (monthly_sales * commission_rate) - advanced_pay if monthly_pay < 0: imbursement = abs(monthly_pay) print("You must reimburse ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/11/18 下午5:48 # @Author : zs # @Site : # @File : add_hw.py # @Software: PyCharm import xml.etree.ElementTree as ET import os def rewrite_xml(cwd, newcwd): for path, d, filelist in os.walk(cwd): for xmlname in filelist: if xmlname.ends...
from sqlite3 import Connection from uuid import uuid4 class ChatTokenRepository: def __init__(self, con: Connection): self._con = con def create(self, name: str, chat_id: int, telegram_user_id: int): token = uuid4().hex with self._con as con: con.cursor().execute('INS...
from collections import OrderedDict from lxml import etree _extensions = {} class GBIFDarwinCoreMapping(object): def __init__(self, extension_paths, reset=False): """Class used to represent the mapping from Darwin Core terms to a GBIF compatible list of Darwin Core Archive extensions and ...
#!/usr/bin/env python # IDENT nluetzge-time.py # LANGUAGE Python # AUTHOR N. Luetzgendorf # PURPOSE # # VERSION # 1.0 24.09.2018 NL Creation import datetime # Making a change here print("# Date : {:s}".format((datetime.datetime.now()).isoformat()))
# 弹夹类 class BulletBox(object): def __init__(self, count): self.__bulletCount = count def setBulletCount(self, count): self.__bulletCount = count def getBulletCount(self): return self.__bulletCount
algo = input('Digite algo: ') print('O tipo dele é {}. Ele é Alfa Númerico? {}. Ele é Númerico? {}. Ele é alfabetico? {}.'.format(type(algo), algo.isalnum(), algo.isnumeric(), algo.isalpha()))
def solution(n, m, section): answer = 0 point = 0 for i in section: if i > point: point = i + m - 1 answer += 1 return answer
# 直接秒杀 class Solution: def fullBloomFlowers(self, flowers: List[List[int]], persons: List[int]) -> List[int]: n = len(flowers) pre, post = [], [] res = [] for s, e in flowers: pre.append(s) post.append(e) pre.sort() post.sort() for t i...
#!/usr/bin/env python # tested on Python 2 & Python 3 ''' Kiff, the Kicad Diff! Graphically compare layout changes between two git versions of a PCB. If `-c` is not given, compares the local working copy against the latest commited version from git. This is useful to verify board changes before committing them. If a...
''' Generate's CT file for Circle Plot based on protein FASTA sequence usage: python generateBaseFile.py apoe.fasta ''' import sys input_name = sys.argv[-1] infile = open(input_name, "r") protein_name = input_name.split('.')[0] output_name = protein_name + ".ct" outfile = open(output_name, "w") #sequence = "KVEQAVE...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-04-14 17:58:38 # @Author : Fallen (xdd043@qq.com) # @Link : https://github.com/fallencrasher/python-learning # @Version : $Id$ #装饰器的应用 #登陆认证 def get_user_pwd(): usr_dict = {} with open('register.txt',encoding='utf-8',mode='r') as f: ...
import passgen import os p = passgen SYMBOLS = '' def start(): print('[1] Generate password\n' + '[2] Settings\n' + '[3] About\n' + '[4] Exit') option = input('--> ') if option == '1': gen() elif option == '2': settings() elif option == '3': abo...
# -*- coding: utf-8 -*- # Задача на программирование: последняя цифра большого числа Фибоначчи # Дано число 1≤n≤107, необходимо найти последнюю цифру n-го числа Фибоначчи. # Как мы помним, числа Фибоначчи растут очень быстро, поэтому при их вычислении нужно быть аккуратным с переполнением. В данной задаче, впрочем, эт...
from collections.abc import Iterable from typing import Any, TypeVar from _typeshed import Incomplete from networkx.classes.graph import Graph _N = TypeVar("_N") def is_k_edge_connected(G: Graph[Any], k: int) -> Incomplete: ... def is_locally_k_edge_connected( G: Incomplete, s: Incomplete, t: Incomplete, k: Inco...