content
stringlengths
5
1.05M
import numpy as np from scipy.ndimage import imread as imread0 import tifffile as tiff def imread_check_tiff(path): img = imread0(path) if img.dtype == 'object': img = tiff.imread(path) return img def imread(path): if isinstance(path, tuple) or isinstance(path, list): st = [] ...
"""Module containing the user entity""" from django.db import models from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager) from shared.base_model import BaseModel class User(AbstractBaseUser, BaseModel): """Model for a user in the system""" class Meta: """Class to add more info...
# TODO: feature - download music based on style & date | quantity # TODO: construct more logical download tree with meta data # TODO: open user's file explorer after download # TODO: setup script # TODO: add license and responsibilities import os import re import datetime import requests import shutil from bs4 import...
import numpy as np from ml_algorithms import utils class DecisionTreeRegressorNode: def __init__(self, score, num_samples, prediction): self.score = score self.num_samples = num_samples self.prediction = prediction self.feature_idx = 0 self.threshold = 0 self.left ...
""" The MIT License (MIT) Copyright (c) 2012, Florian Finkernagel <finkernagel@imt.uni-marburg.de> 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 restriction, including without limitatio...
import pandas as pd #input and output the data data=pd.read_csv('test.csv',header=0,index_col=0) print(data) print(type(data)) data.to_csv('testout.csv',encoding='utf-8-sig')
from django.conf.urls import patterns, url from . import views urlpatterns = patterns('', url(r'^$', views.users, name='all'), url(r'^(?P<user_id>\d+)/$', views.user, name='one'), url(r'^(?P<user_id>\d+)/edit/$', views.edit_view, name='edit'), )
""" Generation of data cos it's tedius to do it by hand """ class Generator: def __init__(self, num_datapoints: int): self.n = num_datapoints self.celcius = [] self.farenheight = [] def getData(self): for i in range(self.n): num = i * 2 + 1 self.celcius...
# # Copyright 2021 LinkedIn Corporation. All rights reserved. Licensed under the BSD-2 Clause license. # See LICENSE in the project root for license information. # import os controller = os.environ['HOROVOD_CONTROLLER'] operators = os.environ['HOROVOD_CPU_OPERATIONS'] timeout = os.environ['HOROVOD_GLOO_TIMEOUT_SECONDS...
from flask import Blueprint from flask_restful import Resource, Api from App.models import HomeBanner api = Api() def init_api(app): api.init_app(app=app) class HomeResource(Resource): def get(self): homebanners = HomeBanner.query.all() return {'msg':'ok'} api.add_resource(HomeResource,'...
from pydantic import BaseModel from datetime import datetime class BusStop(BaseModel): id: int message_text: str city: str created: datetime creator_id: int
"""Configuration tests.""" import os from gt4sd.configuration import ( GT4SDConfiguration, get_algorithm_subdirectories_in_cache, get_algorithm_subdirectories_with_s3, ) gt4sd_configuration_instance = GT4SDConfiguration.get_instance() def test_default_local_cache_path(): if "GT4SD_LOCAL_CACHE_PATH"...
# # Cole Smith # Restaurant Closure Engine # BDS - Undergraduate # prediction.py # # Cluster generation routines for latent restaurant segmentation # from sklearn.decomposition import PCA from src.preprocessing.fetch import fetch_restaurant_inspection_data from src.preprocessing.transform import min_max_scale_values...
import numpy as np import warnings from digideep.agent.sampler_common import Compose, flatten_memory_to_train_key, get_memory_params, check_nan, check_shape, check_stats, print_line from digideep.agent.sampler_common import flatten_first_two from digideep.utility.logging import logger from digideep.utility.profiling ...
from model.contact import Contact def test_edit_first_contact(app): if app.contact.count() == 0: app.contact.create(Contact(firstname ="firstname")) old_contacts = app.contact.get_contact_list() contact = Contact(firstname="TEST") contact.id = old_contacts[0].id contact.lastname = old_conta...
import json import threading import time from flask import Flask, request, make_response, jsonify from flask_restplus import Api, Resource, fields from pub import take_screenshot, RuntimeException, get_image_exists app = Flask("get-screenshot") api = Api(app=app) namespace = api.namespace("/", description="Screensho...
# Copyright 2014-2018 PUNCH Cyber Analytics Group # # 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 applica...
# (c)2021 wolich from utils.io import read_data_table # For now, we simply put the swords data into nested dictionaries. # We avoid the complexity of an "artifact object". def initialize_artifacts(unit='kaeya'): if unit == 'albedo': artifact_set_bonus = read_data_table('../data/artifacts_albedo.tsv') ...
def echo(x): return "echoing: %s" % x
from application import db from sqlalchemy.sql import text # Luokkataulu class Luokka(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(20), nullable=False) kilpailut = db.relationship("Kilpailu", backref='luokka', lazy=True) def __init__(self,name): self.name = name def get_i...
import mol import pytest import numpy as np @pytest.mark.parametrize("molecule, com, natom", [("water", [9.81833333, 7.60366667, 12.673], 3), ("benzene", [-1.4045, 0, 0], 12)],) def test_read_xyz(molecule, com, natom): moldata = mol.data.get_molecule(molecule) assert np.allclose(np.mean(moldata["geometry...
from flask import render_template, request from app import db from app.errors import bp from app.api.errors import error_response as api_error_response def wants_json_response(): return request.accept_mimetypes['application/json'] >= \ request.accept_mimetypes['text/html'] @bp.app_errorhandler(404) def ...
#vaemodel import copy import torch import torch.backends.cudnn as cudnn import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.autograd as autograd from torch.utils import data from data_loader import DATA_LOADER as dataloader import final_classifier as classifier import models ...
from docassemble.webapp.server import app as application if __name__ == "__main__": application.run(host='0.0.0.0')
from django.shortcuts import render, redirect, HttpResponse from .models import Issue, Comment, UserProfile, TeacherProfile, Tags from django.contrib.auth.models import User from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.template.defaultfilters import slugify...
# coding=utf-8 # Copyright 2019 The Tensor2Robot 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 License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
from django.urls import path from contacts.views import Home urlpatterns = [ path('', Home.as_view()), ]
from flask import Flask, request app = Flask(__name__) @app.route("/") def index(): return "Hello, world!" @app.errorhandler(404) def page_not_found(e): return "Not Found: " + request.path
import simuvex ###################################### # listen (but not really) ###################################### import logging l = logging.getLogger("simuvex.procedures.libc.listen") class listen(simuvex.SimProcedure): #pylint:disable=arguments-differ def run(self, sockfd, backlog): #pylint:disable=un...
from table import String, Term, Concept from connection import Connection from collections import defaultdict from itertools import chain class Aggregator(object): """Example class of Aggregate queries using different UMLS tables""" def __init__(self, dbname="umls", hostname="localhost", port=27017): ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the plist plugin interface.""" import unittest from dfdatetime import posix_time as dfdatetime_posix_time from plaso.containers import plist_event from plaso.containers import time_events from plaso.lib import definitions from plaso.parsers.plist_plugins im...
# Generated by Django 3.0.2 on 2020-11-26 04:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('puzzles', '0012_auto_20201111_0130'), ] operations = [ migrations.AddField( model_name='puzzle', name='slack_channel...
import argparse parser = argparse.ArgumentParser(description="This program is a test of argparse.") parser.add_argument('--number')
SECRET_KEY = 'dev' SITES_DICT = { 'www.iie.cas.cn': 'xgs', 'www.is.cas.cn': 'rjs', } ############################################### MYSQL_HOST = 'localhost' MYSQL_PORT = 6761 MYSQL_DB_NAME = 'crawling_db' MYSQL_USER = 'root' MYSQL_PASSWORD = 'mysql' ############################################### S...
"""Send an X10 command.""" from ...constants import ResponseStatus, X10Commands, X10CommandType from ...topics import X10_SEND from ...x10_address import X10Address from .. import ack_handler, nak_handler from ..outbound_base import OutboundHandlerBase class X10CommandSend(OutboundHandlerBase): """Send an X10 co...
import csv with open('names.csv', 'r') as csv_file: csv_reader = csv.reader(csv_file) # to read contents of csv file as dictionary rather than list use this # csv_reader = csv.DictReader(csv_file) # csv_reader contains all an object which contains all data # to see data of csv reader as list we ...
from functools import reduce from operator import mul from typing import Tuple import torch import torch.nn as nn from models.base import BaseModule from models.blocks_2d import DownsampleBlock from models.blocks_2d import UpsampleBlock from models.estimator import Estimator from models.memory import MemModule from ...
from scrapper import * # from process import * import argparse import json def scrapPages(pages, keepTags=True): with open("../data/sources.json", "r") as f: visited = json.load(f) visited_urls = [r["url"] for r in visited] try: with open("scrapped_data.json", "r") as json_file: ...
# Microsoft Azure Linux Agent # # Copyright 2020 Microsoft Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
import os basedir = os.path.abspath(os.path.dirname(__file__)) # BASIC APP CONFIG WTF_CSRF_ENABLED = True SECRET_KEY = 'changeme' LOG_LEVEL = 'DEBUG' LOG_FILE = 'logs/log.txt' # TIMEOUT - for large zones TIMEOUT = 10 # UPLOAD DIR UPLOAD_DIR = os.path.join(basedir, 'upload') # DATABASE CONFIG FOR MYSQL DB_HOST = os....
import unittest from nemex import Entity class TestEntity(unittest.TestCase): def setUp(self) -> None: # TODO: Setup test. self.entity = Entity(0, "") return None def test_example(self): return self.assertEqual("", "") def tearDown(self) -> None: return None i...
class Provider: """Superclass for provider plugins""" DEFAULT_OP_ARGS = {} @classmethod def get_default_op_args(cls, processor): return cls.DEFAULT_OP_ARGS.get(processor, dict()) class TinkerGraph(Provider): # TODO """Default provider""" @staticmethod def get_hashable_id(val): ...
def brightnessApp(display, utime, ujson, bluetooth, startNewThread, playBuzzer, loadJSON, saveJSON, showControls, update, clear): run = True settings = loadJSON("settings.json") display.set_backlight(settings["brightness"]) displayBrightness = int(settings["brightness"] * 10) while run...
# 15/06/2017 import re def condense(str): return re.sub(r"(\w+)\s\1", r"\1", str)
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2018-02-19 03:07 from __future__ import unicode_literals from django.db import migrations from usaspending_api.common.helpers.generic_helper import CORRECTED_CGAC_PG_FUNCTION_DEF from usaspending_api.common.helpers.generic_helper import REV_CORRECTED_CGAC_PG_FUN...
# Copyright 2019 NTRLab # # 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 in writing, softw...
# File: lawnmower.py # from chapter 15 of _Genetic Algorithms with Python_ # # Author: Clinton Sheppard <fluentcoder@gmail.com> # Copyright (c) 2016 Clinton Sheppard # # 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...
import sys from . import more_plugins from .buffered_input import BufferedInput from .page_builder import PageBuilder, StopOutput from .page_of_height import PageOfHeight from .page_wrapper import PageWrapper from .terminal_input import TerminalInput from .terminal_screen import TerminalScreen def MorePageBuilder(*a...
import random def compute_gems(points, num_gems): gems = [] # For each requested gem, fetch a pair of adjacent points from points list and place a gem randomly between them start_indices = random.sample(range(0, len(points)-1), int(num_gems)) start_indices.sort() # Ensure all gems are in strictly i...
from setuptools import setup, find_packages # from setuptools.command.install import install as _install # # # class Install(_install): # def run(self): # _install.do_egg_install(self) # import nltk # nltk.download('stopwords') # nltk.download('punkt') with open("README.md", "r", e...
#! usr/bin/python3.6 """ Module initially auto generated using V5Automation files from CATIA V5 R28 on 2020-07-06 14:02:20.222384 .. warning:: The notes denoted "CAA V5 Visual Basic Help" are to be used as reference only. They are there as a guide as to how the visual basic / catscript function...
#Area of Triangle #Asking for Breadth(b) and Height(h) of triangle. b = float(input("Enter the breadth of the triangle = ")) h = float(input("Enter the height of the triangle = ")) print('Area of triangle = ', h * b / 2," sq.m ")
import random import time import snakefish channel = snakefish.Channel() # create a channel # a function that will be executed on a snakefish thread def f1() -> None: if random.random() < 0.5: print("thread #1: sleep for 100 ms") time.sleep(0.1) ts = snakefish.get_timestamp_serialized() ...
# fill this in with the common functions so i can clean up my shitty code import json import pandas as pd import datetime import math from pathlib import Path import numpy as np def csv_naive_filter(csv_path, list_of_timestamps): df = pd.read_csv(csv_path) df["event_ts"] = pd.to_datetime(df["event_start_time"]) ...
# -*- coding: utf-8 -*- import os from flask import Flask, render_template from flask_cors import CORS from polylogyx.api.api import blueprint as api from polylogyx.celery.tasks import celery from polylogyx.extensions import ( cache, csrf, db, log_tee, mail, make_celery, migrate, rule_...
import scrapy class DocSectionItem(scrapy.Item): title = scrapy.Field() company = scrapy.Field() location = scrapy.Field() class MySpider(scrapy.Spider): name = 'myspider' start_urls = ['https://stackoverflow.com/jobs?med=site-ui&ref=jobs-tab'] def parse(self, response): for a_el...
from copy import deepcopy from json import dumps, loads def test_ffflash_save(tmpdir, fffake): apifile = tmpdir.join('phony_api_file.json') apifile.write_text(dumps({'a': 'b'}), 'utf-8') assert tmpdir.listdir() == [apifile] f = fffake(apifile, dry=True) assert f assert f.args.APIfile == str(...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/bigquery_v2/proto/model.proto import sys _b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode("latin1")) from google.protobuf import descriptor as _descriptor from google.protobuf import message ...
# encoding: utf-8 import os from batman.input_output import formater from tests.plugins import f_snapshot coupling = 'coupling-dir' input_formater = formater('json') output_formater = formater('csv') point = input_formater.read(os.path.join(coupling, 'sample-space.json'), ['X1', 'X2']) result = f_snapshot(point) out...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Activador', fields=[ ('id_esta', models.BigInte...
import json import boto3 import click from tqdm import tqdm from nerd.poll_queue import get_texts_from_queue from nerd.extract import extract_entities @click.command() @click.option( "--source_queue_name", prompt="Source queue name", default="inference-entity-extraction", help="name of the queue whose...
frase = ('Curso em Video Python') dividido = (frase.split()) print(dividido[2][3])
#Problem 1 #Compute the factorial (n!) of a number using recursion import sys def factorial(n): if n ==1: return 1 return n*factorial(n-1) if __name__ == "__main__": try: n = int(input("Ingrese un numero: ")) print(factorial(n)) except Exception as e: print(...
import os import shutil import unittest import tests.helper as helper import thingsvision.vision as vision import numpy as np class FeaturesTestCase(unittest.TestCase): @classmethod def setUpClass(cls): helper.create_test_images() def setUp(self): shutil.rmtree(helper.OUT_PATH) o...
import requests # Vuln Base Info def info(): return { "author": "cckuailong", "name": '''F5 BIG-IP iControl REST unauthenticated RCE''', "description": '''The iControl REST interface has an unauthenticated remote command execution vulnerability.''', "severity": "critical", ...
# ex: set sts=4 ts=4 sw=4 noet: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the reproman package for the # copyright and license terms. # # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## """Facility for ma...
from graphite_feeder.handler.event.enum.alarm import armed from graphite_feeder.handler.event.enum.alarm import triggered
# PYTHON STANDARD LIBRARY IMPORTS --------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function from collections import deque import itertools from os import path # LOCAL MODULE IMPORTS ----------------------------------------...
import os import sys original = sys.stdout original.flush() unbuffered = os.fdopen(original.fileno(), 'w', 0) sys.stdout = unbuffered
from ontobio.io import assocparser from ontobio.io.gpadparser import GpadParser from ontobio.io import gafparser from ontobio.io.gafparser import GafParser from ontobio.io import GafWriter from ontobio.io.assocwriter import GpadWriter from ontobio.assoc_factory import AssociationSetFactory from ontobio.ontol_factory im...
from random import randint computador = randint(0, 10) ntentativas = 0 print('''Sou seu computador... Acabei de pensar em um número entre 0 e 10. Será que você consegue advinhar qual foi?''') jogada = int(input('Qual é o seu palpite? ')) while jogada != computador: if jogada < computador: print('Mais... ...
import io import os import sys import pytest from random import randrange myPath = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, myPath + "/../") import src.utils.messages as msg from src.executor import executor, parser from src.git_manager.git_manager import GitManager from src.profile.profile impor...
import os import re import json from sys import exit from arguments import verify_args # return the $HOME path def get_home(): try: return open('/home/.zshuserpath').readline().strip() except FileNotFoundError: return os.getenv('HOME') # return the absolute path of zsh config file # '/home/venturini/.zshrc', ...
#!/usr/bin/env python import form, app, urwid, layout, button class Dialog (form.Form): """ A modular Form designed to be displayed over the top of other forms. """ def __init__ (self, parent, width, height, align='center', valign='middle', shadow=u'\u2592', top_widget=None): """ In...
from __future__ import generators import sys try: # py 3.8+ from html import escape except ImportError: # py2 from cgi import escape try: raise ImportError import itertools itertools_takewhile = itertools.takewhile except ImportError: # fake it def takewhile(predicate, iterable): ...
from libsaas import http, parsers from libsaas.services import base from . import resource class GistCommentsBase(resource.GitHubResource): path = 'comments' def wrap_object(self, obj): return {'body': obj} class GistComments(GistCommentsBase): @base.apimethod def get(self, format=None, ...
#imports (standard ones first, then the ones I wrote) import numpy as np #for data structures from scipy.io import netcdf #to read DART data from scipy.interpolate import griddata #for interpolation from scipy import interpolate import subprocess #for moving files import sys import cPickle as pickle import datetime, t...
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RAssertiveNumbers(RPackage): """assertive.numbers: Assertions to Check Properties of Numbe...
from torch import nn from torch.optim import SGD from flamecalc.utils import * from tqdm import tqdm class CalVarSolver(nn.Module): def __init__(self, functional, start_point, end_point, domain=None): super().__init__() self.functional = functional self.p_1 = start_point self.p_2 =...
# -*- coding: utf-8 -*- """ Created on Sun Mar 15 15:45:45 2020 @author: Boxi """ import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as seabornInstance from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn import metrics ...
# -*- coding: utf-8 -*- import sys, codecs from tqdm import tqdm SRC_FILE = sys.argv[1] CONTENT_PLAN = sys.argv[2] EVAL_OUTPUT = sys.argv[3] # tuples CONTENT_PLAN_INTER = sys.argv[4] TRAIN = True DELIM = u"│" inputs = [] content_plans = [] with codecs.open(CONTENT_PLAN, "r", "utf-8") as corpus_file: for _, line...
from django.conf import settings from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.contrib import admin from django.views.generic import TemplateView from views import get_api_home, jquery_test_view, home from videos.views import category_list, category_detail, ...
import sys import os import yaml from tables_io import io from rail.estimation.estimator import Estimator # Note: This is where 'base.yaml' actually belongs, but how to make it so def main(argv): if len(argv) == 2: # this is in case hiding the base yaml is wanted input_yaml = argv[1] base_...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
from typing import Dict, Any from final_filter.abc_filtering_module import FilteringModule class PerplexityModule(FilteringModule): def __init__(self, threshold: float): self.threshold = threshold def validate(self, cluster: Dict[str, Any]) -> bool: return cluster["perplexity"] <= self.thres...
import os from cStringIO import StringIO import tarfile import numpy as np from . import get_data_home from tools import download_with_progress_bar TARGETLIST_URL = ("http://www.astro.washington.edu/users/ivezic/" "linear/allDataFinal/allLINEARfinal_targets.dat") DATA_URL = ("http://www.astro.washi...
from snovault import ( CONNECTION, upgrade_step ) @upgrade_step('chip_peak_enrichment_quality_metric', '1', '2') def chip_peak_enrichment_quality_metric_1_2(value, system): if 'FRiP' in value: value['frip'] = value['FRiP'] value.pop('FRiP')
import logging import arrow from dateutil.relativedelta import relativedelta from discord import Embed from discord.commands import ApplicationContext, slash_command from discord.ext import commands from bot import start_time from bot.bot import Bot from bot.core import settings from bot.utils.formatters import color...
from app.clients.email.govdelivery_client import govdelivery_status_map govdelivery_webhook_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "x-www-form-urlencoded POST from Granicus with delivery status define at https://developer.govdelivery.com/api/tms/resource/webhooks/", # ...
# Initialize our dictionary. tokitsukaze = {} # Process our input. tokitsukazeHP = int(input()) # Get our ideal value of Tokitsukaze's rank by brute-forcing through the input received. for i in range(0, 3): tokitsukazeCategory = (int(tokitsukazeHP + i)) % 4 if tokitsukazeCategory == 0: tokitsukaze[i] = 'D' ...
from collections import OrderedDict from tornado.web import RequestHandler from tornado.locale import get_supported_locales from .dispatch import route, LanguageCookieMixin from . import pageutils import libcard2.localization @route("/") class Slash(LanguageCookieMixin): def get(self): self.render("home....
# Generated by Django 2.1.7 on 2019-05-12 19:34 from django.db import migrations, models from django.contrib.postgres.fields import JSONField class Migration(migrations.Migration): dependencies = [ ('device_registry', '0024_fix_scan_info_content'), ] operations = [ migrations.AddField( ...
# coding: utf-8 """ Tools to interact with toolchains GCC, Clang, and other UNIX compilers """ from .util import _create_shared_base, _libext LIBEXT = _libext() def _obj_ext(): return '.o' def _obj_cmd(source, toolchain, options): obj_ext = _obj_ext() return '{} -c -O3 -o {} {} -fPIC -std=c99 {}' \ ...
""" In computer science, merge sort (also commonly spelled mergesort) is an efficient, general-purpose, comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output. Mergesort is a divide and conquer ...
from math import ceil, floor from pygears.typing import Fixp, Ufixp, Uint, Int def test_abs(): uq2_3 = Ufixp[2, 3] q2_3 = Fixp[2, 3] q3_4 = Fixp[3, 4] assert abs(uq2_3.max) == uq2_3.max assert abs(q2_3.min) == q3_4(abs(float(q2_3.min))) def test_add(): uq2_3 = Ufixp[2, 3] uq2_4 = Ufixp[...
import base64 import hashlib from inspect import ( signature, ) import json import logging.config import re from typing import ( Any, Callable, Mapping, Optional, Sequence, Union, ) import urllib.parse from botocore.exceptions import ( ClientError, ) import chalice # noinspection PyPack...
from .handlers import TutorialHandler def _jupyter_server_extension_points(): return [{ "module": "mybutton" }] def load_jupyter_server_extension(server_app): handlers = [("/mybutton/hello", TutorialHandler)] server_app.web_app.add_handlers(".*$", handlers)
# Kaolin PCB Converter Utility # # ILAN E. MOYER # March 30th, 2021 # # One goal of the Kaolin project is to embed the design for an MCU's PCB within the memory of the MCU # This script reads in an Autodesk Eagle PCB (.brd) file, and converts it into the Kaolin format, and # saves out an Intel HEX file. import xml.etr...
from io import BytesIO import json from typing import List import flask import pytest def test_parameter_validation(simple_app): app_client = simple_app.app.test_client() url = "/v1.0/test_parameter_validation" response = app_client.get(url, query_string={"date": "2015-08-26"}) # type: flask.Response ...
#!/usr/bin/env python2 from flask import Response from dns import query, zone, rdtypes, rdatatype, rdataclass, rdata, update, tsigkeyring import dns.query import dns.message import dns.rdatatype import dns.rdata import dns.rdtypes import dns.tsigkeyring import dns.update from .models import * import urllib import IPy...