content
stringlengths
5
1.05M
# Unless explicitly stated otherwise all files in this repository are licensed under the the Apache License Version 2.0. # This product includes software developed at Datadog (https://www.datadoghq.com/). # Copyright 2021 Datadog, Inc. import re from utils.tools import logger def _spans_with_parent(traces, parent_id...
import versioneer from setuptools import setup setup_args = dict( name='nbexamples', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), license='BSD', platforms=['Jupyter Notebook'], packages=[ 'nbexamples' ], include_package_data=True, install_requires=[ ...
# Searching Algorithm Visualizer # from tkinter import * from tkinter import messagebox from PIL import Image,ImageTk import time class Initialization: def __init__(self,root): self.window= root self.store=[10,20,30,40,50,60,70,80,90,100] self.search_positio...
import argparse import json import logging import os from flask import Flask, request, jsonify, abort from flask_restful import Api parser = argparse.ArgumentParser(description='Multimedia probe analysis.') parser.add_argument( '-j', dest='json', type=str, help='JSON template for instances in server') parser.add_...
# -*- coding: utf-8 -*- import sys import json FLAT = False SEPARATOR = ">" def dumps(data): if FLAT: return json.dumps(data) return json.dumps(data, indent=4, sort_keys=True) def output(data, fh=sys.stdout): """Output data, if it is not string, then serialized to JSON. Input: - ...
from inferencer import Inferencer, Inferencer_Params from tfcore.interfaces.IPipeline_Inferencer import IPipeline_Inferencer_Params, IPipeline_Inferencer from tfcore.utilities.preprocessing import Preprocessing import gflags import os import sys import imageio import numpy as np def get_filename(idx, filename='', dec...
""" Created on 21 Aug 2013 @author: Anna """ import math import numpy import random from .Globals import G class Allocation: def __init__(self, itemList, week, altRoutes, excBuffer): self.week = week self.altRoutes = altRoutes self.itemList = itemList self.excBuffer = excBuffer ...
from configs import Level, LEVEL_MAP, PROCESS_METRICS_FIELDS from db.QueryBuilder import get_level_refactorings, get_level_stable from refactoring_statistics.plot_utils import box_plot_seaborn_simple from refactoring_statistics.query_utils import retrieve_columns, get_last_refactored_instance_all from utils.log import...
"""Simple HTML5 document builder.""" __version__ = '0.1.0' __author__ = 'skitschy' class HTML5Builder: """Simple HTML5 generator class. The following code generates a blank japanese HTML5 document. >>> tag = HTML5Builder() >>> doc = tag.html([tag.head(''), tag.body('')], lang='ja') >>> str(tag....
# 1.7.2 Woche 1, Block 7, Aufgabe 2 # Import from turtle import * from random import randint # Malen Settings speed(10) bgcolor('black') x = 1 while x < 400: r = randint(0, 255) g = randint(0, 255) b = randint(0, 255) colormode(255) pencolor(r, g, b) fd(50 + x) rt(90.911) x += 1 e...
# -*- coding: utf-8 -*- #!/bin/env python3 # 194-67-90-149 import os, sys import time import io import getopt import subprocess import time import signal import yaml import requests os.system('cls') re = "\033[1;31m" gr = "\033[1;32m" cy="\033[1;36m" logo = (f""" _ __ {re}___ __{...
import datetime import unittest from base import option class TestOptionsClass(unittest.TestCase): def testOptionClassCreation(self): """Tests than an exception is raised when class is instantiated.""" with self.assertRaisesRegex(TypeError, "Cannot instantiate abstract class."): option.Option(underlyi...
import time import struct try: # Try to import the Python 3.x enum module from enum import IntEnum except: # If we're on Python 2.x we need to define # a dummy replacement class IntEnum: pass # <pep8 compliant> LOG_READ_TIME = False LOG_WRITE_TIME = False LOG_ANIM_HEADER = False LOG_ANIM...
# Copyright (C) 2019-2021 HERE Europe B.V. # # 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 t...
from minpiler.std import L, M, inline @inline def f(x): y = x M.print_flush(y) f(L.message1) # > printflush message1
import matplotlib.pyplot as plt import pyDeltaRCM with pyDeltaRCM.shared_tools._docs_temp_directory() as output_dir: delta = pyDeltaRCM.DeltaModel(out_dir=output_dir) for _t in range(0, 5): delta.update() delta.finalize() fig, ax = plt.subplots() ax.imshow(delta.bed_elevation, vmax=-3) plt.sho...
from db.tables import materials def load(): return materials.read()
import psycopg2 import numpy as np from numpy import convolve import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt from psycopg2 import Error from DataProcessing import StockData import displayData import sys def pullColumnAll(cursor, ticker, column_name): """ Retrieves specific column d...
#!/usr/bin/env python # -*- coding:utf-8 -*- # author: owefsad@huoxian.cn # datetime: 2021/7/1 下午3:02 # project: dongtai-engine from django.db import models from dongtai.models.agent import IastAgent from dongtai.utils.settings import get_managed class IastReplayQueue(models.Model): agent = models.ForeignKey(Ias...
"""Check if userbot alive. If you change these, you become the gayest gay such that even the gay world will disown you.""" #IMG CREDITS: @WhySooSerious import asyncio from telethon import events from uniborg.util import admin_cmd from userbot import ALIVE_NAME from telethon.tl.types import ChannelParticipantsAdmins DEF...
def LoadParameters(name): if name == 'q50_4_3_14_params': from parameters.q50_4_3_14_params import GetQ50Params return GetQ50Params() elif name == 'q50_3_7_14_params': from parameters.q50_3_7_14_params import GetQ50Params return GetQ50Params() elif name == 'q50_11_20_14_param...
# @copyright@ # Copyright (c) 2006 - 2018 Teradata # All rights reserved. Stacki(r) v5.x stacki.com # https://github.com/Teradata/stacki/blob/master/LICENSE.txt # @copyright@ import stack.commands class Command(stack.commands.remove.environment.command): """ Remove an attribute for an Environment. <arg type='str...
from keras_batchflow.base.batch_shapers import BatchShaper from keras_batchflow.base.batch_shapers import IEncoderAdaptor from keras_batchflow.base.batch_shapers import NumpyEncoderAdaptor from keras_batchflow.base.batch_shapers import PandasEncoderAdaptor
# VISA full time master's ph.D question. # money = 50, items_per_bundles = 20, bundel_cost = 12 def find_bundles(money, items_per_bundles, bundel_cost): total_money_spent = 0 total_bundel = 0 if money == 0: return 0 while total_money_spent <= money and money - total_money_spent >= bundel_...
import os # Rules for bracket based off of https://www.boydsbets.com/whats-the-farthest-each-seed-has-gone-in-the-tournament/ # Rule 1) Only pick from the top 3 seeds to win tournament # Rule 2) Best for seeds 4-7 is final four # Rule 3) Best for seeds 9-11 is elite eight # Rule 4) Best for seeds 12-16 is swee...
import requests from bs4 import BeautifulSoup headers = { 'User-Agent': 'Mozilla/5.0', } headers = {'Accept-Language': "lang=AR-DZ"} s = requests.Session() url = 'http://www.mae.gov.dz/select_language.aspx?language=ar&file=default_ar.aspx' r = s.get(url)#, headers=headers) url = 'http://www.mae.gov.dz/news_...
dlga_start:close_window = 0 dlga_member_chat:close_window = 1 dlga_event_triggered:close_window = 2 dlga_start:hideout_warder_1 = 3 dlga_start:hideout_torturer_1 = 4 dlga_start:brothel_manager = 5 dlga_start:nakepit_manager = 6 dlga_start:nakepit_manager = 7 dlga_start:close_window.1 = 8 dlga_start:bath_manager = 9 dlg...
from pathlib import Path from typing import List, Dict, Any, Optional import yaml from remi import App import os DAY_FORMAT = "%Y-%m-%d" HOUR_FORMAT = "%H:%M:%S" DATE_FORMAT = f"{DAY_FORMAT} {HOUR_FORMAT}" # the number of seconds between to events to be # considered as two different events EVENTS_SEQUENCE_SEPARATION...
import re import os import logging from concurrent.futures import ProcessPoolExecutor from libs.libmd5 import md5_for_text from libs.librequests.api import ( download_text, download_binary, ) logger = logging.getLogger(__name__) image_url_ptn = re.compile(r'src="(https://mmbiz.qpic.cn/mmbiz_.*?)"') def ge...
import json import numpy as np import os import sys import torch from datasets import mnist, celeba from neural_process import NeuralProcessImg from time import strftime from training import NeuralProcessTrainer device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # Get config file from command line ...
# Generated by Django 2.2.5 on 2020-05-19 21:46 import atlas.models.change import django.contrib.postgres.fields.jsonb from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("atlas", "0029_change_user")] operations = [ migrations.AddField( model...
import numpy as np from torch.utils.data import DataLoader from torch.utils.data.sampler import SubsetRandomSampler import torchvision.transforms as transforms from dataloader.gaussian_blur import GaussianBlur from torchvision import datasets from .dataset import ClrDataset np.random.seed(0) class DataSetWrapper(obj...
#!/usr/bin/env python3 import requests import yaml import json configFile = "config.yml" # save api requests to files def save(name, obj): with open('users/'+name+'.yaml', 'w') as f: yaml.dump(obj, f) def printJson(json_object): print(json.dumps(json_object, indent=1)) def getUsers(cnf): cnf["max_p...
from os import listdir from PIL import Image import os dataset = "./cleaned/" train_path = dataset + "train_frames/" val_path = dataset + "val_frames/" test_path = dataset + "test_frames/" sets = [train_path, val_path, test_path] for dataset in sets: emotions = os.listdir(dataset) for emotion in emotions: fr...
import os import sys import re import glob import urllib.request, urllib.error, urllib.parse import json from MediaManager.image.library.image import ImageInfo class AlbumArtLibrary(object): def __init__(self, image_cache_path, online=True): self.__image_cache_path = image_cache_path self.__not_f...
import torch import torch.nn as nn from mimic.networks.FeatureCompressor import LinearFeatureCompressor from mimic.networks.char_encoding import DataGeneratorText as DataGeneratorText_CharEnc from mimic.networks.char_encoding import FeatureExtractorText as FeatureExtractorText_CharEnc from mimic.networks.word_encoding...
import sys import json import redis if __name__ == '__main__': with open(sys.argv[1]) as f: config = json.load(f) host = config['redis_address'] port = config['redis_port'] redis_client = redis.Redis(host='localhost', port=6379) # Load the config file routine_config_file_path = confi...
class Solution: def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: strs = [] tmp = '' for s in paragraph: if s in '!? \';.,': if tmp: strs.append(tmp) tmp = '' else: tmp += s.lowe...
#coding: utf-8 SAMPLE_RATE = 44100 WAVETABLE_SAMPLE_SIZE = 512 KEYNOTE_FREQ = [27.5, 29.13523509, 30.86770633, 32.70319566, 34.64782887, 36.70809599, 38.89087297, 41.20344461, 43.65352893, 46.24930284, 48.9994295, 51.9130872, 55, 58.27047019, 61.73541266, 65.40639133, 69.29565774, 73.41619198, 77.78174593, 82.40688923...
import rospy from std_msgs.msg import String def callback(str): pass if __name__=="__main__": rospy.init_node("start") rospy.logerr("script start") rospy.Subscrier("lll",String,callback) rospy.spin()
import os import json from typing import Dict from athena.helpers.exception import EnvironmentException ATTACH = '__attachments__' MESSAGE = 'message' def structure(clz=None): """ The structure decorator provides an interface to create structured data by defining inner data classes within a Python obje...
from flask import abort import requests def readable_format(num): magnitude = 0 while abs(num) >= 1000: magnitude += 1 num /= 1000.0 num = num - num % 0.01 return '{}{}'.format('{:f}'.format(num).rstrip('0').rstrip('.'), ['', 'K', 'M', 'B', 'T'][magnitude]) def multi_scrape(string_s...
import os import re import sphinx import sys import urllib from docutils import nodes from docutils.parsers.rst import directives from jinja2 import Template from pkg_resources import parse_version from sphinx.environment import NoUri from sphinxcontrib.needs.utils import status_sorter from sphinxcontrib.needs.filter...
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='docxify', version='0.1.3', description='docxify and dedocxify fi...
from django.utils.html import format_html from logger.models import User from functools import reduce import django_tables2 as tables import math import datetime class UserTable(tables.Table): def render_card_id(self, value): return format_html('<a href="{}">{}</a>', value, value) class Meta: ...
import unittest import EllucianEthosPythonClient import pytz import datetime class test_WorkerThread_prefCounterTimeValueISBefore(unittest.TestCase): def test_nextTimeSimple(self): self.assertEqual( EllucianEthosPythonClient.getNextWorkerTime( lastRunTime=pytz.timezone('UTC').localize(datetime.dat...
from django.test import TestCase from django.contrib.auth.models import User from .models import Project, Rating, UserProfile # Create your tests here. class TestProject(TestCase): def setUp(self): self.user=User(email='francis@gmail.com',username='fgithae',first_name='user',last_name='fgithae') self.project...
#!/usr/bin/env python3 NUMBER_OF_MARKS = 5 if __name__ == '__main__': mark_list = [] for count in range(NUMBER_OF_MARKS): while True: mark = int(input(f'Enter mark #{count + 1}: ')) if 0 <= mark <= 100: mark_list.append(mark) break ...
""" Definition of views. """ from django.conf import settings from django.shortcuts import render from django.http import HttpRequest, JsonResponse, HttpResponseRedirect, HttpResponse from django.template import RequestContext from cgi import parse_qs, escape from django.views.decorators.csrf import csrf_exempt from d...
#!/usr/bin/env python # sneeze-translator/sneeze-translator.py from Processor import Processor import os import json from dotenv import load_dotenv import logging import discord import tweepy from tweepy.streaming import StreamListener from time import strftime from datetime import datetime from queue import Queue fro...
import copy import logging import numpy as np from pymatgen.io.vasp import Chgcar, VolumetricData, Elfcar from cams.propressing.data_rotate import rotation_axis_by_angle, rote_index from cams.propressing.spilt_tri import relative_location, spilt_tri_prism_z try: # import matplotlib # matplotlib.use('Agg') ...
from os import getenv, walk, path from platform import system read = open("Game.spec", "rt", encoding="utf-8").readlines() for index, line in enumerate(read): if line.startswith("assets = [('"): newassets = [] for (dirpath, dirnames, filenames) in walk("assets"): for dirname in dirname...
import os import tomodachi from typing import Any, Dict from tomodachi import aws_sns_sqs, aws_sns_sqs_publish from tomodachi.discovery import AWSSNSRegistration from tomodachi.protocol import JsonBase @tomodachi.service class ExampleAWSSNSSQSService(tomodachi.Service): name = 'example_aws_sns_sqs_service' lo...
values = list() values.append(5) values.append(9) values.append(4) values.remove(4) for c, v in enumerate(values): print(f'Na posição {c} achei o valor {v}!') print('Cheguei no final!')
import telnetlib import requests from loguru import logger headers = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-CN,zh;q=0.9", "Cach...
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-02-25 12:27 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('scheduler', '0002_authenticationtoken'), ] operations = [ migrations.AddField(...
#=============================================================================# # # # MODIFIED: 15-Jan-2019 by C. Purcell # # # ...
#!/usr/bin/python # -*- coding: utf-8 -*- """Unit tests for WikidataStuff.""" from __future__ import unicode_literals import json import mock import os import unittest import pywikibot from wikidatastuff import wikidata_stuff from wikidatastuff.reference import Reference # replace with mocks from wikidatastuff.stat...
# coding=utf-8 # import importlib # import torch # from collections import OrderedDict # from copy import deepcopy # from os import path as osp # from tqdm import tqdm # # from basicsr.models.archs import define_network # from basicsr.models.base_model import BaseModel # from basicsr.utils import get_root_logger, imwri...
from flask import request, current_app from flask.views import MethodView from app.helpers import ( response_data, args_check, login_required, JSONObject ) from app.v0.users.validators import UserValidator, ChangePasswordValidator, RequestPasswordChangeValidator from app.errors import E000, E...
import os import csv import glob import json def load_stripped_dataset(data_dir): users = {} for filepath in glob.glob(os.path.join(data_dir, '*.json')): with open(filepath, 'r') as f: d = json.loads(f.read()) for raw_uid in d: uid = int(raw_uid) ...
banner="http://www.pythonchallenge.com/pc/def/banner.p" dir=".\\Data\\005" import helper helper.ensureDir(dir) import urllib.request (filename,headers)=urllib.request.urlretrieve(banner,dir+'\\banner.p') import pickle data=pickle.Unpickler(open(filename,'rb')).load() # print(data) for line in data: for tupleit...
""" link.py: Helper functions for generating links. """ import settings def spreadsheet(file_id): return 'https://docs.google.com/spreadsheets/d/' + file_id def unsubscribe(user_email): return 'http://www.' + settings.URL + '/unsubscribe?email=' + user_email
from ..backend import Kernel from ..HKernel import HKernel from ..SCacheton import SCacheton from ..Tensor import Tensor from .Initializer import Initializer class InitConst(Initializer): def __init__(self, value=0): """ arguments value(0) """ super().__init__() ...
from django import forms from django.conf import settings from reviews import models as review_models from . import models class CelebrityForm(forms.ModelForm): class Meta: model = models.Celebrity fields = '__all__' widgets = { 'duties': forms.CheckboxSelectMultiple, ...
''' Have the function SimpleSymbols(str) take the str parameter being passed and determine if it is an acceptable sequence by either returning the string true or false. The str parameter will be composed of + and = symbols with several letters between them (ie. ++d+===+c++==a) and for the string to be true each let...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('analytics', '0001_initial'), ] operations = [ migrations.AddField( model_name='case', name='missing_...
from math import sqrt import json import sys import multiprocessing as mp from utils import _progBar, _chunkIt, loadFile, loadJSON class Recommender: def __init__(self, user_source, object_source, processes=4): self.user_data = user_source self.object_data = object_source self.objects = se...
import hashlib import json import logging import os from typing import List, Optional from pip._vendor import requests from toncommon.contextmanager import secret_manager from toncommon.core import TonExec from toncommon.models.TonCoin import TonCoin from toncommon.models.depool.DePoolElectionEvent import DePoolElecti...
#!/usr/bin/env python3 # # Filter coverage reported by lcov # # Copyright 2020 BlueKitchen GmbH # import sys blacklist = [ '/opt/local', '3rd-party/yxml', '3rd-party/tinydir', 'chipset/zephyr', 'platform/embedded/btstack_audio_embedded.c', 'platform/embedded/btstack_em9304_spi_embedded.c', ...
#!/usr/bin/env python ''' Python + Ansible - Class 3 - Exercise 2 Gleydson Mazioli da Silva <gleydsonmazioli@gmail.com> I created this program with a different concept: Data saving and load using a yaml or json file. So the system save system resources and can be run throught a cron or anacron job. ''' import snmp_he...
import asyncio import logging import sys import weakref if sys.version_info >= (3, 7): def get_loop(task): return task.get_loop() else: def get_loop(task): return task._loop class StreamSink: def __init__(self, stream): self._stream = stream self._flushable = callable(...
import xml.etree.ElementTree as ET tree = ET.ElementTree(file='FR.xml') indent = 0 ignoreElems = ['/word/document.xml'] def printRecur(root, f): """Recursively prints the tree.""" # print('root tag:', root.tag, root.text) global indent if root.tag in ignoreElems: return f.write(' ' * inden...
#!/usr/bin/env python3 from qsilInterpreter import Object, Pointer, Interpreter, Bytecode, SpecialIDs, VisibilityTypes, QSIL_TYPE_DIRECTOBJECT, QSIL_TYPE_DIRECTPOINTEROBJECT from struct import pack printBytecodes = False classClassInstVars = [] methodClassInstVars = [] bootstrapPtr = None class QSILClass(object): ...
from typing import Optional from django.db import models from ...apps import UFDLCoreAppConfig from ...exceptions import * from ..mixins import DeleteOnNoRemainingReferencesOnlyModel, DeleteOnNoRemainingReferencesOnlyQuerySet class NodeQuerySet(DeleteOnNoRemainingReferencesOnlyQuerySet): """ A query-set ove...
import dotenv import tweepy def load_dot(): dotenv.load() def handleAuth(): consumer_key = dotenv.get('ENV_KEY') consumer_secret = dotenv.get('ENV_SECRET') access_key = dotenv.get('TOKEN_KEY') access_secret = dotenv.get('TOKEN_SECRET') auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_a...
# _*_ coding: utf-8 _*_ """ ------------------------------------------------- @File Name: __init__.py @Description: @Author: caimmy @date: 2019/10/22 17:46 ------------------------------------------------- Change Activity: ------------------------------------------------- """
import pytest from api.search.serializers import SearchSerializer from api_tests import utils from osf.models import MetaSchema from osf_tests.factories import ( AuthUserFactory, NodeFactory, ProjectFactory, ) from tests.utils import make_drf_request_with_version, mock_archive from website.project.metadata...
# coding: utf-8 """ Ed-Fi Operational Data Store API The Ed-Fi ODS / API enables applications to read and write education data stored in an Ed-Fi ODS through a secure REST interface. *** > *Note: Consumers of ODS / API information should sanitize all data for display and storage. The ODS / API provides reas...
#-*- coding: utf-8 -*- import sys import os import glob import click #import click_completion #click_completion.init() from sequana import version import functools __all__ = ["main"] import sequana import colorlog logger = colorlog.getLogger(__name__) # This can be used by all commands as a simple decorator def...
import datetime as dt from library.ftx.base import AsyncBaseApiClass class Wallet(AsyncBaseApiClass): """https://docs.ftx.com/#account""" def __init__(self, api_key: str, secret_key: str, subaccount_name: str = ''): super().__init__(api_key, secret_key, subaccount_name) async def get_coins(self...
import click from .adni_to_bids import adni_to_bids_cli from .aibl_to_bids import aibl_to_bids_cli from .nifd_to_bids import nifd_to_bids_cli from .oasis3_to_bids import oasis3_to_bids_cli from .oasis_to_bids import oasis_to_bids_cli @click.group("convert") def cli() -> None: """Convert popular neuroimaging data...
__author__ = 'jwely' __all__ = ["gap_fill_interpolate"] from dnppy import core from to_numpy import to_numpy from is_rast import is_rast import arcpy import os def gap_fill_interpolate(in_rasterpath, out_rasterpath, model = None, max_cell_dist = None, min_points = None): """ Fills g...
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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 ...
# tests for correct PEP479 behaviour (introduced in Python 3.5) # basic case: StopIteration is converted into a RuntimeError def gen(): yield 1 raise StopIteration g = gen() print(next(g)) try: next(g) except RuntimeError: print('RuntimeError') # trying to continue a failed generator now raises StopIt...
from typing import Optional from fastapi import APIRouter from src.controllers.schedule_controller import get_group_schedule, get_teacher_schedule from src.schemas.schema import x_schedule_header from src.utils.events import Events from src.utils.tracking import track tag = "Schedule" router = APIRouter() @router....
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2012 The Plaso Project Authors. # Please see the AUTHORS file for details on individual authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the L...
from django.urls import path from django.contrib.auth import views as auth_views from django.contrib import admin from . import views urlpatterns = [ path("signup", views.signup, name="signup"), path("logout", auth_views.LogoutView.as_view(), name='logout'), path("login" , auth_views.LoginView.as_view(),...
import sqlite3 from flask import Flask, jsonify, json, render_template, request, url_for, redirect, flash from werkzeug.exceptions import abort import logging from multiprocessing import Value counter = Value('i', 0) length = Value('i', 0) # Function to get a database connection. # This function connects to database ...
# 给出一个完全二叉树,求出该树的节点个数。 # # 说明: # # 完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。 # # 示例: # # 输入: # 1 # / \ # 2 3 # / \ / # 4 5 6 # # 输出: 6 # # 来源:力扣(LeetCode) # 链接:https://leetcode-cn.com/problems/count-complete-tree-nodes # 著作权归领扣网络所有。商业转载请联系官方授权,非商业转...
from pyspark.sql import SparkSession, DataFrame from pyspark.sql.functions import row_number, rank, dense_rank, percent_rank, ntile, cume_dist, lag, lead, col, avg, \ min, max, sum, round, count, datediff, unix_timestamp, stddev, collect_list, element_at, size, sort_array, \ broadcast, spark_partition_id, lit, ...
"""Copy database structures to a new database file.""" # Copyright (c) 2001-2009 ElevenCraft Inc. # See LICENSE for details. import os import schevo.database from schevo.script.command import Command from schevo.script import opt usage = """\ schevo db copy [options] SRCURL DESTURL SRCURL: The database to copy th...
""" :mod:`wsgi` =========== Provide a WSGI callable. (It could be nice if this was at ``pando:wsgi`` instead of ``pando.wsgi:website``, but then Website would be instantiated every time you import the ``pando`` module. Here, it's only instantiated when you pass this to a WSGI server like gunicorn, spawning, etc.) ""...
import matplotlib.pyplot as plt import numpy as np from matplotlib.widgets import SpanSelector import SpectrumPlotter import ImagePlotter import Image import collections import os from mpl_toolkits.axes_grid1 import host_subplot import matplotlib matplotlib.use('TkAgg') '''Things to do: Add vertex addition and deletio...
from main import calc_angle_mbc import unittest class CalcAngleTests(unittest.TestCase): def test_angle_one(self): self.assertEqual(calc_angle_mbc(10, 10), 45) def test_angle_two(self): self.assertEqual(calc_angle_mbc(1, 10), 6) def test_angle_three(self): self.assertEqual(calc_a...
from collections import deque def find_route_dfs(graph, start, end, path=[]): path = path + [start] if start == end: return path if start not in graph: return None for node in graph[start]: if node not in path: newpath = find_route_dfs(graph, node, end, path) ...
# -*- coding: utf-8 -*- # Copyright (c) 2016 Holger Nahrstaedt # See COPYING for license details. """ Helper function for annotations """ from __future__ import division, print_function, absolute_import import numpy as np from scipy.interpolate import interp1d import matplotlib.pyplot as plt from mpl_toolkits.mplot3...
FOREST, PLAINS, MOUNTAIN, HILLS, SWAMP, WATER, DESERT, FROZEN, JUNGLE, WASTELAND, BEACH, NETHER, END, MUSHROOM, MAGICAL.
from pyleap import * elli = Ellipse(200, 200, 140, 60, "red") def draw(dt): window.clear() elli.rotation += 1 elli.draw() repeat(draw) run()
# import cucim import math import numbers import numpy as np import uarray as ua import dask.array as da from skimage import filters from skimage.util import apply_parallel from skimage._backend import scalar_or_array from skimage._shared.utils import _supported_float_type # Backend support for skimage.filters _imp...