text
stringlengths
3.07k
12.6k
#!/usr/bin/env python # -*- coding: utf-8 -*- import collections import numpy as np import sympy as sp import time import dh import jacobian import inverse_kinematics import utils pwm = utils.import_pwm() class Planner(object): ''' This class selects actions for the manipulator This is extremely limite...
import time from gsmHat import GSMHat, SMS, GPS import threading gsm = GSMHat('/dev/ttyS0', 115200) gsm.ColData() backToMainMenu = False def get_input(): data = input() # Something akin to this if data == 'q' or data == 'exit': global backToMainMenu backToMainMenu = True return data d...
import sagemaker from PIL import Image import requests from io import BytesIO import os import json import numpy as np import xmltodict from tqdm import tqdm import pandas as pd from argparse import ArgumentParser def main(name): predictor = sagemaker.predictor.RealTimePredictor('faster-rcnn-ep') # predictor ...
from unittest import mock from unittest.mock import MagicMock from core.models import Book, Category from django.http import HttpRequest from django.test.testcases import TestCase from django.urls import reverse from import_export import admin, formats, forms, mixins class ExportViewMixinTest(TestCase): class T...
# Copyright (c) ZenML GmbH 2021. 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: # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
from typing import List, Optional from allennlp.common import Registrable, Params from allennlp.nn.beam_search import BeamSearch, Sampler from dataclasses import asdict, dataclass, replace from iconary.data.datasets import IconaryIcon, IconaryGame from iconary.utils.utils import load_json_object @dataclass class Be...
from src.utils import softmax from collections import defaultdict import numpy as np import torch import torch.nn as nn def create_ground_truth(users, items): """ Creates a dictionary, where the keys are user ids and the values are item ids that the user actually bought. """ ground_truth_arr = np.stac...
from __future__ import print_function from ply import lex, yacc reserved_list = [ 'begin', 'end', 'parameters', 'molecule_types', 'species', 'reaction_rules', 'observables', ] reserved = dict((r, r.upper()) for r in reserved_list) tokens = [ 'ID', 'FLOAT', 'INTEGER', ...
import click import pytest from click_params.domain import ( DOMAIN, PUBLIC_URL, URL, EMAIL, SLUG, DomainListParamType, PublicUrlListParamType, UrlListParamType, EmailListParamType, SlugListParamType ) from tests.helpers import assert_in_output, assert_equals_output @pytest.mark.parametrize(('name', 'paramet...
#!/usr/bin/env python # Kobo Patch GUI Copyright (c) 2015 <NAME> # # This software is provided under the MIT license. Please see LICENSE.txt for details from __future__ import absolute_import, division, print_function, unicode_literals from PatchEdit import * try: from tkinter import * from tkinter import t...
""" Copyright (c) 2020 <NAME> 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, sublic...
import numpy as np import cv2 import os import json import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from scipy.stats import bernoulli from sklearn.utils import shuffle DATA_PATH = '/home/timo/Documents/mldata/car_sim_video_images/training_dataB/' DRIVING_LOG_FI...
#!/usr/bin/python # Copyright (c) 2020, 2022 Oracle and/or its affiliates. # This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 # See LICENSE.TXT for d...
import logging from django.apps import apps from django.conf import settings from django.contrib.auth import get_user_model from django.core.files import File from django.db import OperationalError from django.utils.encoding import force_text from mayan.celery import app from mayan.apps.lock_manager.backends.base im...
''' written by <NAME> ''' import numpy as np import tensorflow as tf import time import sys from dataLoader import loadData import os seed = int(time.time()) np.random.seed(seed) # load data tr, vr = loadData('./ml-100k/ratings.dat', delimiter=',', seed=seed, transpose=True, valfrac=0.1) tm = np.g...
#!/usr/bin/env python3 import csv import os import sys from typing import Dict, List from adafruit_pca9685 import PCA9685 import board import busio from tabulate import tabulate NUMBER_OF_BUTTONS = 8 * 2 PWM_OFF = 0x0000 # 0% duty cycle PWM_ON = 0xFFFF # 100% duty cycle LightsConfiguration = Dict[str, Dict[str, L...
import utils from exceptions import FieldException import methods __all__ = ('FieldException', 'StoreField' 'ReferenceField', 'DojoDateField') class StoreField(object): """ The base StoreField from which all ```StoreField```s derive """ def __init__(self, model_field=None, store_field=None, g...
import bs4 import sys import urllib.request, urllib.error, urllib.parse import http.client from socket import error as SocketError import ssl import os.path import argparse import datetime import pickle import signal import http.cookiejar import re import json import random from multiprocessing import Pool from multi...
import logging import copy import numpy as np import utils import torch from torch import nn import torch.nn.functional as F from nao_encoder import Encoder from nao_decoder import Decoder class NAODataset(torch.utils.data.Dataset): def __init__(self, inputs, targets=None, train=True, sos_id=0, eos_id=0): ...
import sys from pathlib import Path import scipy import numpy as np import pandas as pd from scipy import ndimage from scipy.signal import find_peaks from copy import deepcopy import math from bokeh.layouts import layout, row, column, gridplot, widgetbox from bokeh.plotting import figure, show from bokeh.io import ou...
import os from tqdm import tqdm import torch from torch.utils.data import DataLoader from frames_dataset import PairedDataset from logger import Logger, Visualizer import imageio from scipy.spatial import ConvexHull import numpy as np def normalize_kp(kp_source, kp_driving, kp_driving_initial, adapt_movement_scale=...
from commonsbot import mysql from commonsbot.utils import get_nomination_page from pprint import pprint, pformat from datetime import datetime import pywikibot import mwparserfromhell import sys def split(l, n): """ Splits a list into several lists of given size @param l: List to split @type l: list ...
"""The ICSI Meeting Corpus.""" import os import json import datalabs from datalabs import get_task, TaskType # the following package are needed when more additional features are expected to be calculated from featurize.summarization import ( get_features_sample_level, get_schema_of_sample_level_features, )...
import warnings from typing import Collection, Any, Optional import torch import torch.nn as nn import torch.nn.functional as F ArgStar = Collection[Any] def dropout_mask(x, sz, dropout): """ Applies a dropout mask whose size is determined by passed argument 'sz'. Args: x (torch.Tensor): A torch Var...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json from . import * _DATAVIZ_SESSION = None _DATAVIZ_CSRF_TOKEN = None _DATAVIZ_USER = 'admin' def _get_api_url(): return get_url_scheme() + '://viz.cdsw.{}.nip.io/arc'.format(get_public_ip()) def _api_call(func, path, data=None, files=None, headers=None):...
import os from sys import exit as x from datetime import datetime import cv2 import numpy as np import printj from annotation_utils.coco.structs import COCO_Category_Handler, COCO_Dataset from annotation_utils.ndds.structs import NDDS_Dataset from logger import logger # dataset.display_preview(show_details=True) # im...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import argparse import contextlib import multiprocessing import os import sys from typing ...
import glob import json import os import re import string from collections import Counter from scrape import Song import pandas as pd from nltk import ngrams from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from nltk.tokenize import word_tokenize from textblob import TextBlob def tf_idf(art...
import os import shutil import hashlib import numpy as np import cv2 from keras.preprocessing.text import Tokenizer from keras.preprocessing.image import ImageDataGenerator from keras.preprocessing.sequence import pad_sequences from keras.utils import to_categorical from PIL import Image VOCAB = ", { } small...
# Copyright 2016 Google 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 required by applicable law or agreed ...
import enoki as ek import pytest def get_class(name): """Resolve a package+class name into the corresponding type""" if 'cuda' in name: if not ek.has_cuda(): pytest.skip('CUDA mode is unsupported') elif 'llvm' in name: if not ek.has_llvm(): pytest.skip('LLVM mode is ...
#!/usr/bin/env python3 import logging import os import re import shutil import tarfile import unicodedata from contextlib import closing from typing import Any, Optional from zipfile import ZipFile import mkdocs from dirtools2.dirtools2 import Dir from mkdocs.plugins import BasePlugin logger = logging.getLogger(__nam...
import numpy as np from collections import defaultdict from enum import Enum from multiprocessing import cpu_count from psutil import virtual_memory import GPUtil import logging import datetime import math log = logging.getLogger('scanner') log.setLevel(logging.INFO) log.propagate = False if not log.handlers: cla...
from datetime import date, timedelta from django.contrib.auth.mixins import LoginRequiredMixin from django.core.files import File from django.db.models import Min, Sum from django.http import HttpResponseRedirect from django.urls import reverse from django.utils.text import slugify from django.utils.timezone import now...
from __future__ import print_function import argparse import torch import torch.utils.data from torch import nn, optim from torch.nn import functional as F from torchvision import datasets, transforms from torchvision.utils import save_image parser = argparse.ArgumentParser(description='VAE MNIST Example') parser.add...
from __future__ import division import os import argparse import torch import codecs import glob from nltk.tokenize import word_tokenize import torch.distributed as dist import torch.multiprocessing as mp import table import table.IO import opts from multiprocessing import Pool,Manager from functools import partial p...
from __future__ import print_function, absolute_import import scrapy import re import logging from collections import deque from scrapy.http import HtmlResponse from scrapy.utils.misc import load_object from scrapy.exceptions import NotSupported from scrapy.utils.decorators import inthread from twisted.internet import ...
import logging import os import util as u from config import Config def register(): return { 'render_mode_hybrid_forecasts': make_hybrid_forecast } def make_hybrid_forecast(webmaker, dest_key, work_item, list_args): try: Config.log("dest_key = '%s'" % dest_key, tag='HYBRID_FORECAST_START...
import math import numpy as np from ply import lex, yacc import sympy from astropy import units as u from astropy.units import imperial as imp import state import importer import solver import funcs def string_to_unit(s): for module in [u, imp]: if hasattr(module, s) and isinstance(getattr(module, s), u...
import inspect from importlib import import_module from espider.request import Request from heapq import heappop, heappush try: import cPickle as pickle # PY2 except ImportError: import pickle class PriorityQueue(object): def __init__(self): self._queue = [] self.index = 0 async def...
import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.model_zoo as model_zoo __all__ = ['Inception2', 'inception_v2'] def inception_v2(pretrained=False, **kwargs): r"""Inception v2 model architecture from `"Rethinking the Inception Architecture for Computer Vision" <http://arx...
# -*- coding: utf-8 -*- """ Created on Tue Oct 8 12:20:41 2019 @author: Mike """ import numpy as np import matplotlib.pyplot as plt from keras.datasets import cifar10 from keras.utils import np_utils from keras import backend as K # In *older* versions of Tensorflow/Keras you may need to adjust the image # dimensi...
# -*- coding: utf-8 -*- import os import shlex import numpy as np from pytools import prefork from collections import defaultdict from pyfr.mpiutil import get_comm_rank_root from pyfr.writers.native import NativeWriter def init_csv(cfg, cfgsect, header, *, filekey='file', headerkey='header'): # Determine the f...
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging from telemetry.core import util from telemetry.core.backends.chrome import inspector_timeline_data from telemetry.core.backends.chrome import ...
import pandas as pd import numpy as np from optparse import OptionParser from pytrends.request import TrendReq from itertools import combinations from string import ascii_lowercase import time from collections import Counter import random import plotly.graph_objects as go import plotly.express as px def interactive_pl...
import torch import numpy as np from tqdm import tqdm import torch.nn as nn import matplotlib.pyplot as plt from torch.utils.data import DataLoader @torch.no_grad() def test(hn, hf, dataset, chunk_size=10, img_index=0, nb_bins=192, H=400, W=400): ray_origins = dataset[img_index * H * W: (img_index + 1) * H * W, :...
# Copyright (c) 2018-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # import numpy as np import torch from common.common_pytorch.utils import wrap from common.transformation.quaternion import qrot...
#!/usr/bin/env python """ Show original SMLM images overlaid with localization data. Data is rendered in napari. To run the script:: locan check <pixel size> -f <images file> -l <localization file> -t <file type> Try for instance:: locan check 133 -f "locan/tests/test_data/images.tif" -l "locan/tests/test_...
import math import torch import torch.nn as nn def get_freq_indices(method): assert method in ['top1','top2','top4','top8','top16','top32', 'bot1','bot2','bot4','bot8','bot16','bot32', 'low1','low2','low4','low8','low16','low32'] num_freq = int(method[3:]) if 'to...
#! /usr/bin/python # -*-coding: UTF-8 -*- import os import inspect from airtest.core.cv import Template as TemplateBase, loop_find as loop_find_core, try_log_screen from airtest.utils.transform import TargetPos from airtest.core.settings import Settings as ST # noqa from airtest.aircv.template_matching import Templat...
# Copyright (c) 2021 Massachusetts Institute of Technology # SPDX-License-Identifier: MIT import inspect from collections import Counter from dataclasses import dataclass, is_dataclass from itertools import zip_longest import hypothesis.strategies as st import pytest from hypothesis import assume, given from omegacon...
is_torchvision_installed = True try: import torchvision except: is_torchvision_installed = False import torch import torch.nn.functional as F import torch.utils.data import random import numpy as np from torch.utils.data.sampler import BatchSampler device = torch.device('cuda' if torch.cuda.is_available() el...
import os import json import pathlib import hashlib import errno import shutil import subprocess rol = lambda val, r_bits, max_bits: \ (val << r_bits%max_bits) & (2**max_bits-1) | \ ((val & (2**max_bits-1)) >> (max_bits-(r_bits%max_bits))) ror = lambda val, r_bits, max_bits: \ ((val & (2**max_bits-1)) >>...
from manim_imports_ext import * class TrigRepresentationsScene(Scene): CONFIG = { "unit_length" : 1.5, "arc_radius" : 0.5, "axes_color" : WHITE, "circle_color" : RED, "theta_color" : YELLOW, "theta_height" : 0.3, "theta_value" : np.pi/5, "x_line_col...
import numpy as np import pandas as pd import gc import random from sklearn.metrics import roc_auc_score from sklearn.model_selection import train_test_split import torch import torch.nn as nn import torch.nn.utils.rnn as rnn_utils from torch.autograd import Variable from torch.utils.data import Dataset, DataLoader imp...
# coding: utf-8 #import networkx as nx #import matplotlib.pyplot as plt #import operator #from collections import defaultdict #from collections import Counter #from collections import deque # from functools import reduce # from math import log import copy import operator import re import sys import time from itertools ...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch import torch.nn as nn from torch.nn import functional as F import numpy as np import numpy.random as npr from maskrcnn_benchmark.layers import smooth_l1_loss, Label_Smoothing_Regression from maskrcnn_benchmark.modeling.box_coder impor...
# -*- coding: utf-8 -*- #Figure 17.1 has no code import pylab #Figure 15.8 (repeated) def variance(X): """Assumes that X is a list of numbers. Returns the standard deviation of X""" mean = sum(X)/len(X) tot = 0.0 for x in X: tot += (x - mean)**2 return tot/len(X) def stdDev(X)...
from typing import List, Optional, NamedTuple import argparse import sys import re import keyword import sqlalchemy from sqlalchemy.engine.base import Engine from sqlalchemy.schema import MetaData, Table, Column from sqlalchemy.sql import sqltypes def main(): args = init_argument_parser().parse_args() execut...
import json import logging import os import string from tqdm import tqdm logger = logging.getLogger(__name__) def read_mrp_json_file(dataset_filename): """Read mrp formatted json file""" mrp_jsons = [] with open(dataset_filename) as rf: for line in rf: mrp_json = json.loads(line.stri...
import os import re import json import logging from typing import List from datetime import datetime from uuid import uuid4 from botocore import xform_name from . import s3_object, sqs logger = logging.getLogger() def get_input_uri_key(stage): return f"{xform_name(stage).upper()}_INPUT_URI" def get_output_ur...
""" Adapted from sphinx.ext.purpose https://github.com/sphinx-doc/sphinx/blob/master/sphinx/ext/purpose.py Allow purposes to be inserted into your documentation. Inclusion of purposes can be switched of by a configuration variable. The purposelist directive collects all purposes of your project...
# # Script to process lines in a text file # and output them to a CSV file suitable # for importing with import-tweets.py. # # Each line is assumed to contain a single tweet. # This is then scheduled according to the values # passed to the script. # # The output format is: # # date,tweet_text # # Version: 1.0 # impor...
"""Serialise and Deserialise to and from tf records.""" # Copyright 2019 CSIRO (Data61) # # 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 # # ...
# # Copyright (c) 2021 Czech Technical University in Prague. # # This file is part of Roadmaptools # (see https://github.com/aicenter/roadmap-processing). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free So...
#!/usr/bin/env python3 # Copyright 2022 Xiaomi Corporation (Author: <NAME>) # # See ../../../../LICENSE for clarification regarding multiple 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 Licen...
# Copyright 2019 Huawei Technologies Co., Ltd # # 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...
# -*- coding: utf-8 -*- """ Vigenère cipher encryption/decryption toolkit Author: <NAME> Allows working with non-Latin alphabets """ class CryptoAlphabet(object): """ A class that represents a particular alphabet. (E.g. Latin, Cyrillic) """ _alphabet = "" _alphaSize = 0 _letter_index = {} ...
from matplotlib import pyplot as plt import numpy as np from .stats import ci def plot_ci_graph(y, x, y_err_series=None, x_err_series=None, colors=None, shapes=None, labels=None, line=False, markersize=15, fill=True, grid=True, legend=True, legendloc='center', ...
# -*- coding: utf-8 -*- import sys import os import math import random import numpy as np from point import Point from sklearn import datasets from sklearn.cluster import KMeans from sklearn.cross_validation import train_test_split from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import matp...
# RSA Cipher # http://inventwithpython.com/hacking (BSD Licensed) import sys # IMPORTANT: The block size MUST be less than or equal to the key size! # (Note: The block size is in bytes, the key size is in bits. There # are 8 bits in 1 byte.) DEFAULT_BLOCK_SIZE = 128 # 128 bytes BYTE_SIZE = 256 # One byte has 256 diff...
# Copyright (c) 2021, ByteDance Inc. All rights reserved. # !/usr/bin/python from __future__ import print_function import logging import os import subprocess import sys import threading from deepspeed.utils import log_dist from megatron import mpu class PropagatingThread(threading.Thread): """ propagate excep...
import json from datetime import datetime from threading import Thread, Event from typing import List, Union from mongoengine import OperationError from src.contracts.ethereum.multisig_wallet import MultisigWallet from src.db.collections.commands import Commands from src.db.collections.eth_swap import Swap, Status fr...
""" Name: FissionsAdd breif: Adding fission particles to phase vectors for MCDC-TNT Author: <NAME> (OR State Univ - <EMAIL>) CEMeNT Date: Nov 18th 2021 """ import numpy as np def FissionsAdd(p_pos_x, p_pos_y, p_pos_z, p_mesh_cell, p_dir_y, p_dir_z, p_dir_x, p_speed, p_time, p_alive, fis_count, nu_new_n...
# Third-party import astropy.units as u import astropy.coordinates as coord from astropy.coordinates import (frame_transform_graph, CoordinateAttribute, FunctionTransform, AffineTransform, ICRS) from astropy.coordinates.matrix_utilities import (rotation_matrix, ...
import discord import re import urllib.parse as urlparse import clashroyale import brawlstats creditIcon = "https://i.imgur.com/TP8GXZb.png" credits = "Bot by GR8 | Titan" class friendlink: """Automatically convert Clash Royale and Brawl Stars friend links to beautiful embeds""" def __init__(self, bot): ...
import os from conans.model.ref import ConanFileReference, PackageReference from conans.util.files import load, relative_dirs, path_exists from os.path import isfile from os.path import join, normpath from conans.model.manifest import FileTreeManifest EXPORT_FOLDER = "export" SRC_FOLDER = "source" BUILD_FOLDER = "bui...
#!/usr/bin/python # Rescale .xbb file values for epub formatting. # ---------------------------------------------------------------------------- # LaTeX eBook utility tools # ----------------------------------------------------------------------------- # <NAME> - https://github.com/jfogarty - <EMAIL> # ----------------...
"""Module using IndRNNCell to solve the addition problem The addition problem is stated in https://arxiv.org/abs/1803.04831. The hyper-parameters are taken from that paper as well. The network should converge to a MSE around zero after 1500-20000 steps, depending on the number of time steps. """ import tensorflow as t...
import atexit import os import signal from collections import defaultdict from contextlib import asynccontextmanager from datetime import datetime from tempfile import NamedTemporaryFile from time import monotonic from typing import Optional import boto3 from aiohttp import web from . import executor, kernel from .no...
#!/usr/bin/env python3 # vim: set fileencoding=utf-8 tabstop=4 shiftwidth=4 softtabstop=4: import functools, itertools, operator import sys, os, os.path import fileinput, glob import string, re import decimal import argparse from gw2_item_recipes import * from gw2_spidy import * # # program code # def currency_to_...
# Create your views here. # from django.contrib.gis.maps import google import StringIO import xlsxwriter # import pandas from models import EarthQuake from django.db.models import Q from django.db import connection from django.http import HttpResponse from django.utils.translation import ugettext from django.utils.dat...
#!/usr/bin/python # coding: UTF-8 from serial import * from sys import stdout, stdin, stderr, exit from flask import Flask, render_template, request, redirect, url_for, jsonify # シリアルポートはls -l /dev/tty.* # 自身の名称を app という名前でインスタンス化する app = Flask(__name__) ser = None tocostick = '/dev/tty.usbserial-AHXMLYXU' # 前進時の推力一覧...
import os import subprocess import sys import mock import py import pytest import virtualenv # Template for creating setup.py for installing console scripts. SETUP_TEMPLATE = """ import setuptools setuptools.setup( name='{script_name}', version='1.0', py_modules=['{script_name}'], zip_safe=False, ...
# -*- coding: utf-8 -*- # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ This file contains components with some default boilerplate logic user may need in training / testing. They will not work for everyone, but many users may find them useful. The behavior of functions/classes in this file...
# Copyright (C) 2019 Bloomberg LP # # 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 writi...
#------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. #-------------------------------------------------------------------------- import os i...
""" Package to init views """ import os import datetime from flask import Flask from flask_sessionstore import SqlAlchemySessionInterface from flask_compress import Compress from flask_caching import Cache from flask_mail import Mail from flask_sqlalchemy import SQLAlchemy import logging from logging.config import dict...
"""The Proxy class module.""" from __future__ import annotations import asyncio import logging import socket import uuid from abc import ABC, abstractmethod from dataclasses import dataclass from typing import List from opentrons.hardware_control.emulation.settings import ProxySettings log = logging.getLogger(__name_...
# from astropy.nddata.ccddata import _uncertainty_unit_equivalent_to_parent import pytest import time from muler.hpf import HPFSpectrum, HPFSpectrumList from specutils import Spectrum1D # from astropy.nddata.nduncertainty import StdDevUncertainty import numpy as np import glob import astropy local_files = glob.glob("...
""" Created on Tue 27 Mar 2018 by PavitrakumarPC Modified on Wed 13 Nov 2019 by AlessandroSaviolo """ import cv2 import os import pandas as pd import h5py import os import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Rectangle from PIL import Image from random import randint def images_...
from cloudify.decorators import operation from cloudify.amqp_client import get_client from cloudify.models_states import AgentState from cloudify import ctx, utils as cloudify_utils from cloudify.exceptions import (CommandExecutionError, CommandExecutionException) from cloudify.agent_ut...
# # voice-skill-sdk # # (C) 2020, Deutsche Telekom AG # # This file is distributed under the terms of the MIT license. # For details see the file LICENSE in the top directory. # # import io import os import sys import json import shutil import pathlib import tempfile import unittest import subprocess from unittest.mock...
import numpy as np import tensorflow as tf def softmax_weighted_loss(): def compute_loss(gt, y_pred): n_dims=y_pred.shape[-1] loss = 0. ############################################# # gt = produce_mask_background( gt, y_pred) # gt = tf.stop_gradient( gt ) #########...
""" Implementation of "Attention is All You Need" """ import torch import torch.nn as nn from onmt.encoders.encoder import EncoderBase from onmt.modules import MultiHeadedAttention from onmt.modules.position_ffn import PositionwiseFeedForward from onmt.utils.misc import sequence_mask class TransformerEnc...
# Copyright (c) 2021 <NAME> <<EMAIL>> # This file is part of the "cgitize" project. # For details, see https://github.com/egor-tensin/cgitize. # Distributed under the MIT License. import os import tomli from cgitize.bitbucket import Bitbucket from cgitize.github import GitHub from cgitize.gitlab import GitLab from c...
import hashlib import json from time import time from uuid import uuid4 from urllib.parse import urlparse from flask import Flask, jsonify, request class BlockChain(object): def __init__(self): self.chain = [] self.current_transactions = [] self.nodes = set() # first block in ch...
# -*- coding: UTF-8 -*- """This module contains functions for validating user input""" import re import ipaddress def supplied_config_values_are_valid(int_netmask, int_ip_low, int_ip_high, ext_netmask, ext_ip_low, ext_ip_high, gateway, cluster_name, ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import sys import geocoder from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.signals import user_logged_in from django.db.models import ForeignKey from djadmin import settings from .mixins import Dj...
""" Containerize Functionality to deploy existing hacksport compatible challenges within a docker container. Intended to serve as a compatibility layer to "lift" legacy challenges into a fully isolated environment like DockerChallenge. This is intended as a replacement for the existing deploy functionality. For examp...