content
stringlengths
5
1.05M
import random import discord from discord.ext import commands from .inputs import responses, fortunes, quo, nerd, tech, rost, bk, cmp, blurt, jk from .utils import COLOR class Fun(commands.Cog): def __init__(self, client): self.client = client @commands.command(aliases=["8ball"]) async def magicb...
import functions import numpy as np import math import matplotlib.pyplot as plt from matplotlib.textpath import TextPath from matplotlib.patches import PathPatch def alignment_bracket_processing(serial_brackets, serial_alignment, n): spine = [i[0] for i in serial_brackets] serial_brackets = [[i, i...
import pytest import asyncio import ucp async def talk_to_client(ep, listener): recv_req = await ep.recv_future() recv_msg = ucp.get_obj_from_msg(recv_req) ucp.destroy_ep(ep) ucp.stop_listener(listener) async def talk_to_server(ip, port): client = await ucp.get_endpoint(ip, port) await clien...
import pytest from requests import HTTPError from .bases import _TestInteractionBase, _random_slave_channel_and_port, _slave_endpoint, _get_master_endpoint from ..test_utils import random_port from ...master.task import TaskStatus @pytest.mark.unittest class TestInteractionSimple(_TestInteractionBase): @pytest....
""" From Problem Set 1: American Express uses 15-digit numbers, MasterCard uses 16-digit numbers, and Visa uses 13- and 16-digit numbers All American Express numbers start with 34 or 37; most MasterCard numbers start with 51, 52, 53, 54, or 55 and all Visa numbers start with 4. """ amex = ['34', '37'] mcard = ['51',...
from .visualizer import CustomVisualizer from .extend_utils_boxes import pairwise_ioa, pairwise_intersection
"""Import modules.""" from typing import List from .impact import AggregateImpact, CompoundPlayerImpact, SimplePlayerImpact from .io import ( GetGamesList, LoadRatingData, ScoreboardLoader, BoxScoreLoader, LoadSurvivalPredictions, LoadSwapProbabilities, SaveImpactData, SavePlayerTimeSe...
#!/usr/bin/env pytest-3 import bisect import collections.abc import pytest class SortedList(collections.abc.Sequence): # Subclassing `list` is possible but discouraged because it would still expose # the `append` and `insert` methods, which can make the list unsorted. def __init__(self, iterable=()): ...
def Articles(): """create articles and store them in an array """ articles = [ { 'id': 1, 'title': 'Article One', 'body': 'This is the description of article one. Should define all ones and zeros for this matter', 'author': 'Tsofa Nyule', 'crea...
# Copyright (c) 2017 ntfwc # # 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 limitation the rights # to use, copy, modify, merge, publish, distribute, ...
import os import unittest from Bio import SeqIO import filecmp from genofunk import editfile EditFile = editfile.EditFile Edit = editfile.Edit this_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) data_dir = os.path.join(this_dir, 'tests', 'data', 'editfile') class TestEditFile(unittest.TestCase): ...
import re from django import forms from django.utils.safestring import mark_safe import happyforms from product_details import product_details from tower import ugettext as _, ugettext_lazy as _lazy from apps.groups.models import Group, Skill, Language from apps.users.helpers import validate_username from apps.users...
# Installed packages from flask import request import yfinance as yf import redis import requests # Local from utils.symbols import symbols import models as m # Built in packages from datetime import date import os import json from .datenow import day_of_week r = redis.Redis.from_url(os.getenv('REDIS_URL')) url = "...
from os.path import expanduser, join HOME = expanduser("~") GDRIVE_PATH = join(HOME, '.gdrive') CREDENTIALS_PATH = join(GDRIVE_PATH, 'credentials.json') TOKEN_PATH = join(GDRIVE_PATH, 'token.pickle') EXTRACTOR_CONFIG_FILE = join(GDRIVE_PATH, 'data_config.json') UPLOAD_CHUNK_SIZE = 1024 * 1024 * 10 # 10MB DOWNLOAD_CHU...
DEFAULT_BRANCH = "main" DEFAULT_INTERVAL = 900
import requests import os import logging from tqdm import tqdm from glob import glob from .utils import _delete_folder, _get_home logger = logging.getLogger('backblaze') def check_file_cloud(base_url, url): url = base_url + url r = requests.head(url) exist = r.status_code == 200 if exist: ver...
import json import requests class TroiaClient(object): __ENDPOINT_STATUS = 'status' __ENDPOINT_ADD_JOB = 'jobs' __ENDPOINT_DELETE_JOB = 'jobs' __ENDPOINT_GET_JOB = 'jobs/{}' __ENDPOINT_COMPUTE = 'jobs/{}/compute' __ENDPOINT_ADD_ASSIGNS = 'jobs/{}/assigns' __ENDPOINT_GET_WORKER = 'jobs/{}/w...
import torch import torch.nn as nn import torch.nn.functional as F from ..utils import get_activation def make_att_3d(attention, channel, act_mode='relu'): if attention == 'strip_pool': return StripPoolingAttention3D(channel, act_mode) elif attention == 'plane_pool': return PlanePoolingAttent...
from stats_grabber import sorted_data def gen_prometheus_out(): out = "" for lk in sorted_data()["data"]: name = lk['name'].replace('-','_') name = name.replace(' ','_') name = name.replace("ä", "ae") name = name.replace("ü", "ue") name = name.replace("ö", "oe") ...
from django.urls import path,include from . import views urlpatterns = [ path('',views.send_message,name="contact"), ]
# -*- coding: utf-8 -*- """ cannlytics.traceability.leaf.client ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module contains the Client class responsible for communicating with the Leaf Data Systems API. """ from json import dumps from datetime import datetime from requests import Session from .exceptions import APIError...
from django import forms from crispy_forms.helper import FormHelper from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Field, HTML from crispy_forms.bootstrap import FormActions class mileageEntryForm(forms.Form): expenseDate = forms.DateField(label='Expense Date') mile...
#-*- coding: utf-8 -*- import six import base64 import select from hashlib import sha1 from wsgiref import util from django.core.wsgi import get_wsgi_application from django.core.servers.basehttp import WSGIServer, WSGIRequestHandler from django.core.handlers.wsgi import logger from .. import settings from django.core....
# This __init__.py file for the vehicleConfigData package is automatically generated by the build system from vehicleConfigData import *
# Tai Sakuma <tai.sakuma@gmail.com> import copy import collections import logging try: import unittest.mock as mock except ImportError: import mock from alphatwirl.loop import CollectorComposite, ReaderComposite ##__________________________________________________________________|| class MockCollector(object...
import unittest from openbci.cyton import OpenBCICyton PORT = 'loop://' class TestOpenBCICyton(unittest.TestCase): def setUp(self): self.cyton = OpenBCICyton(port=PORT) def tearDown(self): self.cyton.disconnect() def test_init(self): """After initialization, we send b'v' to ini...
from . import constants def unit_string_to_cgs(string: str) -> float: """ Convert a unit string to cgs. Parameters ---------- string The string to convert. Returns ------- float The value in cgs. """ # distance if string.lower() == 'au': return co...
from aws_cdk import core from pipelines_source.pipeline_lambda_stack import PipelineLambdaStack def test_lambda_handler(): # GIVEN app = core.App() # WHEN PipelineLambdaStack(app, 'Stack') # THEN template = app.synth().get_stack_by_name('Stack').template functions = [resource for resource in template[...
import sys import io import shlex from behave import given, then, fixture, use_fixture import abaqus2dyna import abaqus2dyna.__main__ class CmdlineFixture: def __init__(self): self.code = None self.args = None def run(self, argv): try: self.args = abaqus2dyna.__main__.cmd...
class SurfaceElementProjectionZ(Enum,IComparable,IFormattable,IConvertible): """ Presets for given Analytical Projection Z. enum SurfaceElementProjectionZ,values: BottomOrExterior (2),CenterOfCore (3),CenterOfElement (1),Plane (4),TopOrInterior (0) """ def __eq__(self,*args): """ x.__eq__(y) <==> x==y...
import logging import treefiles as tf class Table: def __init__( self, header=None, rows=None, orient: str = "r", head_sep: [None, str] = "-", col_pad: str = " ", col_sep: str = " ", ): self.header = header self.rows = [] if rows is None...
#!/usr/bin/env python from Tkinter import * import os import sys from libxml2 import thrDefDefaultBufferSize import rospy import Queue import threading #from listener import getState from baxter_collaboration_msgs.msg import WOZ root = Tk() states = [0,0,0,0] dance = StringVar() wave = StringVar() giggle = StringVa...
import torch import sys import colorama colorama.init() from colorama import Fore from ._ModelSaver import save_model def respond_exeption(model: torch.nn.Module): print(Fore.CYAN + "\n* Ctrl-Cによる終了コマンドが入力されました。") print(Fore.CYAN + "* 現時点で学習済みモデルを保存しますか?") print(Fore.CYAN + "* [ Yes: (Y/y), No: (N/n) ] >...
from django.conf.urls import patterns, url from .views import HomeView urlpatterns = patterns('', # by rfc url(r'^(?P<rfc>[A-Z]{4}[0-9]{6}[A-Z0-9]{3})/$', HomeView.as_view()), )
#!/usr/bin/env python # coding=utf-8 """ Provide FileList Class """ import os import argparse class FileList(): """ class: provide file(eg.images,videos) list management """ cur_idx = 0 file_cnt = 0 def __init__(self, folder, search_type="NotRecursive", supported_file_suffix=None): self.file_dirname = folde...
# flake8: noqa: F401 from .threads_manager import RunningTestThreadsManager from .prepare_for_running import prepare_for_running
# -*- coding: iso-8859-1 -*- # Maintainer: joaander import hoomd; import hoomd.md; from hoomd import * hoomd.context.initialize() import unittest import os import tempfile import numpy # unit tests for analyze.log class analyze_log_tests (unittest.TestCase): def setUp(self): init.create_lattice(lattice.sc...
from urllib.request import urlopen, HTTPError, URLError from bs4 import BeautifulSoup as bs # Extract content import pickle # save file from chardet.universaldetector import UniversalDetector import re # 编码格式识别 def Detection_coding_format(html): detector = UniversalDetector() for line in html: ...
import os import json import jsonpickle from git_upm_publisher.utils import discover from git_upm_publisher.utils.package_json_obj import PackageJsonObj class PackageManager: def __init__(self, package_root_path: str): if not os.path.exists(package_root_path): print("Warning: Package root does...
from world import World class Client(object): def __init__(self, model_step): self.id = None self.keys = {'w': False, 'a': False, 's': False, 'd': False} self.model_step = model_step self.world = None def connect(self): raise NotImplementedError() def send(self, m...
from PIL import Image, ImageEnhance, ImageFilter import numpy as np def ImprovedSecondDerivativeEdgeDetection(target: Image.Image): width, height = target.size blur_radius = int((min(width, height) * 0.05) if (min(width, height) * 0.05) > 0 else (min(width, height) * 0.1)) copy = target.filter(ImageFilter....
# __main__.py import sys if sys.version_info[0] < 3 or sys.version_info[1] < 10: print ('Python version 3.10 or later is needed. Please consider upgrading') sys.exit(1) from fluke_28x_dmm_util import dmm_util def cli(): """Call the utility""" dmm_util.main() if __name__ == "__main__": cli()
import threading import gi import os gi.require_version("Gtk", "3.0") # noqa: E402 from gi.repository import Gtk, Gdk, GLib class DialogLogin(Gtk.Dialog): def __init__(self, parent, access): Gtk.Dialog.__init__(self, title="{}: {}".format(_("Server"), access.server["server_na...
from enum import Enum from typing import Optional from fastapi import APIRouter, Depends from pydantic import BaseModel from api import acapy_utils as au from api.tenant_security import ( oauth2_scheme, ) router = APIRouter() class ConnectionProtocolType(str, Enum): Connections = "connections/1.0" DID...
#------------------------------------------------------------------------------ # JupyterQtConsoleApp(JupyterApp,JupyterConsoleApp) configuration #------------------------------------------------------------------------------ ## Whether to display a banner upon starting the QtConsole. c.JupyterQtConsoleApp.display_ban...
from rest_framework import serializers, validators from django.contrib.auth.models import User from .models import Profile class UserSerializer(serializers.ModelSerializer): # notes = serializers.StringRelatedField(many=True) email = serializers.EmailField( validators=[ val...
''' Zhenyu's experiment: Is motion adaptation speed-dependent? Use like this: >>> from slab.experiments import motion_speed >>> motion_speed.main_experiment('subject01') ''' import time import functools import numpy import scipy import slab # configuration slab.Signal.set_default_samplerate(44100) _speaker_positions ...
#加载路径 save_path 上的model和tokenizer #加载test_publiv.csv进行预测,输出文件为lstm_crf_baseline2-final.csv import time import datetime import pandas as pd from tqdm import tqdm import numpy as np import random import torch import matplotlib.pyplot as plt from torch.nn.utils import clip_grad_norm_ from torch.utils.data import TensorDa...
#!/usr/bin/env python from aiida.engine import WorkChain, if_ from aiida.orm import Bool, Float, Str, Dict, StructureData, KpointsData from aiida_twinpy.common.structure import get_shear_structures from aiida_twinpy.common.utils import collect_relax_results from aiida_twinpy.common.builder import get_calcjob_builder f...
""" dummy init file """ from .v_log import VLogger
import errno import os import shutil import sys import tempfile import warnings try: # Python 3 from unittest.mock import patch except ImportError: # Python 2 from mock import patch import nose.tools as nt from testpath import modified_env, assert_isdir, assert_isfile fr...
# 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, software # distributed under th...
#!/usr/bin/python # Takes a set of hitlists and merges them depending on the options. import sys import string import re import codecs import argparse import math from operator import itemgetter import datetime def main(): # Parse command line arguments parser = argparse.ArgumentParser(usage=__doc__, ...
import os import h5py from scipy import io from glob import glob import tables import h5py dataset_dir = '/Users/noel/Projects/DeepLearning/Dataset/ADE20K/ADE20K_2016_07_26' mat = os.path.join(dataset_dir, 'index_ade20k.mat') training_set_dir = os.path.join(dataset_dir, 'training') val_set_dir = os.path.join(dataset_...
from setuptools import setup setup(name='covid19wikiscrape', version='0.1', description='Scrape Covid19 data from Wikipedia', url='http://github.com/jhellerstein/covid19wikiscrape', author='Joe Hellerstein', author_email='hellerstein@berkeley.edu', license='Unlicense', package...
def problem342(): pass
from machine import Pin, freq import neopixel import utime import uos freq(160000000) PIXEL_WIDTH = const(8) PIXEL_HEIGHT = const(8) MAX_BRIGHT = const(2) pixels = neopixel.NeoPixel(Pin(13, Pin.OUT), PIXEL_WIDTH*PIXEL_HEIGHT) def conway_step(): global board global color_board new_board = board[:] changed = ...
DEBUGGING_R = False FIXED_SPECIES = ["H2O", "H+", "O2(g)", "water", "Cl-", "e-", "OH-", "O2", "H2O(g)"] import os import re import sys import shutil import copy import collections import dill import math from urllib.request import urlopen import warnings import subprocess import pkg_resources import pandas as pd imp...
# Print out realtime audio volume as ascii bars import sounddevice as sd import numpy as np from makersign import LedSign import pygame from colour import Color pygame.init() screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) width, height = pygame.display.get_surface().get_size() pygame.display.set_caption...
from transformers.models.auto.tokenization_auto import tokenizer_class_from_name from openprompt.plms.utils import TokenizerWrapper from typing import List, Dict from collections import defaultdict class MLMTokenizerWrapper(TokenizerWrapper): add_input_keys = ['input_ids', 'attention_mask', 'token_type_ids'] ...
from reformat_gherkin.ast_node import GherkinDocument from reformat_gherkin.formatter import LineGenerator from reformat_gherkin.options import AlignmentMode def format_ast(ast, alignment_mode=AlignmentMode.LEFT): line_generator = LineGenerator(ast, alignment_mode) lines = line_generator.generate() return...
import sys from .store_emergency_service_data_in_database import * from main_project.Logs.service_logs import emergency_service_log from datetime import datetime, timedelta import copy import json class FetchEmergencyServiceApi: def __init__(self): self.logger = emergency_service_log() self.pd = p...
from setuptools import setup setup( name = 'geoplot', packages = ['geoplot'], # this must be the same as the name above install_requires=['matplotlib', 'seaborn', 'pandas', 'geopandas', 'cartopy'], py_modules=['geoplot', 'crs', 'utils', 'quad'], version = '0.2.0', description = 'High-level geosp...
# THIS FILE IS SAFE TO EDIT. It will not be overwritten when rerunning go-raml. import os from flask import request, redirect, jsonify, flash from ..flask_itsyouonline import requires_auth import json as JSON import jsonschema from jsonschema import Draft4Validator from ..models import Farmer, Location from .reverse_...
from random import randint from time import sleep import meny meny.set_default_frontend("simple") @meny.title("FizzBuzz!") def fizzbuzz(): for i in range(21): stringy = "" fizz = i % 3 == 0 buzz = i % 5 == 0 if fizz: stringy = stringy + "Fizz" if buzz: ...
""" Set of functions to write and edit the xml description file in the PARAMETER folder """ import os def write_xmlDescriptionFile(matrixFile): """ -> Write the Backbone of an xml file for the description of each variable found in matrixFile -> xml file have to be fill with other functions. -> TODO : - add...
import config import copy import os import unittest class TestConfig(unittest.TestCase): def test_group_envars(self): evs = { 'SOME_VAR': False, 'INFLUXDB_HOST': 'localhost', 'INFLUXDB_PORT': 123, 'INFLUXDB__USERNAME': 'someuser', } expected_...
import lxml.etree import pygments import pygments.formatters import pygments.lexers import zeit.cms.browser.view import zope.proxy form_template = zope.formlib.namedtemplate.NamedTemplateImplementation( zope.app.pagetemplate.ViewPageTemplateFile('xml.edit-contents.pt'), zope.formlib.interfaces.IPageForm) cla...
# Copyright 2014 Cisco Systems, Inc. All rights reserved. # # 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 requir...
# Copyright (c) 2019 Jannika Lossner # # 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 limitation the rights # to use, copy, modify, merge, publish, dis...
from flask import Blueprint, redirect, render_template, request, url_for, session from App.models import db, User, Grade, Student, Role, Permission from utils.ch_login import is_login user_blueprint = Blueprint('user', __name__) @user_blueprint.route('/create_db/') def create_db(): """ 创建数据 """ db.c...
"""A test class for testing the class CodeElement.""" from typing import List, Union from concepttordf import Concept from datacatalogtordf import URI import pytest from pytest_mock import MockFixture from rdflib import Graph from skolemizer.testutils import skolemization, SkolemUtils from modelldcatnotordf.modelldca...
import sys from scrapy.crawler import CrawlerProcess from scrapx.utils.project import get_project_settings # debug or not DEBUG = False # just crawl newly published data INCREMENT = False # project name BOT_NAME = 'test1' # crawler info CRAWLER_INFO = { 'uid': '3e6d0d5b-e0d0-446e-991f-ad1004d0f590', 'desc...
# Standard Library import inspect import os from collections import defaultdict # Import from local from .dist_helper import MASTER_RANK, get_local_rank, get_rank, get_world_size class Environment(object): """A namespace that used to transfer variables across modules """ def __init__(self): self...
from .exception import QuandlException from .nse import NSE __author__ = 'Kiron Krishnankutty <kironnk@gmail.com>' __version__ = '1.0'
from pyV2DL3.eventdisplay.util import getGTI from pyV2DL3.eventdisplay.util import getRunQuality import numpy as np def test_getRunQuality(): vpm_messages = [ "(VPM) data from database for telescope 1", "(VPM) data from database for telescope 2", "(VPM) data from database for telescope 3",...
# -*- coding: utf-8 -*- """ Utility functions for multidimensional scaling. R must be installed, and the Python package ``rpy2`` must be installed, e.g.:: $ apt-get install r-base $ pip install rpy2 See also the examples at: - http://nbviewer.ipython.org/github/alimanfoo/anhima/blob/master/examples/mds.ipyn...
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright 2011-2019, Nigel Small # # 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 # # Unle...
import copy import argparse from collections import namedtuple, OrderedDict import torch import numpy as np import matplotlib.pyplot as plt from formula import * from utils import revert_onehot, similarity_index, pixel_similarity_index, inspection_accuracy PLURAL_KEYS = ['dices', 'jacs', 'pdices', 'pjacs', 'gsensis'...
#!/usr/bin/env python # -*- coding: utf-8 -*- # FSRobo-R Package BSDL # --------- # Copyright (C) 2019 FUJISOFT. All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # 1. Redistributions of source code...
history = data.history mainWindow = browser.activeWindow() mainWindow.addTab() links = "" sorted_history = sorted(history.items(), key=lambda x: (x[1]["last_visited"] if "last_visited" in x[1].keys() else 0), reverse=True) for item in sorted_history: links += "\n <a href='%s'>%s</a> (%s)<br>" % (QUrl.fromUse...
import turtle import random INSTANT = False COLOR = 0 MAXCOLOR = 16777215 if INSTANT: turtle.tracer(0, 0) turtle.speed(0) turtle.hideturtle() turtle.penup() turtle.backward(200) turtle.right(90) turtle.forward(200) turtle.left(90) turtle.pendown() def triangle(l, n): global COLOR if n == 0: tur...
# SPDX-License-Identifier: Apache-2.0 import numpy as np # type: ignore import onnx from onnx.defs import ONNX_DOMAIN, AI_ONNX_PREVIEW_TRAINING_DOMAIN from ..base import Base from . import expect class Gradient(Base): @staticmethod def export_gradient_scalar_add() -> None: add_node = onnx.helper.m...
import torch.nn as nn from modules.rnn import LSTM from model.biaffine_model import BiaffineScorer from modules.layers import Embeddings, CharCNNEmbedding from modules.BertModel_fixed import BertEmbedding from modules.dropout import * class NERParser(nn.Module): def __init__(self, num_wds, num_chars, num_tags, ...
# @String input_analysis # @String image_dir # @String cell_parameters # @String outlines # @Integer height # @Integer width # @String filenames # @String outputfiles # @String outlinefiles from ij import IJ, ImagePlus from ij.plugin import ImageCalculator cell = open("{}_parameters.txt".format(cell_parameters), 'r')...
# Copyright (c) nexB Inc. and others. All rights reserved. # http://nexb.com and https://github.com/nexB/vulnerablecode/ # The VulnerableCode software is licensed under the Apache License version 2.0. # Data generated with VulnerableCode require an acknowledgment. # # You may not use this software except in compliance ...
#!/usr/local/bin/python # -*- coding: utf-8 -*- import ldap import ldap.modlist as modlist import sys import argparse import constantes_admin def search(dn, filtre): """ Search in the ResEl LDAP with the given parameters >>> search('ou=machines,dc=resel,dc=enst-bretagne,dc=fr', '(Zone=User)') """ try: try: ...
# -*- coding: utf-8 -*- """ A base configuration that loads settings from environment variables and sets appropriate defaults for all configuration variables used in the application. """ from typing import Iterable from typing import Optional from os import environ from os import path # noinspection PyPacka...
import numpy as np import scipy.io as scio def text_save(filename, data):#filename为写入CSV文件的路径,data为要写入数据列表. file = open(filename,'w') l = len(data) data = sorted(data) for i in data: s = str(i).replace('[','').replace(']','')#去除[],这两行按数据不同,可以选择 s = s.replace("'",'').replace(',','') +'\n...
import numpy as np import os import h5py as h5 from ...utils import torch_utils as tu from ...utils.train_utils import Frequency from ...utils.exceptions import assert_, FrequencyValueError, NotUnwrappableError from ...utils import python_utils as pyu from .base import Callback import gc class NaNDetector(Callback): ...
"""rio-tiler types.""" from typing import Dict, Sequence, Tuple, Union import numpy NumType = Union[float, int] BBox = Tuple[float, float, float, float] NoData = Union[float, int, str] Indexes = Union[Sequence[int], int] DataMaskType = Tuple[numpy.ndarray, numpy.ndarray] ColorTuple = Tuple[int, int, int, int] # ...
import datetime import logging import logging.config import logging.handlers import os import re import sys from functools import wraps from typing import Any, Callable, Dict, FrozenSet, List, Optional, Pattern, Tuple import gevent import structlog LOG_BLACKLIST: Dict[Pattern, str] = { re.compile(r"\b(access_?tok...
# Description # 中文 # English # Given a positive integer, return its corresponding column title as appear in an Excel sheet. # 1 -> A # 2 -> B # 3 -> C # ... # 26 -> Z # 27 -> AA # 28 -> AB # Have you met this question in a real interview? # Example # Example1 # Input: 28 # Output: "AB" # Example2 # Input: 29 # O...
import os import sys import shutil import subprocess from python_helpers import open_utf8 excluded_objects = ['utf8proc_data.cpp'] def get_libraries(binary_dir, libraries, extensions): result_libs = [] def find_library_recursive(search_dir, potential_libnames): flist = os.listdir(search_dir) f...
#!/usr/bin/env impala-python # Copyright (c) 2015, Cloudera, inc. # Confidential Cloudera Information: Covered by NDA. # 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/...
from .plugin_config import Plugin_Config from .plugin_db import Plugin_DB class Plugin_Utils(): """ A wrapper for core functions for a plugin to have access to. """ def __init__(self, config, logger, db, versions, plugin_name, plugin_manifest, modname, path): self.config = Plugin_Config(con...
# encoding: utf-8 ################################################## # This script shows how to create animated plots using matplotlib and a basic dataset # Multiple tutorials inspired the current design but they mostly came from: # https://towardsdatascience.com/animations-with-matplotlib-d96375c5442c # Data uses the...
import time import torch import torch.distributed as dist import torch.nn.functional as F import random from utils import AverageMeter, calculate_accuracy, write_to_batch_logger, write_to_epoch_logger def train_epoch(epoch, data_loader, model, criterion, ...
import os KEY_DIR = 'server/keys/' RSA_PUBLIC_KEY = os.path.join(KEY_DIR, 'public.pem') RSA_PRIVATE_KEY = os.path.join(KEY_DIR, 'private.key') if not os.path.exists(KEY_DIR): os.mkdir(KEY_DIR)
"""empty message Revision ID: bbba4c4eb15 Revises: 5a190aa4623b Create Date: 2015-11-12 10:43:07.973540 """ # revision identifiers, used by Alembic. revision = 'bbba4c4eb15' down_revision = '5a190aa4623b' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - pl...