text
stringlengths
3.07k
12.6k
import numpy as np # Plotting import matplotlib.pyplot as plt from matplotlib.colors import LogNorm ##### # Plot a time series data set ##### def plot_series(series, n_steps, y=None, y_pred=None, x_label="$t$", y_label="$x(t)$"): plt.plot(series, ".-") if y is not None: plt.plot(n_steps, y,...
import os import numpy as np import pandas as pd import datetime import matplotlib.pyplot as plt from fpdf import FPDF ########## Defining functions and classes ########## def aggregate_data(data_list, filepath, column): '''Takes a list containing csvs, a filepath to the folder containing the csvs and a column...
from evaluation.EvaluatorBase import EvaluatorBase, get_transform from torch.autograd import Variable import numpy as np import torch from torch.nn import functional as F from evaluation.face_recognition.model import create_model import os import glob from PIL import Image class ResultsLabeledDataset(torch.utils.data....
# Metronome - <NAME> (Kwistech) from tkinter import * from winsound import Beep class Metronome: """Create Metronome app with class instance.""" def __init__(self, root): """Initiate default values for class and call interface(). Args: root (tkinter.Tk): Main class instance for t...
""" OpenVZ services -- asynchronous objects that exchange data to/from the device """ import collections from enum import Enum class IncompletePacket(IOError): """ Exception used if we attempt to parse a packet that's insufficiently long to parse. """ pass class InappropriatePacket(IOError): """ Except...
# coding: utf-8 import numpy as np import json import datetime import sys import boto3 from Reversi import choice_random, Reversi from Reversi import DualNet, ChoiceReplaySteps, choice_primitive_monte_carlo, ChoiceMonteCarloTreeSearch, ChoiceSupervisedLearningPolicyNetwork, ChoiceAsynchronousPolicyAndValueMonteCarloT...
# Copyright 2019 Xanadu Quantum Technologies Inc. # 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 agre...
# A script to copy positions using Interactive Brokers because SierrChart does # not support adaptive market orders import asyncio import json import logging import typing as t import datetime as dt from asyncio.tasks import ensure_future from contextlib import suppress import click from ib_insync import ContFuture, ...
from nltk import word_tokenize import string from nltk.stem import SnowballStemmer from tqdm import tqdm """ This file used to generate baseline paraphrases from ppdb. """ PPDB_DB = "./rep_ppdb/ppdb-2.0-tldr" ############ THIS IS THE NLTK-BASED PARAPHRASE GENERATOR !!!! ########## def add_to_dict_of_set(key, value, ...
""" idea: spawn in waves. everyone saves up food from the plant until a certain time at which everyone spawns soldiers as fast as possible. Triggered by an attack. Everyone set their spawn requirement according to the distance to the attack so that the spawn will all reach the spot at the same time. idea: use avg pos...
from xml.dom import minidom from xml.etree.ElementTree import Element, SubElement, Comment, tostring from xml.etree import ElementTree import os from parser import Parser from formatter import * import sys class XMLMaker: """Class to construct the XML file. Note: this class makes it much easier to debug/test ...
# Read position from gulp outfile import numpy as np import pandas as pd def read_index(OUTfile,k_number,Atomic_number=240): with open(OUTfile,'r') as out: # print(out.read()) for index, line in enumerate(out,1): if 'Final fractional' in line: print(line,index) i = index if 'Final Cartesian lattice...
from datetime import ( datetime, timedelta ) from http import HTTPStatus from flask import request from flask_restful import Resource from pymongo import MongoClient from backend.clients.sbb_client import SBBClient from backend.clients.swisscom_client import SwisscomClient class PingView(Resource): def...
import os import re import threading import urllib.parse as urlparse import xbmc import xbmcvfs from contextlib import closing from libs import mediainfo as info, mediatypes, pykodi, quickjson from libs.addonsettings import settings from libs.pykodi import localize as L, log from libs.webhelper import Getter, GetterEr...
from psdaq.configdb.typed_json import cdict import psdaq.configdb.configdb as cdb import pyrogue import pyrogue.interfaces.simulation import epix100a_gen2 import ePixFpga as fpga import numpy as np import sys import IPython import argparse import re mem = pyrogue.interfaces.simulation.MemEmulate() class EpixBoard(pyr...
import tensorflow as tf import src.settings as settings ''' refer to: https://github.com/wenxinxu/resnet-in-tensorflow/blob/master/resnet.py ''' def activation_summary(x): tensor_name = x.op.name tf.summary.histogram(tensor_name + '/activations', x) tf.summary.scalar(tensor_name + '/sparsity', tf.nn.zero_...
# BSD 2-CLAUSE LICENSE # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # Redistributions i...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import uuid import shutil import zipfile import logging import subprocess from hashlib import md5 from pathlib import Path import rarfile from ezsub import const from ezsub.utils import to_screen from ezsub.errors import ( EmptyArchiveError, BadCompressedFileErr...
from rdkit import Chem import pandas as pd #========================================================== # validate SMILES def molStructVerify(compounds, getFailedStruct=False, getFailedStructIdx=False, printlogs=True): #-----------------------...
''' Data aggregation facilities. ''' import threading as th import queue import multiprocessing as mp from .module_exceptions import ConfigurationError from .util import FactoryBase from .guns.base import Sample from .util import q_to_dict import asyncio import time from dateutil import tz import numpy as np import pa...
from utils.database import dbutils import json import requests import polyline import cPickle as pickle import os def get_routes(location_pairs, routes_path, get_time=False): """ Gets the driving route from Open Street Routing Machine for an array of pairs of coordinates. Decodes the returned polyline rou...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
from vision.ssd.data_preprocessing import PredictionTransform from vision.ssd.vgg_ssd import create_vgg_ssd, create_vgg_ssd_predictor from vision.ssd.mobilenetv1_ssd import create_mobilenetv1_ssd, create_mobilenetv1_ssd_predictor from vision.ssd.mobilenetv1_ssd_lite import create_mobilenetv1_ssd_lite, create_mobilenetv...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2021, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function from ansible.module_utils.basic import AnsibleModule, env_fallback from ansib...
# ------------------------------------------------------------------------------ # BSD 2-Clause License # # Copyright (c) 2019-2020, <NAME> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following condi...
from django.core.validators import MinValueValidator, MaxValueValidator from django.db import models from django.utils import timezone from django.utils.translation import pgettext_lazy from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel from wagtail.admin.edit_handlers import F...
import torch import torch.nn as nn import onmt.utils import programmingalpha import logging import numpy as np import math from copy import deepcopy from .BertGen import OnmtBertEncoder, buildBert from .RoBertaGen import OnmtRobertaEncoder, buildRoberta from .XLNetGen import OnmtXLNetEncoder, buildXLNet ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # @date Dec 13 2015 # @brief # import sys import threading import logging from logging.handlers import ( TimedRotatingFileHandler, SocketHandler, DatagramHandler, SysLogHandler, SMTPHandler, HTTPHandler, ) from logging import LoggerAdapter t...
import mistune import re import os import time ROOT_MD_DIR = '../docs/' ROOT_IMG_DIR = ROOT_MD_DIR + 'figures/' ROOT_TEX_DIR = './chaps/' # LaTeXRenderer class LaTeXRenderer(mistune.HTMLRenderer): NAME = 'latex' IS_TREE = False def __init__(self, is_book_or_report=True): self._is_book_or_repor...
import tensorflow as tf import numpy as np import random import csv import cv2 import json import h5py from sklearn.utils import shuffle from sklearn.model_selection import train_test_split from keras.layers import Activation, Dense, Dropout, ELU, Flatten, Input, Lambda from keras.layers.convolutional import Convolut...
#!/usr/bin/env python3 # <xbar.title>Jackpot</xbar.title> # <xbar.version>v1.1</xbar.version> # <xbar.author>Marcos</xbar.author> # <xbar.author.github>astrowonk</xbar.author.github> # <xbar.desc>Displays current Mega Millions and Powerball jackpots.</xbar.desc> # <xbar.dependencies>python</xbar.dependencies> # <xbar....
import aiohttp import asyncio import sys from aiohttp import web from collections import defaultdict, Counter import datetime as dt from src.db_analysis_functions import count_date_status_function, count_date_status_format, \ count_approval_history_function, get_form_date, get_form, get_old_status from src.db_inter...
from collections import namedtuple, deque import rx from rxx.types import NamedObservable, Update, Updated from rxx.internal.trampoline import Trampoline from rx.disposable import CompositeDisposable, SingleAssignmentDisposable class Source(object): def __init__(self, on_back): self.buffer = deque() ...
import logging import sys import numpy as np import matplotlib.pyplot as plt def load_file(filename): """ Carrega o dataset para a memória :param filename: nome do arquivo :return: matriz x e y """ x_input = [] y_input = [] f = open("data/" + filename + ".txt") lines = f.r...
import datetime import argparse import torch import random import numpy as np from configs.config import MyConfiguration from BaseTrainer import BaseTrainer from BaseTester import BaseTester from data.dataset import MyDataset from torch.utils.data import DataLoader from models.MyNetworks import ESFNet from v...
""" This is a Tank Game based on PocketTanks, made in Python 3 using Pygame and Pymunk for physics """ from random import randint import sys import pygame import pymunk import pymunk.pygame_util # CLASS AND FUNCTION IMPORTS from ground import Ground from tank import Tank from text import text class PyTanksIO: "...
from queue import Queue import pysc2.agents.myAgent.myAgent_2.macro_operation as macro_operation from absl import app from pysc2.agents import base_agent from pysc2.lib import actions, features from pysc2.env import sc2_env, run_loop import pysc2.agents.myAgent.myAgent_2.smart_actions as sa import pysc2.agents.myAgen...
import json from threading import Thread import os import logging import sys import shutil import copy from PyQt5.QtWidgets import QWidget, QPushButton, QApplication, QLabel, QMainWindow, QSizePolicy, QGraphicsDropShadowEffect, QProgressBar from PyQt5.QtCore import QCoreApplication, QTimer, pyqtSlot from PyQt5.QtGui i...
from PIL import Image, ImageCms def rgb2lab(image): RGB_p = ImageCms.createProfile('sRGB') LAB_p = ImageCms.createProfile('LAB') return ImageCms.profileToProfile(image, RGB_p, LAB_p, outputMode='LAB') def lab2rgb(image): RGB_p = ImageCms.createProfile('sRGB') LAB_p = ImageCms.createProfile('LAB'...
import collections import os import numpy as np from torch import Tensor import librosa from torch.utils.data import Dataset ___author__ = "<NAME>" __email__ = "<EMAIL>" def genSpoof_list(dir_meta, is_train=False, is_eval=False): d_meta = {} file_list = [] with open(dir_meta, 'r') as f: ...
import sys from six.moves.collections_abc import Iterable from functools import partial from promise import Promise, is_thenable from ...error import GraphQLError, GraphQLLocatedError from ...type import (GraphQLEnumType, GraphQLInterfaceType, GraphQLList, GraphQLNonNull, GraphQLObjectType, Graph...
import os from random import shuffle import datetime import json import tensorflow as tf import pandas as pd import click from tensorflow.python.keras.metrics import AUC from src.models.models import get_model from src.models.loss import loss_with_fl, dice_coe_metric, dice_coe_loss from src.data.drive import (get_dat...
# ****************************************************************************** # Copyright 2017-2018 Intel 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.apa...
# -------------- # import libraries import numpy as np import pandas as pd import re # Load data data = pd.read_csv(path, parse_dates = [0], infer_datetime_format = True) # Sort headlines by date of publish data.sort_values(by=['publish_date'], axis=0, ascending=True, inplace = True) # Retain only alphabets data['h...
import tkinter from tkinter import * questions = [ "1.Depressed mood most of the day, nearly every day", "2.Markedly diminished interest or pleasure in all, or almost all, activities most of the day, nearly every day.", "3.Significant weight loss when not dieting or weight gain, or decrease or increa...
import pandas as pd import sys from common import * import configparser,json,os import glob as glob import ntpath import pandas as pd def read_protodata(folder_name,mdd=0): fields=['amp_fac','server_id'] folder_dir=folder_name+'query/*/*' folders=glob.glob(folder_dir) eachfile=folders[0] if mdd==1...
import discord import os import requests import json from keep_alive import keep_alive client = discord.Client() dog_words = ["puppy", "pup", "dog", "woofer", "woof", "bork", "borker", "good boy", "good girl", ":dog:"] dog_breeds = [ 'affenpinscher', 'african', 'airedale', 'akita', 'appenzeller', 'austr...
import math, sys from lux.game import Game from lux.game_map import Cell, RESOURCE_TYPES from lux.constants import Constants from lux.game_constants import GAME_CONSTANTS from lux import annotate DIRECTIONS = Constants.DIRECTIONS game_state = None def getSurroundingTiles(pos,range): directions = ["NORTH", "SOUTH",...
# -*- coding: utf-8 -*- """""" import colorsys import pathlib import numpy as np from ruamel.yaml import YAML def unpack(compressed: np.ndarray): assert compressed.ndim == 1 uncompressed = np.zeros(compressed.shape[0] * 8, dtype=np.bool) for b in range(8): uncompressed[b::8] = compressed >> (7 - b...
import skew from collections import namedtuple import argparse skew_tuple = namedtuple("skew_tuple", "skew_resource instances_filters cluster_count instance_type " "reserved_filters reserved_count reserved_type dimensions") skew_dict = { 'rds' : skew_tuple( 'db',{'DBInstanceStatus':'avail...
""" author: Prabhu """ ''' *******A convolutional neuralnet********** convolution: Convolution is the first filter applied as part of the feature engineering step. An application of a filter to a image. We pass over a mini image, usually called a kernel and outputting the filtered subset of our image. ...
""" This file contains api resources for interacting with the tutor as users take the course. """ import time from flask_restful import abort, reqparse from edx_adapt.api.resources.base_resource import BaseResource from edx_adapt.data.interface import DataException from edx_adapt import logger from edx_adapt.select.i...
from handsome.MicropolygonMesh import MicropolygonMesh, Position from handsome.Pixel import FloatPixel, array_view, pixel_view from handsome.Tile import Tile from handsome.TileCache import TileCache from handsome.capi import fill_micropolygon_mesh, generate_numpy_begin from handsome.util import save_array_as_image, poi...
from datetime import datetime import threading from flask import Flask, request, jsonify import os import sys import numpy as np import json import cv2 from maskrcnn_benchmark.config import cfg from maskrcnn_benchmark.data import make_data_loader from maskrcnn_benchmark.structures.bounding_box import BoxList from pre...
# -*- coding: utf-8 -*- import itertools import time import matplotlib.pyplot as plt import numpy as np import scipy.stats as sc_stats def get_bps(modulation): if modulation.upper() in ['BPSK']: return 1 else: raise Exception(f"Unknown modulation {modulation}") def get_fec_matrix(name): ...
from typing import List, Iterator, Dict from typing_extensions import Literal from itertools import groupby from pathlib import Path import datetime import bson import numpy as np from pymatgen import Structure from pymatgen.analysis.structure_matcher import StructureMatcher, ElementComparator from monty.serializatio...
#!/usr/bin/python3 # Standard libraries. import os import sys import collections chromiumPath = "" if os.path.exists("/usr/bin/chromium"): chromiumPath = "/usr/bin/chromium" elif os.path.exists("/usr/bin/chromium-browser"): chromiumPath = "/usr/bin/chromium-browser" # Reads the given file, returns the entire...
import math import numpy as np from numba import jit, cuda import srfnef as nef def change_id(id1,id2): index = np.where(id1<id2)[0] maxs = id2[index] id2[index] = id1[index] id1[index] = maxs return id1.reshape(-1,1),id2.reshape(-1,1) @jit(nopython = True) def cal_sinogram(list_mode_data, tot...
from __future__ import absolute_import from __future__ import division from builtins import zip from builtins import object import pandas as pd import numpy as np import json import matplotlib.pyplot as plt from .. import plot def json_eci_to_pandas(jsoneci): """Go through an eci.json file and extract all the...
import _ailib class CostFunction(): SQUARED_ERROR = 0 CROSSENTROPY = 1 class neuralnetwork(): def __init__(self, filepath=""): if filepath == "": self.net = _ailib.neuralnetwork_init() else: self.net = _ailib.neuralnetwork_init_fromfile(filepath) def __del__(self): _a...
#!/usr/bin/env python import json import sys import gzip import pdb def write_dataset(dataset, output_file): with gzip.open(output_file, 'wt') as fout: json.dump(dataset.to_dict(), fout, indent=2) def read_dataset(input_file): with gzip.open(input_file, 'rt') as fin: dataset = Dataset() ...
import matplotlib from matplotlib import pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D from matplotlib.patches import FancyArrowPatch from mpl_toolkits.mplot3d import proj3d from mpl_toolkits.axes_grid1 import make_axes_locatable matplotlib.rcParams['mathtext.fontset'] = 'cm' matplotlib.rcP...
#!/usr/bin/env python # coding: utf-8 # # Copyright 2016 The Fontbakery Authors # Copyright 2017 The Google Font Tools 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://ww...
#!/usr/bin/env python3 # Copyright (c) 2014-2018 <NAME> # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # RPC test for basic name registration and access (name_show, name_history). from test_framework.names import NameTestFra...
#!/usr/bin/env python3 import sys import tempfile def chunks(x, n): return [x[i:i+n] for i in range(0, len(x), n)] COLORS = [ # "alice blue", # "aquamarine", # "azure", # "beige", # "bisque", # "black", # "blanched almond", "blue", "blue violet", "brown", "burlywood",...
import numpy as np import os os.environ["CUDA_VISIBLE_DEVICES"] = "1" os.environ[ 'XLA_FLAGS'] = '--xla_gpu_cuda_data_dir=/usr/local/cuda' from absl import app from absl import flags import matplotlib.pyplot as plt import tensorflow as tf import pickle import jax import jax.numpy as jnp import jax_cosmo as jc impo...
import torch from torch.autograd import Variable as var import torch.nn.functional as F import numpy as np def Gaussian2D(x, mu, sigma, rho): factor = 1.0 / (2 * np.pi * sigma[0] * sigma[1] * torch.sqrt(1 - rho**2)) norm_x = (x - mu)/sigma Z = torch.sum(norm_x**2) - 2 * rho * norm_x[0] * norm_x[1] val = factor * t...
# -*- coding: utf-8 -*- """ Javelin Web2Py Default Controller """ from applications.javelin.ctr_data import ctr_enabled, get_ctr_data from gluon.tools import Service service = Service(globals()) @auth.requires_login() @auth.requires_membership('standard') def index(): """ example action using the internationaliza...
#!/usr/bin/env python # coding: utf-8 # Script for running example BSEP inhibition classification models against user-provided data. import sys import os import pandas as pd import numpy as np from sklearn import metrics import argparse from atomsci.ddm.pipeline import model_pipeline as mp from atomsci.ddm.pipeline ...
import unittest from lxml import etree from lxml.etree import XPathSyntaxError from pyxmlmapper import base from pyxmlmapper.components.exceptions import NotFoundException from pyxmlmapper.components.fields import XmlField xml = """ <PurchaseOrder PurchaseOrderNumber="99503" OrderDate="1999-10-20" EmptyDate=""> <...
# -*- coding: utf-8 -*- """Views to run a survey by the instructor. This module implements three views: - run_survey_ss: Display the rows available for the survey and allow for links to run each row individually - run_survey_row: Run the survey as instructor for a single row """ from typing import List, Optional...
# https://www.deeplearningwizard.com/deep_learning/deep_reinforcement_learning_pytorch/dynamic_programming_frozenlake/ # -*- coding: utf-8 -*- import gym import numpy as np import matplotlib.pyplot as plt import random np.set_printoptions(precision=3) np.set_printoptions(suppress=True) # Environment # Slippery envir...
""" Fixed-Point GAN adapted from Siddiquee et al. (2019) """ from dataclasses import dataclass import torch import torch.autograd from torch import Tensor, nn from util.dataclasses import DataclassExtensions, DataShape from util.pytorch_utils import relativistic_loss from models.abstract_model import Abstr...
"""General utilities.""" import collections.abc import re import shutil import subprocess from copy import deepcopy from functools import partial from os import cpu_count from pathlib import Path from haddock import log from haddock.core.exceptions import SetupError check_subprocess = partial( subprocess.run, ...
import os import sys import fire import time import torch import torchplus base_path = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, base_path) sys.path.append(os.path.join(base_path, 'third_party/second.pytorch')) MAJOR_VERSION = 1 MINOR_VERSION = 0 from tqdm import tqdm from tensorboardX import Sum...
from random import randint import math, time from tkinter import messagebox import tkinter as tk class Application(tk.Frame): def __init__(self, master=None): super().__init__(master) master.wm_title("Find Shortest Path") self.circleSize = 4 master.resizable(width=False, height=Fals...
"""Intermediate variable preprocessor for PyBryt submissions""" import ast import astunparse import nbformat from IPython.core.inputtransformer2 import TransformerManager from .abstract_preprocessor import AbstractPreprocessor from ..utils import make_secret class UnassignedVarWrapper(ast.NodeTransformer): ""...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Unit tests for the icompression module """ __author__ = "<NAME> <<EMAIL>>" __date__ = "6/4/2020" import unittest import tempfile import subprocess import glob import os import sys import numpy as np import shutil import test_all from enb.config import get_options opt...
# -*- encoding: utf-8 -*- import os import sys import argparse from tqdm import tqdm if os.path.abspath('..') not in sys.path: sys.path.insert(0, os.path.abspath('..')) from Evaluate.evaluate_openKBP import * from model import * from NetworkTrainer.network_trainer import * def read_data(patient_dir)...
import os import time import json import random import threading import re import urllib.request from datetime import datetime import praw import yaml from prawcore import NotFound class OgreBot(threading.Thread): __config = dict() __dictionary = dict() __error_dictionary = dict() __header_dictionary...
import tkinter as tk from tkinter import ttk import ttkthemes as tkT from lib import sharelib from PIL import ImageTk import time import datetime ac_name = sharelib.connnection_popup() chain_proxy = sharelib.def_credentials(ac_name) file_uploading_proxy = sharelib.def_credentials(ac_name, mode="fileuploading") roo...
import numpy as np from models import Policy, ValueFunction def one_step_actor_critic(mdp, value_function_alpha, policy_alpha, iterations, episodes, max_actions, final_performance_episodes): #print("One Step actor critic with mdp: " + mdp.name) actions_vs_episodes_all = np.zeros((iterations, episodes)) f...
""" @Author: Lzy @Time: 2022/03/09 @Description: 排序问题 """ import functools from typing import List from heapq import * def min_number(nums: List[int]) -> str: """ Offer 45. 把数组排成最小的数 核心思想:自定义排序规则 x + y < y + x; 则 x 应该放在 y 的左边,即 x 比 y 小 :param nums: :return: """ def quick_sort(left: in...
''' unit tests for Ansible module: na_ontap_vscan_on_demand_task ''' from __future__ import (absolute_import, division, print_function) __metaclass__ = type import json import pytest from ansible_collections.netapp.ontap.tests.unit.compat import unittest from ansible_collections.netapp.ontap.tests.unit.compat.mock im...
import config as conf import os import sys import numpy as np from copy import deepcopy import fnmatch import basic_plot_functions import var_utils as vu import h5py as h5 ''' Directory structure and file names for ctest (or cycling experiments): test/ ├── Data/ │   ├── sondes_obs_2018041500_m.nc4 (or sondes_obs_201...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ TODO """ from numpy import arctan2, cos, digitize, linspace, log10, sin, sum, sqrt, zeros from pandas import DataFrame from .angle import Angle from .catalog import SourceCatalog, HaloCatalog from .distance import Distance from .lensing import bmo_f, bmo_g, delta_c ...
import time from gettext import gettext as _ from string import Template from django.core.exceptions import ValidationError, ObjectDoesNotExist from django.core.urlresolvers import reverse from django.db.models import Q, F from django.db import models from cyder.base.mixins import ObjectUrlMixin, DisplayMixin from cy...
"""pytest unit tests for vibrationtesting""" import numpy as np import vibrationtesting as vt import numpy.testing as nt import scipy.io as sio def test_sos_modal_forsparse(): mat_contents=sio.loadmat('vibrationtesting/data/WingBeamforMAC.mat') # WFEM generated .mat file K = (mat_contents['K']) M = (mat_contents['...
#Chapter 3 - Building interactive apps with Bokeh #----------------------------------------------------------------------------------------------------# #Using the current document # Perform necessary imports from bokeh.io import curdoc from bokeh.plotting import figure # Create a new plot: plot plot = figure() #...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os import logging import smtplib from email.mime.text import MIMEText import types import re import yaml import markdown logger = logging.getLogger('emaillib') logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.INFO) PROVIDERS_...
#!/usr/bin/env python # coding: utf-8 # In[97]: # Task 1 # In[98]: class Goose: def __init__(self, name, weight): self.name = name self.weight = weight def feed(self, food): self.weight += food def collect_eggs(self, quantity): self.weight -= quantit...
import os # Working with operation system environment import shutil # Directories processing import sys # Pass launch arguments import ctypes # Dialogue messages import datetime from getpass import getuser import re # Regular expressions (folder name mask) def main(argv): ...
import json from collections import defaultdict from pathlib import Path import albumentations as A import numpy as np import pandas as pd import torch from easydict import EasyDict from rasterio.features import rasterize from shapely.geometry import Polygon from skimage import io from sklearn.model_selection import t...
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ * UMSE Antivirus Agent Example * Author: <NAME> <<EMAIL>[at]gmail[dot]com> * Module: UMSE Decryption Tools * Description: This module allows to decrypt UMSE file entries. * * Copyright (c) 2019-2020. The UMSE Authors. All Rights Reserved. * Redistributi...
from typing import List, Tuple, NamedTuple import io import shutil import pathlib import pkg_resources from rawtypes.generator.cpp_writer import to_c_function, to_c_method from rawtypes.generator.py_writer import to_ctypes_iter, write_pyi_function, write_pyi_struct from ..parser.header import Header from ..parser impor...
from os import path import pynvim from pynvim import Nvim from astropy.io import fits from typing import List, Union Number = Union[int, float] @pynvim.plugin class FitsOpen: def __init__(self, nvim: Nvim): self.nvim = nvim @pynvim.function("FITSInfo", sync=True) def fits_info(self, args): ...
""" Copyright (C) 2019 NVIDIA Corporation. All rights reserved. Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode). """ import argparse import numpy as np import matplotlib.pyplot as plt LINE_COLORS = plt.rcParams['axes.prop_cycle'].by_key()['color'] LINE_STYLES...
"""Encoder Description: This module encodes Planning Problem into Constraint Satisfaction Problem License: Copyright 2021 <NAME> 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...
import random import matplotlib.pyplot as plt # TO-D0 Make a Plot with Bicubic and SRCNN PSNR Evaluation Values with each Epoch def evaluation_plot(): epoch_eval1 = { 'psnr_srcnn': [], 'psnr_bicubic': [], 'ssim_srcnn': [], 'ssim_bicubic': [] } # Extracting SSIM and PSNR S...
r""" Basis Pursuit (BP) solvers tackle the original :math:`P_0` problem :eq:`p0_approx` by posing L1-relaxation on the norm of unknown :math:`\vec{x}`. .. autosummary:: :toctree: toctree/relaxation/ basis_pursuit_linprog basis_pursuit_admm """ import numpy as np from scipy.linalg import solve_triangular f...