text
stringlengths
3.07k
22.1k
import cv2 import numpy as np from cfg.config import model_params, path_params, test_params, CLASSES def calculate_iou(box_1, box_2): """ calculate iou :param box_1: (x0, y0, x1, y1) :param box_2: (x0, y0, x1, y1) :return: value of iou """ # calculate area of each box area_1 = (box_1[2]...
import math import numpy as np import string import random import json import argparse import torch as T import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from transformers import * import sys sys.path.append("../") from DataLoader.bucket_and_batch import bucket_and_batch from model.B...
from enum import Enum, unique from math import fabs import random from tetris_engine import TetrisEngine, Playfield, TetrominoShape """ TODO if we record how the agent performs we can use emojis 🡲 Wide-Headed Rightwards Medium Barb Arrow 🡰 Wide-Headed Leftwards Medium Barb Arrow 🡳 Wide-Headed Downwards Medium Barb...
import logging import struct import time import json from ctypes import sizeof from ctypes.wintypes import FLOAT from SimConnect.Enum import SIMCONNECT_CLIENT_DATA_PERIOD, SIMCONNECT_UNUSED class SimVariable: def __init__(self, id, name, float_value = 0): self.id = id self.name = name self....
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Detect dhcp server working status on the network by broadcasting DHCP discover packet Created on Mar 27, 2011 Update on May 9, 2014 - ruohan.chen @author: hassane, linxiulei<<EMAIL>>, <EMAIL><<EMAIL>> ''' from __future__ import print_function impor...
from flask import Blueprint, request, jsonify from ..Models import db from ..Models.User import User from ..Models.Course import Course from ..Models.Schedule import Schedule from ..Models.Role import Role, RoleName from ..app import error_json from .Auth import require_logged_in from datetime import datetime import ...
"""" Implements the View-Model of an MVVM architecture. """ import hashlib import pickle import re from collections import OrderedDict, namedtuple from itertools import takewhile from typing import List, Mapping import dateutil.parser import nbformat from sqlalchemy.orm import joinedload, undefer from nbcollate impo...
'''Functions for performing CPM on connectome data. Originally created by github:esfinn at https://github.com/esfinn/cpm_tutorial/ ''' from random import sample import numpy as np import scipy as sp import pandas as pd from sklearn.model_selection import KFold def mk_kfold_indices(subj_list, k=10): """ Spli...
import json from urllib import response import pandas as pd import os import spacy from urllib.request import urlopen import json import requests import tarfile from tqdm import tqdm """ Method to get the size (bytes) of a directory (including all of its child directory) Code taken from: https://stackoverflow.com/qu...
import cv2 # state of the art computer vision algorithms library import numpy as np # fundamental package for scientific computing import matplotlib.pyplot as plt # 2D plotting library producing publication quality figures import pyrealsense2 as rs ...
"""Various common utils shared by the bots.""" import re from typing import Dict, Iterator, Optional, Set import unicodedata import mwparserfromhell import pywikibot import pywikibot.data.api from pywikibot import Site # Configuration used in the module, see `initLimits()`. _editsLimits: Dict[str, int] = {'default':...
from itertools import groupby class Atom: """An indeterminate raised to a certain power""" def __init__(self,s,p=1): assert type(s) == str assert len(s) == 1 assert type(p) == int assert p >= 1 self.s = s self.p = p def __eq__(self,other): ...
#!/usr/bin/env python3 import random, os, time, sys from nano25519.nano25519 import ed25519_oop as ed25519 from pyblake2 import blake2b from bitstring import BitArray import binascii from configparser import SafeConfigParser from modules import nano import pyqrcode BOARDWIDTH = 10 BOARDHEIGHT = 10 RAW_AMOUNT = 100000...
import random import websockets import asyncio import os import sys import json import argparse import gi gi.require_version('Gst', '1.0') from gi.repository import Gst gi.require_version('GstWebRTC', '1.0') from gi.repository import GstWebRTC gi.require_version('GstSdp', '1.0') from gi.repository import GstSdp sessi...
from apscheduler.schedulers.blocking import BlockingScheduler from multiprocessing.dummy import Pool as ThreadPool from bs4 import BeautifulSoup as bs import requests import timeit import datetime import time import sys import re from getconf import * # TO DO: scrape for early links # Constants base_url = 'http://www...
# Copyright (c) 2016-present, Facebook, Inc. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # pyre-strict import argparse import ast import functools import glob import logging import os from pathlib import Path from typing import Callable...
import argparse import json import sys import pandas as pd import numpy as np import scipy.interpolate import lalsimulation as lalsim from gwpy.table import Table try: import ligo.lw # noqa F401 except ImportError: raise ImportError("You do not have ligo.lw install: $ pip install python-ligo-lw") from bilb...
import os import pickle import gym import numpy as np import torch import torch.nn.functional as F from gym.spaces.box import Box from gym.wrappers.clip_action import ClipAction from stable_baselines3.common.atari_wrappers import (ClipRewardEnv, EpisodicLifeEnv, ...
import numpy as np import xarray as xr import sympy as sp import control as ct from typing import Callable, Optional, Sequence, Union, Tuple from collections import deque from textwrap import indent from tqdm.auto import tqdm from scipy.linalg import expm from IPython.display import display, Markdown from scipy.signal...
# Copyright 2021, 2022 Cambridge Quantum Computing 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 la...
from tqdm import trange from script.model.sklearn_like_model.Mixin import Xs_MixIn, zs_MixIn, noise_MixIn from script.model.sklearn_like_model.BaseModel import BaseModel from script.util.Stacker import Stacker from script.util.tensor_ops import * from script.util.summary_func import * import numpy as np def ...
# python3 # Copyright 2021 InstaDeep Ltd. 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 applic...
import logging from logging import config import json import random from random import shuffle import argparse from pprint import pprint from pathlib import Path import sys import os import gc import math import ipdb from tqdm import tqdm import numpy as np import pandas as pd import adabound from sklearn.metrics impor...
#!/usr/bin/env python3 # coding: utf8 # Author: <NAME>, 2018 ''' Parse the MEDIC terminology used for the NCBI disease corpus. ''' import csv from collections import OrderedDict from ..terminology import DictEntry from ...util.util import smart_open from ...util.umls import read_RRF, iterconcepts, co_rows, C, D ...
""" KVSController is a wrapper for KVSClient that adds some useful functionality related to interprocess communication. It also keeps track of a bunch of SLURM related stuff that was previously workflow's problem. """ from kvsstcp import KVSClient from inferelator.distributed import AbstractController from inferelato...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from torch.nn import functional as F from maskrcnn_benchmark.layers import smooth_l1_loss from maskrcnn_benchmark.modeling.box_coder_3d import BoxCoder3D from maskrcnn_benchmark.modeling.matcher import Matcher from maskrcnn_benchmark....
# ----------------------------------------------------------------------------- # Copyright (c) 2009-2016 <NAME>. All rights reserved. # Distributed under the (new) BSD License. # ----------------------------------------------------------------------------- import numpy as np from . import colors as _colors from glumpy...
import numpy as np import pandas as pd from nltk import word_tokenize from scipy.optimize import linear_sum_assignment import networkx as nx from node2vec import Node2Vec from tax_utils import read_nigp_csv_pd, get_averaged_vectors, read_okpd_pd from tax_utils import matrices_cosine_distance, get_top_indices from ut...
from functools import wraps from time import time from typing import Optional import jsonpickle as jspkl import json import requests from flask import Flask, jsonify, request, render_template from flask_cors import CORS import binascii import Crypto import Crypto.Random from Crypto.PublicKey import RSA from blockchai...
import tensorflow as tf from tensorflow import keras from tensorflow.python.keras.engine import data_adapter from tensorflow.python.eager import backprop from tensorflow.python.keras.mixed_precision.experimental import loss_scale_optimizer as lso from tensorflow.python.distribute import parameter_server_strategy clas...
#!/usr/bin/env python import re import sys from optparse import OptionParser def extractSplitsFromBwaMem(inFile, numSplits, includeDups, minNonOverlap): if inFile == "stdin": data = sys.stdin else: data = open(inFile, 'r') for line in data: split = 0 if line[0] == '@': ...
import os import typing as tp from numbers import Number from dataclasses import dataclass try: import click except ImportError: click = None from .math import * from .table import TableParameters __all__ = ('Designer', 'DesignResult') class Designer: """A utility to assist in choosing correct values fo...
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
import sys import json import time from random import choice, randint, randrange import pathlib import logging import timeit import click from click_help_colors import HelpColorsCommand, HelpColorsGroup from typing import Union, Optional from math import inf as INFINITE from cyberserver.servers import utilities _scr...
#!/usr/bin/env python import copy import math import pickle import random from itertools import combinations import js2py import hashlib import base64 def euclid(a, b): """returns the Greatest Common Divisor of a and b""" a = abs(a) b = abs(b) if a < b: a, b = b, a while b != 0: a...
import os import sys import numpy as np import json import random import trimesh from sklearn.decomposition import PCA BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(BASE_DIR, '..', 'code')) from pyquaternion import Quaternion def load_obj(fn): fin = open(fn, 'r') lines = [l...
import pandas as pd import numpy as np from collections import Counter import itertools import re # Own modules #from preprocessing import cleaning #from utilities import utils #### CONTACT TYPES AND ACTIVITY COUNT JOURNEY PROFILES def one_hot_encoding(eventlog_df): """ Function that creates the Activity...
import os.path import zipfile from collections import OrderedDict from time import time from django.conf import settings from django.contrib import messages from django.core.exceptions import PermissionDenied from django.forms import formset_factory from django.http import Http404 from django.shortcuts import get_obje...
import pickle import numpy as np import pandas as pd import torch from matplotlib import pyplot as plt from data_generator import GPCurvesReader from decoder import Decoder from deterministic_encoder import DeterministicEncoder from latent_encoder import LatentEncoder from util import plot_functions TOTAL_EPOCHS = 1...
"""Tree inducers: SKL and Orange's own inducer""" import numpy as np import scipy.sparse as sp import sklearn.tree as skl_tree from Orange.base import TreeModel as TreeModelInterface from Orange.classification import SklLearner, SklModel, Learner from Orange.classification import _tree_scorers from Orange.statistics i...
''' This is a follow up of https://letianzj.github.io/portfolio-management-one.html It backtests four portfolios: GMV, tangent, maximum diversification and risk parity and compare them with equally-weighted portfolio ''' import os import numpy as np import pandas as pd import pytz from datetime import datetime, timezon...
#! /usr/bin/python3 import os import importlib.util # import pathlib spec = importlib.util.spec_from_file_location("module.name", "/home/jolitp/Dropbox/PROJECTS/python-scripts/helpers/helpers/helpers.py") helpers = importlib.util.module_from_spec(spec) spec.loader.exec_module(helpers) # region def get_first_co...
import functools from abc import ABC, abstractmethod from logging import Logger from typing import List, Optional, Set, Tuple, Type, Dict from guapow.common import class_util from guapow.common.model import CustomEnum, ProfileFile, FileModel def rgetattr(obj, attr, *args): def _getattr(obj, attr): return...
import re import reversion from django.conf import settings from django.contrib.auth.models import User from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models from crum import get_current_request from dja...
import os import sys import numpy as np import torch import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP import torch.multiprocessing as mp import torchvision as tv from mlpug.examples.documentation.shared_args import base_argument_set, describe_args # Import mlpug for Pyt...
""" ~ guild ~ This module contains the class defitions for all things regarding the guild and also defines a USER class from the BaseGUILD class. """ from contextlib import suppress from typing import Literal, Union, List from .tracing import * from .const import * from .message import...
# Copyright (c) 2018 FlashX, LLC # # 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, distrib...
""" module for window to query a documents source. query string search syntax: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#query-string-syntax """ from __future__ import unicode_literals from prompt_toolkit.application import Application from prompt_toolkit.key_bi...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Created on Wed Apr 22 14:40:52 2015 @author: ddboline """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np import pandas as pd import os import gzip imp...
''' (*)~--------------------------------------------------------------------------- Pupil - eye tracking platform Copyright (C) 2012-2018 Pupil Labs Distributed under the terms of the GNU Lesser General Public License (LGPL v3.0). See COPYING and COPYING.LESSER for license details. ------------------------------------...
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import inspect from functools import update_wrapper from typing import Any, Set, Tuple, Type from pants.build_graph.address import Address from pants.engine.internals.objects import Resol...
#!/usr/bin/env python from bs4 import BeautifulSoup import requests from datetime import date import pandas as pd url = 'https://weather.com/en-IN/' api_key="<KEY>" #obtained from the source code itself. date_def= date.today() #default date cho...
import pandas as pd; import numpy as np; import scipy as sp; import sklearn; import sys; from nltk.corpus import stopwords; import nltk; import gensim from gensim.models import ldamodel import gensim.corpora as corpora from gensim.utils import simple_preprocess from gensim.models import CoherenceModel import gensim.cor...
import os.path import numpy as np import pandas as pd from matplotlib import pyplot as plt plt.switch_backend('agg') #needed to work on linux from simulation_params import * #imports variables used in the simulation #for reference, variables are as follows: simulation_name, training_epochs, display_epochs, timestep, n_...
#!/usr/bin/env python3 import ipfshttpclient import Hello_baxter import typing as tp import threading import rospy import time import yaml import cv2 import os from substrateinterface import SubstrateInterface, Keypair from sensor_msgs.msg import LaserScan from sensor_msgs.msg import Image from cv_bridge import CvBrid...
import pandas as pd pd.options.mode.chained_assignment = None # default='warn' import os from os.path import expanduser home = expanduser("~") from sklearn.externals import joblib import numpy as np import sys from bs4 import BeautifulSoup import sys import argparse import re import os.path from os import makedirs fr...
''' terms.py part of the wordfish python package: extracting relations between terms from corpus this set of functions works with different plugins (in plugins folder) to produce input terminologies to search for in corpus Copyright (c) 2015-2018 <NAME> Permission is hereby granted, free of charge, to any person ob...
"""Main Module for the Restaurant-Search""" import random from typing import List from typing import Union import httpx from sqlalchemy.orm import Session from db.crud import filter as crud_filter from db.crud import restaurant as crud_restaurant from db.crud import restBewertung as crud_restBewertung from schemes.ex...
# pylint: disable=unused-argument from collections import OrderedDict import json import six from django.conf import settings from django.test import Client from django.db import transaction from . import base, serializers, permissions, filters, decorators as deco class UserViewSet(base.ModelViewSetSet): ''' ...
import configparser import ctypes import os import platform import shutil import sys import tempfile import time from distutils.util import strtobool from pathlib import Path from shutil import copy from subprocess import CalledProcessError, check_output from threading import Thread from unittest import mo...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ============================================================================= """cluster_model - Contains model functions for the Graph Clustering Component""" # ============================================================================= # Imports # ==================...
#!/usr/bin/python ########################################################################### # # Copyright 2019 Dell, 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....
# -*- coding: utf-8 -*- ############################################################################### # # Copyright (c) 2019 HERE Europe B.V. # # SPDX-License-Identifier: MIT # ############################################################################### import json import random import numpy as np f...
#!/usr/bin/env python # 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 # "L...
import pytest import numpy as np import time from keras_contrib.utils.kito import reduce_keras_model def compare_two_models_results(m1, m2, test_number=10000, max_batch=10000): i1 = m1.layers[0].input_shape i2 = m2.layers[0].input_shape if i1 != i2: print('Different input shapes for models {} vs {...
#%% """ Created on July 05 2021 Exposures for an IR swaps, under the Hull-White model - case of netting This code is purely educational and comes from "Financial Engineering" course by <NAME> The course is based on the book “Mathematical Modeling and Computation in Finance: With Exercises and Python and MATLAB...
import abc import dataclasses import re from typing import List, Optional, Tuple from . import helpers, inflection from .helpers import MatchError, ModSet from .js_function import JsFunction, RustParam from .js_type import JsType, TypeWithDocumentation from .models import Context, Documented, ToRust @dataclasses.dat...
import pytest import mock import random import string import os import sys myPath = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, myPath + '/../../') from classes.Http import Http from classes.Registry import Registry from classes.kernel.WSException import WSException from libs.common import file_put_...
import argparse import os from operator import itemgetter import torch from NVLL.data.lm import DataLM from NVLL.model.nvrnn import RNNVAE from NVLL.util.util import GVar def load_args(path, name): with open(os.path.join(path, name + '.args'), 'rb') as f: args = torch.load(f) return args def load_...
#/Users/berk/Computational Vaccine Design/MHCIAnalysis.py #5/18/2021 #In this script, the MHCI binders dataset from the Immune Epitope Dataset will be analyzed. First, the dataset will be cleaned up - duplicates removed and epitopes categorized by protein. Next, MHCI binding predictions will be run on the data and the ...
import tensorflow as tf import pickle import numpy as np from collections import Iterable import pprint import os import datetime import random from tensorflow.python.training import moving_averages from enum import Enum from abc import ABC, abstractmethod def axes_wo_the_last(x): return list(range(len(x.get_shap...
""" API Definition helpers for user apps """ import inspect from functools import partial from typing import Optional, List, Type, Dict, Callable, Union, Tuple, Any, TypeVar import re import typing_inspect # type: ignore from hopeit.dataobjects import BinaryDownload from hopeit.app.config import AppConfig, AppDescri...
"""Adds config flow for GarbageCollection.""" import uuid from collections import OrderedDict from typing import Dict import homeassistant.helpers.config_validation as cv import homeassistant.util.dt as dt_util import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_NAME ...
#!/usr/bin/env python # -*- coding:utf-8 -*- """================================================================= @Project : Algorithm_YuweiYin/LeetCode-All-Solution/Python3 @File : LC-2039-The-Time-When-the-Network-Becomes-Idle.py @Author : [YuweiYin](https://github.com/YuweiYin) @Date : 2022-03-20 ============...
from string import repr from graph import Graph, Digraph class Token: __slots__ = [] def __init__(self): pass class TokenEnd(Token): __slots__ = [] def __init__(self): pass class TokenName(Token): __slots__ = ['value'] def __init__(self, value): self.value = value class TokenString(Token): ...
#!/usr/bin/python # -*- coding: UTF-8 -*- import pandas as pd from sklearn.preprocessing import StandardScaler class PreprocessData: def readData(self,file): df = pd.read_csv(file) return df def writeData(self,df,file,): df.to_csv(file,index=False) def dropColumns(self,df,column...
import math import osmnx as ox import matplotlib.pyplot as plt import numpy as np import geopy.distance import imageio from timeit import default_timer as timer import pandas as pd import seaborn as sns import scipy from scipy.stats import norm import requests import json import os from os.path import j...
''' ResNet-like CNN models. @author <NAME> ''' import tensorflow as tf from tensorflow.contrib.tpu.python.tpu import tpu_config from tensorflow.contrib.tpu.python.tpu import tpu_estimator from tensorflow.contrib.tpu.python.tpu import tpu_optimizer import numpy as np import time import resnet_model tf.flags.DEFINE_b...
""" Functions to create graph visualizations of WNTR networks """ ## TODO: # - [nothing at the moment, JJS 1/25/21] import numpy as np import wntr import networkx as nx import pandas as pd import warnings import matplotlib from matplotlib import cm, colors, colorbar, pyplot import PyPDF2 import os def build_graph(...
import numpy as np import gzip import pickle as cp import pickle from copy import deepcopy import matplotlib.pyplot as plt plt.rcParams['text.usetex'] = True import matplotlib as mpl mpl.rcParams['font.size'] = 12 mpl.rcParams['text.usetex'] = True mpl.rcParams['text.latex.preamble'] = r'\usepackage{{amsmath}}' ''' ...
# # Copyright (c) 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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
import sc2reader import matplotlib.pyplot as plt import numpy as np def worker_created(replay, player_id): workers = [] for event in replay.events: if event.name == "UnitBornEvent" and event.control_pid == player_id: if event.unit.is_worker: workers.append(event.s...
#!/usr/bin/env python3 # Copyright 2020 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. """Command-line tool for printing class-level dependencies.""" import argparse from dataclasses import dataclass from typing import Li...
import logging from random import sample import formatter import json import unicodedata from api_wrapper import CryptoMKT, SurBTC, Orionx logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) class TelegramRequestProcessor: def __init__(self, github, github_user, github_repo): se...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @created: 01.08.21 @author: felix """ import ast import inspect from pathlib import Path from typing import Any from typing import List import click from strongtyping.docs_from_typing import ( rest_docs_from_typing, numpy_docs_from_typing, class_docs_from_...
""" Compares 3 versions of LightGBM Inferencing A - vanilla B - custom build C - treelite to execute: > python src/pipelines/azureml/lightgbm_inferencing.py --exp-config conf/experiments/lightgbm-inferencing.yaml """ # pylint: disable=no-member # NOTE: because it raises 'dict' has no 'outputs' member in dsl.pipeline ...
"""Tools for processing the SSE data for the Gaussian Process.""" from __future__ import annotations from typing import Dict, List, Optional, Union import numpy as np import pandas as pd import pymatgen from megnet.models import MEGNetModel from tensorflow.keras import backend as K from tqdm.contrib import tmap from...
import pyglet from pyglet.gl import * from robocute.base import * QUAD_SW = 0 QUAD_SE = 1 QUAD_NE = 2 QUAD_NW = 3 ''' Quad ''' class Quad(Base): def __init__(self, texture): super().__init__() self.texture = texture self.width = texture.width self.height = text...
""" Objects and helper functions to help with deterministic model calibration and statistical inference. """ from collections import defaultdict import warnings import numpy as np import scipy.interpolate as inter import scipy.optimize as opt import torch from torch.nn import Module, Parameter from skopt.space ...
# (c) 2020-2021, <NAME> @ ETH Zurich # Computer-assisted Applications in Medicine (CAiM) Group, Prof. <NAME> """ This will be called from Create_Dataset to calculate patch indices and return them to fiji for cropping """ import os import site import sys import numpy as np site.addsitedir(os.getcwd()) from utils.cnn...
# -*- coding: utf-8 -*- import os import json from flask import Flask, render_template, g app = Flask(__name__) class DataManager(object): s_computed_values = None @staticmethod def setComputedValues(values): DataManager.s_computed_values = values @staticmethod def getComputedValues(): ...
import sys import os import argparse import logging import pdb import numpy as np from intermol.system import System import helper_functions import desmond_driver import gromacs_driver import lammps_driver # global constants DES_POS = 0 GRO_POS = 1 LMP_POS = 2 N_FORMATS = 3 # Make a global logging object. logger = ...
""" Perform array-wise performance evaluation and plot curves. Supported types of curves: - Precision-recall curves - ROC curve (false positive rate per unit are on the x-axis) """ import os import argparse from tqdm import tqdm import matplotlib.pyplot as plt plt.rcParams['font.family'] = 'serif' plt.rcPar...
import numpy as np import operator from keras.models import model_from_config, Sequential, Model, model_from_config import keras.optimizers as optimizers import keras.backend as K import time def clone_model(model, custom_objects={}): # Requires Keras 1.0.7 since get_config has breaking changes. config = { ...
# -*- coding: utf-8 -*- import click import logging from pathlib import Path from dotenv import find_dotenv, load_dotenv import time import json import os from halite_agent.api.KaggleClient import KaggleClient @click.command() @click.argument('output_filepath', type=click.Path(), default='data/raw/') def main(output_...
import argparse import os from patch_based import data from patch_based import models as m import torch import torch.optim as optim import yaml from patch_based.logger import Logger, ModelLogger from patch_based.trainers import Trainer import sys import numpy as np from PIL import Image from patch_based.custom_transfo...
# Copyright 2015 The TensorFlow Authors. 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 applica...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math import torch import torch.nn.functional as F from fairseq import metrics, utils from fairseq.criterions import FairseqCriterion, ...
# Stuff for reading the data # -*- coding: UTF-8 -*- import codecs, os, glob #from extras import offset_tokenize #from extras import segment_text import extras #from extras import utf8ify import sys # this wreaks havoc on the application if used with python3 if sys.version_info < (3,): reload(sys) sys.setdef...
#!/usr/bin/env python3 import site import sys new_sys_path = set(sys.path) for path in site.getsitepackages(): if path in new_sys_path: new_sys_path.remove(path) sys.path[0:] = new_sys_path import os.path if __name__ == '__main__': # sys.path.append('/usr/lib/libreoffice/program') sys.path.appen...