text
stringlengths
3.07k
12.6k
import typed_ast.ast3 as ast import util.error as err import typesys.mytypes as mytypes from libbase.libfuncs import * def get_func_info(func_name, module_names): if module_names: main = module_names[0] sub = module_names[1:] if len(module_names) > 1 else [] info = module_to_info(main, sub...
from itertools import combinations import numpy as np from torch.autograd import Variable import torch as th import torch.nn as nn import torch.nn.functional as F from components.transforms import _check_inputs_validity, _to_batch, _from_batch, _adim, _bsdim, _tdim, _vdim, _check_nan from models.basic import RNN as Re...
import datetime from django.db import models from django.contrib.auth.models import User from django.conf import settings from tagging.fields import TagField from markdown import markdown class Category(models.Model): title = models.CharField(max_length=250, help_text='Maximum 250 characters.') description...
from keras.callbacks import ReduceLROnPlateau#, LearningRateScheduler from keras.layers import (Input, Conv2D, BatchNormalization, ZeroPadding2D, Dropout, GlobalAveragePooling2D, Activation, Dense, add) from keras.models import Model from keras import optimizers from keras import regularizers ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import torch from torch.jit import script, trace import torch.nn as nn from torch import optim import torch.nn.functional as F import csv import random import re import o...
import requests import os import pandas as pd from flask import Flask, render_template, request, redirect #from bokeh.plotting import figure #from bokeh.embed import components from spotipy.oauth2 import SpotifyClientCredentials import spotipy import dill import spotipy.util as util import spotipy.oauth2 as oauth2 imp...
import abc import matplotlib.patches as patches import numpy as np class IllustratorElement(abc.ABC): """base class for optical illustrator elements""" mode_plot_kwargs = {'color':'k', 'solid_capstyle':'round'} width = 1 @abc.abstractmethod def draw(self, ax): ...
# -*- coding: utf-8 -*- """ A module for decoding "Actions" additional PSD data format. """ from __future__ import absolute_import, unicode_literals import collections from psd_tools.utils import read_unicode_string, read_fmt from psd_tools.constants import OSType, ReferenceOSType, UnitFloatType Descriptor = collect...
import ast import re import numpy as np import pandas as pd def isnull(x): """ Return boolean indicating whether a value is null. """ if pd.isnull(x): return True elif str(x).lower() in ['nan', 'none', 'null', 'n/a']: return True else: return False def map_on_off(x): ...
from functools import wraps, partial, reduce import numpy as np import torch import torch.optim from torch.autograd import grad import utils.distributions as my_dists from .probabilistc_model import ProbabilisticModel def normalize_per_dimension(prob_model, dims, func, name): if dims == 'all': dims = r...
from django.db.models import query from django.db.models.fields import Field from django.db.models.query import QuerySet from django.shortcuts import render, redirect from django.forms import inlineformset_factory from django.contrib import messages from django.contrib.auth import authenticate, login, logout from djan...
# -*- coding: utf-8 -*- """ Created on Fri Dec 28 21:40:15 2018 @author: dylan """ import numpy as np import matplotlib.pyplot as plt import math as m from mpl_toolkits.mplot3d import axes3d MAGCONFIGR=[ [1, 0, 0], [2, 0, 0], [-1, 0, 0], [-2, 0, 0], [0, 1, 0], [0, 2, 0], [0,-1, 0], [...
from tqdm import tqdm import matplotlib.pyplot as plt from functools import partial import numpy as np import tensorflow_probability as tfp from tensorflow_probability.python.internal import nest_util from tensorflow_probability import bijectors as tfb import tensorflow as tf from tensorflow_probability.python.vi impo...
from .mixins import * from .types import * from .decorators import * import json def build_param_message(missing_params): return "The following parameters were missing: {0}".format(", ".join(missing_params)) def build_param_type_message(invalid_params): return "The following parameters were of the wrong type: {0}"....
import json import os from unittest import TestCase, skip, expectedFailure import Gui.jumpcutterGui as J_gui # constants PROJECT_ROOT = os.path.normpath(os.path.join(__file__, '..', '..')) DOWNLOAD_FOLDER = r"C:\Users\frank\Downloads" GUI_FOLDER = os.path.join(PROJECT_ROOT, "Gui") SETTINGS_FILE = os.path.join(GUI_F...
# Copyright (c) 2015. Mount Sinai School of Medicine # # 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 o...
#!/usr/bin/env python3 import os import subprocess import sys from Bio import SeqIO from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord from simplesam import Reader #========================================================================================================== # COMMANDS LIST TRINITY = 'Trinity ...
# -*- coding: utf-8 -*- from __future__ import absolute_import import json import logging import sys from time import sleep from Crypto.Hash import SHA256 from cached_property import cached_property from standardjson import StandardJSONEncoder import requests from six import string_types if not logging.getLogger()....
""" copyright <NAME> 11/08/2021 """ class Solution: def findMedianSortedArrays(self, nums1: list[int], nums2: list[int]) -> float: """ :rtype: object """ i = 0 j = 0 return_list = [] while i <= (len(nums1) - 1) and j <= (len(nums2) - 1): if num...
import math import torch from torch.optim.lr_scheduler import _LRScheduler, LambdaLR #def get_cosine_with_hard_restarts_schedule_with_warmup( # optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, num_cycles: int = 1, last_epoch: int = -1 #): # """ # Create a schedule with a learning rate tha...
from abc import ABCMeta, abstractmethod from typing import Optional import msal from .. import session from ..auth import microsoft, security, yggdrasil class AuthenticatedUser(metaclass=ABCMeta): def __init__(self, access_token: str, refresh_token: str) -> None: self.__name = None self.__uuid =...
import os import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader, TensorDataset from utilities import printf, ModelCoordinator, main from pums_downloader import download_pums_data, get_pums_data_path, datasets from opendp.network.odometer import...
# author: <NAME> # functionality: extraction, training and validation import dynamic_analysis import utility from time import time import pickle import numpy as np import random classes = [ 'Benign', 'Malware/Backdoor', 'Malware/Trojan', 'Malware/Trojandownloader', 'Malware/Tro...
# -*- coding: utf-8 -*- # # Copyright 2020 AllanKT. # 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 ag...
from django.http import HttpResponse from django.shortcuts import render from store.models import * from django.core.mail import EmailMessage from django.views.decorators.gzip import gzip_page from django.http import StreamingHttpResponse import cv2 import threading import numpy as np @gzip_page def Home(request): ...
# -*- coding: utf-8 -*- import os import sys import warnings from time import time from docopt import docopt import colorful import tagexpressions from . import __VERSION__ from .core import Core from .core import Configuration from .loader import load_modules from .matcher import merge_steps from .stepregistry impo...
"""Store game events in database Usage: munerator [options] store Options: -v --verbose Verbose logging --context-socket url ZMQ socket for conext event [default: tcp://127.0.0.1:9002] --database ip:port Host and port for mongo database [default: 127.0.0.1:27017] --rcon-socket url Z...
#!/usr/bin/env python3 import argparse import sys import os import re import numpy from Bio import Entrez from Bio import SeqIO from vars import COV_DIR, EMAIL # NCBI Taxonomy ids: # 333387: single record for testing # 2697049: Severe acute respiratory syndrome coronavirus 2 # 694009 (parent of 2697049): Severe acute...
''' Created on Aug 20, 2010 @author: joel ''' import numpy def applyweights(wp, vp): from numpy import newaxis wp = wp.reshape(wp.shape + (1,)*(3-len(wp.shape))) if len(vp.shape) == 2: vp = vp[:,:,newaxis] wvp = numpy.sum(wp[:,newaxis] * vp[:,:,newaxis,:], axis=3) # print "applyweights %s, %s, ...
#---------------------------------------------------------------------------------------------------------- # <NAME> # <EMAIL> # May 2016 # v1.1 #---------------------------------------------------------------------------------------------------------- import nuke import operator def AlignNodes(direction): #---...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2018 GoPro Inc. # # 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 #...
import os import sys import platform from ._constants import msg_file_not_found import re # IN: persistent_peers = "xxxx@yyy:dddd" # OUT:persistent_peers = "" # or # IN: persistent_peers = "" # OUT:persistent_peers = "xxxx@yyy:dddd" def replaceKey(keystring,filename,quotechar='"',value=""): fullpath = os.path.re...
""" generic_dynamics.py Implements the `GenericDynamics` object by subclassing the `BaseDynamics` class. Author: <NAME> Date: 7/15/2020 """ from __future__ import absolute_import, division, print_function import time import tensorflow as tf try: import horovod.tensorflow as hvd HAS_HOROVOD = True except Impo...
# positivity_test.py # Original by 솜시좋은장씨 # Editted by <NAME> (전한나), <NAME> (황병호) # positivity_test.py는 긍정/부정 정도 판별 모델을 직접 이용하는 모듈을 모아놓은 파일이다. # Licensed by # https://somjang.tistory.com/entry/Keras%EA%B8%B0%EC%82%AC-%EC%A0%9C%EB%AA%A9%EC%9D%84-%EA%B0%80%EC%A7%80%EA%B3%A0-%EA%B8%8D%EC%A0%95-%EB%B6%80%EC%A0%9...
from collections import OrderedDict from rest_framework import status from drf_yasg.inspectors.base import FieldInspector, NotHandled from drf_yasg import openapi, utils, generators from drf_yasg.inspectors import ( SwaggerAutoSchema, swagger_settings, field as field_insp, CoreAPICompatInspector ) from . import fie...
# Copyright 2020 Google LLC # # 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, ...
import argparse from grid import * from utility.logconfig import * import logging script_dir = os.path.dirname(os.path.realpath(__file__)) class Element(GridItemType): def __init__(self, name, image, factor): GridItemType.__init__(self, name, image) self.factor = factor class Board(Grid): # ...
import numpy as np #simple implementation of a doubly linked list #a doubly linked list has a head and a tail element #elements can be appended and removed from either end of the list class LinkedList: def __init__(self): self.size = 0 self.head = None self.tail = None def add_hea...
import numpy as np from sklearn.decomposition import PCA, IncrementalPCA, TruncatedSVD from scipy.sparse import issparse from scipy.sparse.linalg import LinearOperator, svds from sklearn.utils import check_array , check_random_state from sklearn.utils.extmath import svd_flip import warnings """ The following code is i...
from django.shortcuts import render, redirect from django.conf import settings from rest_framework import viewsets, mixins, status from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.response import Response from rest_framework.decorators import permission_classes, action, api_view impo...
import numpy as np import tqdm import gym class ToyEnv(gym.Env): def __init__(self, problem='4state'): self.action_space = gym.spaces.Discrete(2) self._state = None self._diamond = None self._diamond_2 = None self.fn = {'4state': self._4_state_problem, '5state': self._...
from collections import OrderedDict from typing import Dict import torch from .global_var import config from .block_layer import CheckpointBlock from . import nccl import io, pickle def _save_to_state_dict(model : torch.nn.Module, destination, prefix): if isinstance(model, CheckpointBlock): if config['rank...
import time import datetime from typing import Any, Dict import sqlalchemy from sqlalchemy.sql.expression import text from utils import deserialize from .config import Config class UserNotFoundError(Exception): pass class BindError(Exception): def __init__(self, err_msg: str) -> None: super().__in...
# ex:ts=4:sw=4:sts=4:et # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- """ BitBake 'Event' implementation Classes and functions for manipulating 'events' in the BitBake build tools. """ # Copyright (C) 2003, 2004 <NAME> # # This program is free software; you can redistribute it and/or modify # it u...
import math import os # Solution def part1(data, print_coords=False): grid = create_grid(data) result_sum = 0 for xc in range(len(grid)): for yc in range(len(grid[xc])): if grid[xc][yc] == 0: continue sight = dict() for xt in range(len(grid)): ...
""" :Created: 31 October 2014 :Author: <NAME> """ import abc import inspect import logging import random from .exceptions import InvalidConditionError, UndefinedConditionError __all__ = ["Condition", "CompareCondition"] logger = logging.getLogger("condition") class Condition: """ A condition which evalu...
# Copyright (C) 2016 Hewlett Packard Enterprise Development 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...
'''tf.Graph processor used for training''' from .shell_filter import ShellFilter from .shell_reorder import ShellReorder from .scaler import DataScaler, NormDataScaler from .patcher import Patcher from .reshaper import Reshaper, Joiner from .base import CombineDatasets from .io import load_tfrecord_data class Traini...
from scipy.stats import norm from scipy.linalg import cholesky from .. import main import numpy as np ##### ''' The correlation coefficient for the Nataf transformation is evaluated, following: <NAME>. "Evaluating correlation coefficient for Nataf transformation." Probabilistic Engineering Mechanics 37 (2014): 1-...
# -*- coding: utf-8 -*- """ Created on Tue Nov 16 13:31:34 2021 @author: <NAME> """ import seaborn as sns import streamlit as st import pandas as pd from datetime import timedelta import numpy as np import matplotlib import matplotlib.pyplot as plt import datetime def text_area(label): final_comment.append(label...
import sys from inspect import signature from types import FunctionType from typing import ( TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union, ) from warnings import warn from magicgui import magicgui from napari_plugin_engine import HookImplementation, PluginManager fr...
# Author: <NAME> (<EMAIL>) from typing import List, Type, Union import numpy as np from actor.shape_actor import ShapeActor from observer.event.events import CustomEvent from observer.base_observer import BaseObserver from shape.point_2d import Point2D from shape.polygon_2d import Polygon2D from shape.polyline_2d i...
from django.core.urlresolvers import reverse from django.shortcuts import render_to_response, get_object_or_404 from django.http import HttpResponseRedirect, Http404 from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.contrib.syndication.views import feed f...
import enum from torch.utils.data import Dataset from torch.utils.data._utils.collate import default_collate from typing import Dict, List, Tuple, Union import json from transformers import PreTrainedTokenizer import numpy as np import collections from tqdm import tqdm import re import copy FCInst = collections.name...
#!/usr/bin/env python import unittest import pexpect from robot.version import get_version TIMEOUT_SECONDS = 2 child = None def check_result(pattern): index = child.expect([pattern, pexpect.EOF, pexpect.TIMEOUT], timeout=TIMEOUT_SECONDS) try: assert index == 0 except A...
from exceptions import DeviceTimeoutError from mqtt import MqttMessage, MqttConfigMessage from interruptingcow import timeout from workers.base import BaseWorker import logger import json import time from contextlib import contextmanager import bluepy.btle as btle import argparse import signal import struct import sy...
#!/usr/bin/env python ''' Custom advanced radar controller ================================ ''' import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import matplotlib.animation as animation import sorts from sorts.radar.scans import Fence import sorts eiscat3d = sorts.radars.ei...
from __future__ import annotations import argparse import atexit import itertools import pathlib import shlex import shutil import signal import subprocess import sys import traceback from typing import Dict, List, Optional, Tuple from pyoomph import ast, ast2ir, ast_transformer, c_output, ir, parser python_code_dir...
# Copyright (c) 2017-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. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import itertools import numpy as n...
import os.path import torchvision.transforms as transforms import numpy as np import json import nibabel as nib from data.base_dataset import BaseDataset from configurations import * from util.image_property import hash_file, normalize_image, slice_with_neighborhood def get_domain_code(path): code = np.zeros(5) ...
from hydroDL.data import Dataframe, DataModel from hydroDL import utils from .io import * from .subset import * from . import SMAP class DataframeCsv(Dataframe): def __init__(self, rootDB, *, subset, tRange): super(DataframeCsv, self).__init__() self.rootDB = rootDB self.subset = subset ...
"""Task 3 in project""" import matplotlib.pyplot as plt import numpy as np from numba import njit, prange from tqdm import tqdm A = "TGGAATTCTCGGGTGCCAAGGAACTCCAGTCACACAGTGATCTCGTATGCCGTCTTCTGCTTG" def read_file(filename: str = "..\\data\\s_3_sequence_1M.txt"): with open(filename, "r") as f: return f.r...
import uuid import datetime from django.conf import settings from django.db import models from django.utils import timezone from cwfollowup.utils.jobs.request_file_download_id import request_file_download_id from cwfollowup.utils.jobs.request_file_list import request_file_list from cwfollowup.utils.jobs.request_job_s...
from typing import Optional, Callable, Any, List, Tuple import mdtraj as md import numpy as np from dataclasses import dataclass from .. import log _log = log.getLogger(__name__) @dataclass class CV(object): """ Collective variable class with an id and a generator to convert every frame in a trajectory to ...
from pyspark_proxy.proxy import Proxy __all__ = [ 'DataType', 'IntegerType', 'LongType', 'StringType', 'FloatType', 'DoubleType', 'DecimalType', 'LongType', 'StructType', 'NullType', 'NumericType', 'BinaryType', 'FractionalType', 'DateType', 'TimestampType', 'ByteType', 'ShortType', 'ArrayType', 'Struc...
""" Predict labels with a model. """ import logging import zipfile from os import makedirs, walk from os.path import exists, join, basename from shutil import rmtree import jams import numpy as np from sklearn.externals.joblib import dump, load from tensorflow.python.keras import backend as K def predict_from_models...
import pidsim.ml_simulator as ml_kinetics import pnptransport.finitesource as pnpfs import logging import os import numpy as np from datetime import datetime from pidsim.parameter_span import create_filetag import traceback import random def get_logger(output_path, file_tag, **kwargs): name = kwargs.get('name', '...
""" Utilities for isgm Best to keep these separate from the Class modules """ from __future__ import print_function, absolute_import, division, unicode_literals # Python 2 & 3 compatibility try: basestring except NameError: basestring = str import pdb import numpy as np import warnings import json from astr...
import argparse import sys import os import json import datetime import sys as _sys from gettext import gettext as _, ngettext from msgraph import helpers from common.BaseCommand import BaseCommand from common.ResultAndData import * from common.Instance import Instance from common.CaughtParserError i...
import os import sys import io from datetime import datetime import argparse import numpy as np from PIL import Image import tensorflow as tf import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d, Axes3D from PIL import Image import models.argo_nu as models parser = argparse.ArgumentParser() parser.a...
#!/usr/bin/env python import os import urllib import json import dateutil.parser from google.appengine.api import users from google.appengine.ext import ndb from datetime import timedelta, date import jinja2 import webapp2 JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(_...
# Copyright 2019 Katteli Inc. # TestFlows.com Open-Source Software Testing Framework (http://testflows.com) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/lice...
from datetime import date, datetime, timezone from enum import Enum from unittest.mock import Mock import pytest from dateutil import tz from todoms.converters.basic import ( AttributeConverter, ContentAttrConverter, DateAttrConverter, DatetimeAttrConverter, EnumAttrConverter, IsoTimeAttrConve...
import inspect import json import os import pandas as pd import requests from powersimdata.utility.distance import find_closest_neighbor from tqdm import tqdm import prereise def aggregate_ba_demand(demand, mapping): """Aggregate demand in BAs to regions as defined in the mapping dictionary :param pandas.D...
import os import sys import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.externals import joblib from collections import OrderedDict import re from os.path import dirname, join, abspath from sklearn.model_selection import cross_val_score def plot_coefficients(model, top_features=20): ...
import shutil import os # Get the current path of the script script_dir = os.path.dirname(os.path.abspath(__file__)) # Get the root folder of the ETL etl_dir = os.path.abspath(os.path.join(script_dir, os.pardir)) # Get the ETL repository folder include_dir = os.path.join(etl_dir, 'include') # Get the ETL heade...
from Sorts import count_sort def rabin_karp_matching( text: str, pattern: str, max_char: int = 256, prime: int = 999983) -> bool: ''' Pattern matching in a string using rabin karp algorithm. Takes a text and pattern as input and returns true if the pattern oc...
import numpy as np # NOT IN BOOK from matplotlib import pyplot as plt # NOT IN BOOK def load(): import numpy as np from scipy import sparse data = np.loadtxt('data/ml-100k/u.data') ij = data[:, :2] ij -= 1 # original data is in 1-based system values = data[:, 2] reviews = sparse.csc_matri...
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: from nose.tools import assert_equal, assert_raises from numpy.testing import assert_array_almost_equal, assert_array_equal import numpy as np from .... import load_image from ....testing import funcfile ...
#Python MemeCreationBot: creates a meme based on user input and imgflip.com internet connection import discord import random from discord.ext import commands import time from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager #list of lists for each meme; each list's elements ar...
# -*- coding: utf-8 -*- """ Created on Tue Dec 12 10:10:41 2017 @author: ibari """ import os import warnings from distutils.spawn import find_executable __LOCAL__ = ['sensor', 'projection', 'orbit', 'polarizations', 'acquisition_mode', 'start', 'stop', 'product', 'spacing', 'samples', 'lines'] class St...
import inspect import subprocess from collections import defaultdict from functools import wraps import pytest # deploy statuses STATUS_BEFORE, STATUS_AFTER, STATUS_CRUSHED = "before", "after", "crushed" class State: """ class for common vars """ terminal = None # terminal for printing deploy_cmd = Non...
#*************************************************************************** # _ _ ____ _ # Project ___| | | | _ \| | # / __| | | | |_) | | # | (__| |_| | _ <| |___ # \___|\___/|...
from SALib.sample import saltelli from SALib.analyze import sobol from SALib.test_functions import Ishigami import numpy as np from numpy import cos,sin,tan,pi from scipy.integrate import odeint from numpy.linalg import norm import pandas as pd import matplotlib.pyplot as plt import matplotlib #matplotlib.rcParams['tex...
# Acumos - Apache 2.0 import hashlib import fakeredis from acumos_proto_viewer.run_handlers import MODEL_SELECTION, MESSAGE_SELECTION from acumos_proto_viewer.run_handlers import get_source_index, handle_data_post, handle_onap_mr_put, handle_onap_mr_delete, get_model_properties, get_modelid_messagename_type from acum...
import os import tempfile import zipfile from datetime import timedelta from io import BytesIO from PIL import Image, ImageFont, ImageDraw from pycaption.base import BaseWriter, CaptionSet, Caption HEADER = """st_format 2 SubTitle\tFace_Painting Tape_Type\t{tape_type} Display_Start\tnon_forced Pixel_Area\t(2 479) Di...
"""Group.py: NeoPixel Indicator Module.""" import threading import time from typing import Any, List, overload import neopixel from npin.Constants import Color from npin.Counter import SharedCounter from npin.Element import Element class Group: """Make this a docstring.""" def __init__( self, elem...
import csv import util import numpy as np import statistics import argparse from os.path import join from collections import OrderedDict from tabulate import tabulate CLI = argparse.ArgumentParser() CLI.add_argument("fold", help="Absolute path of the fold json file") CLI.add_argument("k", help="Maximum number of rec...
import subprocess import time import threading import os import json import web #################################################### # run background services to receive web hooks #################################################### # agent webhook callbacks class webhooks: def GET(self, topic): # just fo...
import math import numpy as np from bwmorph_thin import bwmorph_thin as bwmorph def my_xor_infile(u_infile, u0_GT_infile): temp_fp_infile = np.zeros(u_infile.shape, np.uint8) temp_fp_infile[(u_infile == 0) & (u0_GT_infile == 1)] = 1 temp_fn_infile = np.zeros(u_infile.shape, np.uint8) temp_fn_infile[...
from typing import List from tensorflow.keras import Model, Input from tensorflow.keras import layers from datetime import datetime from pathlib import Path import tensorflow as tf from tensorflow.keras import losses, metrics from tensorflow.keras.callbacks import TensorBoard class ResidualBlock(layers.Layer): ...
"""Tools for creating graphical visualizations of auction algorithms.""" import re import json try: from IPython import display except ImportError: pass class AuctionGraphVisualizer(object): """Abstract base class for graph visualizations.""" def draw_graph(self, graph): raise NotImplementedE...
import os import cv2 import sys import torch import pprint import torch.nn as nn import torch.nn.functional as F import arcsim import gc import time import json import gc import numpy as np from datetime import datetime import pytorch3d from pytorch3d.structures import Meshes from pytorch3d.io import load_obj from py...
#!/home/wli/env python3 # -*- coding: utf-8 -*- """ Title: color normalization ========================== Created: 10-31-2019 Python-Version: 3.5 Description: ------------ This module is used to do the color normalization for image patches. Input: template image for color normalization template_image_path = '/ra...
""" plot_vertical_cross_section_from_netcdf.py: plot the vertical cross section from the netcdf file. """ import click import matplotlib.pyplot as plt import numpy as np from scipy.interpolate import RegularGridInterpolator from netCDF4 import Dataset def generate_vcs_mesh(lon1, lat1, lon2, lat2, dep1, dep2, rh, rdep...
import sys import inspect import weakref from contextlib import contextmanager from collections import OrderedDict import numpy as np from scipy.spatial import cKDTree _SHAPE_ASSERTIONS = True def assert_shape(arr, shape, label='array'): ''' Raises a ValueError if `arr` does not have the specified shape ...
"""Defines several services for Google OAuth implementation.""" import os import logging import json import requests from oauthlib.oauth2 import WebApplicationClient from urllib import request as urllib_request from flask import request, redirect from flask_login import login_user from . import auth_mapper logger = l...
# -*- coding: utf-8 -*- """ Created on Mon Nov 5 13:04:16 2018 Copyright (c) <NAME> Author email: <<EMAIL>> Description: This program was originally created to calculate the evaluation statistics of deblurred images. However, this program can be used to evaluate any image with another image. ...
# Copyright 2022 @ReneFreingruber # # 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 applicable law or agreed to in...
import os import glob import h5py import numpy as np from mask_DC2 import read_selections from mask_DC2 import mask_cat lowz_lib = '/gpfs/mira-fs0/projects/DarkUniverse_esp/dkorytov/data/Galacticus/low_z/galaxy_library/*.hdf5' hiz_lib = '/gpfs/mira-fs0/projects/DarkUniverse_esp/dkorytov/data/Galacticus/high_z/galaxy_l...