text stringlengths 6.04k 39.5k |
|---|
# Adapted from:
#
# -*- coding: utf-8 -*-
#==========================================
# Title: syntheticFunctions.py
# Author: <NAME> and <NAME>
# Date: 20 August 2019
# Link: https://arxiv.org/abs/1906.08878
#==========================================
# For license relevant to the original work,
# see /prob... |
from __future__ import division
from pyomo.environ import *
from pyomo.dae import *
import numpy as np
import pandas as pd
'''
Linear interpolation to find data for new time grid (e.g., the one obtained via FE collocation)
Inputs:
- x_new: new domain for which to perform interpolation
- x: domain for whi... |
# plot Antennas position results relative to one antenna
# First version imported by <NAME>. All subsequent edits by <NAME>
#
from __future__ import print_function # prevents adding old-style print statements
import math
from asdm import *
from AntPosResult import *
import pylab as pl
from WvrCorrection import *
def... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2018, <NAME> <<EMAIL>> <<EMAIL>>
# 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
__metaclass__ = type
DOCUMENTATION = '''
---
module: openssh_cert
author: "<N... |
import numpy as np
from skimage import io, color
import mock
# import graph
# import dijkstra_path
# import dijkstra
from scipy.signal import convolve2d as conv2
def construct_graph(X):
import graph
h, w, c = X.shape
G = {}
V = list(range(h * w))
# E = []
Graph_X = graph.Graph(G... |
#!/usr/bin/env python
# ASCii VMSS Console - The power is in the terminal...
"""
Copyright (c) 2016, <NAME>
Description: The power is in the terminal...
License: MIT (see LICENSE.txt file for details)
"""
from azure import *
#Linux or Windows?
oursystem = platform.system();
#Our Home...
HOMEUSER = expanduser("~")
... |
"""
TRPO is almost the same as PPO. The only difference is the update rule that
1) computes the search direction via conjugate
2) compute step by backtracking
"""
import time
import gym
import numpy as np
import torch
import torch.distributions
from torch.optim import Adam
import spinup.algos.pytorch.trpo.core as co... |
import os
import torch
import itertools
import numpy as np
from torch.utils.data import Dataset
import nibabel as nib
from fmri.models.supervised.resnetcnn3d import ConvResnet3D
from fmri.models.unsupervised.VAE_3DCNN import Autoencoder3DCNN
from fmri.models.unsupervised.SylvesterVAE3DCNN import SylvesterVAE
import ran... |
from fltk import *
from PyCommon.modules.GUI.hpSimpleViewer import *
from PyCommon.modules.Renderer import ysRenderer as yr
from PyCommon.modules.GUI import ysSimpleViewer_ori as ysvOri
from PyCommon.modules.GUI import ysBaseUI as ybu
import pydart2 as pydart
from SkateUtils.NonHolonomicWorld import NHWorld, NHWorldV2... |
# Imports Alphabetically:
from decimal import Decimal
from matplotlib.backends.backend_wx import NavigationToolbar2Wx
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.figure import Figure
from os import listdir
from scipy import stats
from scipy.interpolate import interp1d... |
from __future__ import division
import numpy as np
import multiprocessing
from sys import stdin, stdout, version_info
# For compatibility with python3.
if version_info[0] == 3:
from functools import reduce
xrange = range
__map = map
map = lambda *args: list(__map(*args))
__filter = filter
filter = lambda *... |
# -*- coding: utf-8 -*-
import numpy as np
from scipy.interpolate import interp1d
from . import constants as cc
from . import utils
from . import preliminary_computations as precomp
#######################################
#-------------------------------------------------------------------------------
def set_filter(... |
import os
import re
from sqlalchemy import func
from flask import current_app, json, render_template, request, send_from_directory, jsonify
import werkzeug
import datetime
import codecs
from emonitor.extensions import db, babel
from emonitor.modules.alarmkeys.alarmkey import Alarmkey
from emonitor.modules.alarmkeys.al... |
from __future__ import print_function
import re
from datetime import datetime as dt
import pandas as pd
import orca
from urbansim.models.util import (apply_filter_query, columns_in_filters,
columns_in_formula)
################################
## SPEC AND FORMAT MANAGEMENT ##
##############################... |
import dataclasses
from typing import List, Optional, Sequence, Tuple, Set
from fv3fit._shared.config import (
OptimizerConfig,
RegularizerConfig,
register_training_function,
)
from fv3fit._shared.scaler import StandardScaler
from fv3fit._shared.stacking import SAMPLE_DIM_NAME, StackedBatches
import tensorf... |
# %% [markdown]
# # Error Estimation
# %%
from datetime import datetime
import glob
import logging
import os
import cartopy.crs as ccrs
import luigi
import matplotlib
import matplotlib.colors as colors
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from netCDF4 import Dataset
thresholds = [1e-... |
# -*- coding: utf-8 -*-
import functools
import sys
import os
from argparse import ArgumentParser
from contextlib import contextmanager
import tensorflow as tf
from pprint import pformat
from matplotlib import pyplot
from tensorflow.contrib.framework import arg_scope, add_arg_scope
import tfsnippet as spt
from tfsnip... |
"""Provides a number of classes used internally by midani.
"""
import dataclasses
import functools
import math
import random
import typing
from . import midani_colors
@dataclasses.dataclass
class Note: # pylint: disable=missing-class-docstring
pitch: int
start: float
end: float
def __post_init__(s... |
# Copyright (c) 2021, <NAME>, FUNLab, Xiamen University
# All rights reserved.
import os
import time
import numpy as np
import random
import torch
from pathlib import Path
from numpy.random import default_rng
from pprint import pprint
def generate_1_sequence(size, MAX):
rng = default_rng()
sequence = rng.choi... |
# Copyright 2019 IBM 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 in writing, ... |
import datetime, heapq, json, operator, pymongo, tweepy
from .util import *
from .keys import angus as angus_keys
from .keys import twitter as twitter_keys
from config import *
from database import Database
from .twitter import Connection
from .faces import Connection as Faces
from .sentiment import Predictor
class... |
#!/usr/bin/env python
import re
import keyword
import os.path as op
import simplejson as json
from jsonschema import validate, ValidationError
from argparse import ArgumentParser
from boutiques import __file__ as bfile
from boutiques.util.utils import loadJson, conditionalExpFormat
from boutiques.util.utils import cus... |
#!/usr/bin/env python3
"""Run through all the results and perform turbulence analysis on each
"""
# ========================================================================
#
# Imports
#
# ========================================================================
import os
import argparse
import numpy as np
import time
... |
"""
Utility functions for link prediction
Most code is adapted from authors' implementation of RGCN link prediction:
https://github.com/MichSchli/RelationPrediction
"""
import numpy as np
import torch
import dgl
import math
from dgl.contrib.data import load_data
######################################################... |
"""
The :mod:`hotspots.hs_io` module was created to facilitate easy reading and
writing of Fragment Hotspot Map results.
There are multiple components to a :class:`hotspots.result.Result` including, the
protein, interaction grids and buriedness grid. It is therefore tedious to manually
read/write using the various cla... |
import tensorflow as tf
from tensorflow.keras import layers
import numpy as np
from sklearn.model_selection import train_test_split
from scipy.stats import chi2
import json
#beyond preprocessing, everything the user needs should be in here
def makeWindow(data, window = 1):
data = np.array(data)
t = data.shape[... |
""" Fix time / date / timezone for photos in Apple Photos """
import datetime
import os
import sys
from functools import partial
import click
import pytimeparse
from cloup import (
Command,
Context,
HelpFormatter,
HelpTheme,
Style,
command,
constraint,
option,
option_group,
ver... |
# Copyright 2018 The TensorFlow Probability 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://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
# This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import classification.operations as O
import numpy as np
import torch
from classification import utils
from torch import nn
from util.categorical_asng import CategoricalASNG
n_prev_cells = 2
n_categorical_dist_per_node = 4
channels_image = 3
def count_params(module):
... |
import matplotlib
matplotlib.use("Qt4Agg")
matplotlib.rcParams['backend.qt4'] = 'PySide'
import PySide
from PySide import QtCore, QtGui
import math
import os
import datetime
import vc.util
import vc.variable
import vc.globals
import vc.backend
from QTWeekGraph import WeekGraph
from QTTelemetryWindow import QTTelemet... |
import json
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.http import Http404
from ..ehb_service_client import ServiceClient
from ..utilities import RecordUtil... |
from abc import ABC
import torch
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https... |
from data_loading import ColonDataset
import argparse
import _osx_support
import copy
import time
import os
import numpy as np
from collections import defaultdict
import torch
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from torchsummary import summary
from architecture... |
import os
import argparse
import yaml
import json
import ast
import textwrap
import inspect
from shlex import quote
from collections import OrderedDict
try:
from collections.abc import MutableMapping
except ImportError:
from collections import MutableMapping
import json
from pprint import pprint
from sys impo... |
# Copyright (c) 2021 Graphcore Ltd. All rights reserved.
import argparse
import json
import os
import re
from multiprocessing import Pool
from glob import glob
from pathlib import Path
from typing import Any, Dict, Iterator, List, Text, Tuple
# clang is not a common install. Raise error and point to readme in case of ... |
# -*- coding: utf-8 -*-
"""
Structure Relaxations are made up of a series of ionic steps -- where each
ionic step can be thought of as a single energy calculation. This yields
energy, forces, and lattice stress for a given structure. In many cases,
users won't need all of this data because they're only after the final... |
# coding='utf-8'
import matplotlib.pyplot as plt
import numpy as np
import os
def t_SNE_visualisations():
from time import time
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.ticker import NullFormatter
from sklearn import manifold, datasets
n_points ... |
#!/usr/bin/python
# Copyright (c) 2020 Red Hat
# 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
__metaclass__ = type
DOCUMENTATION = r"""
module: podman_network
author:
- "<NAME> (@sshnaidm)"
version_added:... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import copy
def one_hot_encode_along_channel_axis(sequence, onehot_axis=1):
to_return = np.zeros((len(sequence),4), dtype=np.int8)
seq_to_one_hot_fill_in_array(zeros_array=to_return,... |
"""Contains I/O operation from and towards .fif format (MEGIN / MNE)."""
import json
import operator
from functools import reduce
from numbers import Integral
from pathlib import Path
from typing import List, Union
import numpy as np
from mne.io import Info
from mne.io._digitization import _format_dig_points, _read_d... |
import copy
import logging
import os
import platform
import re
import subprocess
import sys
from pathlib import Path
from typing import List, Union, Dict, Optional
import pkg_resources
from rdkit import rdBase
from rdkit.Chem import AllChem as Chem
from rdkit.Chem.Descriptors import NumRadicalElectrons
from rdkit.Chem... |
import requests
import time
import schema
import yaml
import logging
import warnings
import shell
import datetime
import contextlib
import traceback
import logging
import sys
import util.iter
import util.log
import googleapiclient.discovery
import google.cloud.dns
import google.cloud.storage
import google.cloud.logging... |
import unittest.mock
import pyJ1587 as dut
class TestPID(unittest.TestCase):
SINGLE_LENGTH_PIDS = [0, 1, 12, 127, 256, 383]
DOUBLE_LENGTH_PIDS = [128, 191, 384, 447]
VARIABLE_LENGTH_PIDS = [192, 253, 448, 509]
DLESCAPE_PIDS = [254, 510]
UNEXTENDED_PIDS = [0, 1, 12, 254]
EXTENDED_PIDS = [256,... |
#!/usr/bin/env python3
# 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 pandas as pd
from collections import defaultdict
import numpy as np
import numpy.ma as ma
from pathlib import Pat... |
'''
(c) University of Liverpool 2020
Licensed under the MIT License.
To view a copy of this license, visit <http://opensource.org/licenses/MIT/>..
@author: neilswainston
'''
# pylint: disable=invalid-name
# pylint: disable=protected-access
# pylint: disable=too-many-arguments
# pylint: disable=too-many-l... |
import math
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.axes import Axes
import seaborn as sns
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing... |
"""
Create a hardcoded AI team i.e. actions are determined using simple geometry
"""
from settings import *
from const import ACT, FORM
from teams.agent import Agent
from teams.team import Team
class OriginalAIAgent(Agent):
"""
Harcoded AI agents that play like the original AI (designed in 2013)
Takes an... |
import numpy as np
import pandas as pd
DAYS_INFO_PATH, REGIONS = 'agg_data/1_regions_features_mean.npy', 1 # data aggregated for the whole city
###################################################### DATA PREPROCESSING PARAMETERS
MM, TIME_SLOT = 60, 5 # In minutes
SLOTS_PER_HOUR = int(MM/TIME_SLOT)
TOTAL_SLOTS = 24*S... |
#-*- coding: utf-8 -*-
# https://github.com/Kodi-vStream/venom-xbmc-addons
from resources.lib.gui.hoster import cHosterGui
from resources.lib.gui.gui import cGui
from resources.lib.handler.inputParameterHandler import cInputParameterHandler
from resources.lib.handler.outputParameterHandler import cOutputParameterHandle... |
# -*- coding: utf-8 -*-
"""
Chord Diagrams for Bokeh
Author: <NAME>
"""
import numpy as np
from operator import itemgetter
from bokeh import palettes
from bokeh.plotting import figure
from bokeh.models import Range1d
class Color():
""" Make it easy to iterate through different colors. """
def... |
#!/usr/bin/env python3
import datetime
import os
import subprocess
import sys
import time
from pathlib import Path
from signal import SIGINT, SIGTERM, signal
import mysql.connector
import pandas as pd
from django.core.mail import EmailMessage
from dotenv import load_dotenv
sys.path.insert(1, str(Path(sys.path[0]).pa... |
from dataclasses import dataclass
from datetime import datetime, timezone
from dataclass_csv import accept_whitespaces, dateformat
from sqlalchemy import Column, DateTime, Float, ForeignKey, Integer, String
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import relationship
import vigorish.datab... |
import datetime as dt
import logging
import os.path
import numpy as np
import pandas as pd
import pyam
import scipy.interpolate
from openscm_units import ScmUnitRegistry
from pint.errors import DimensionalityError
logger = logging.getLogger(__name__)
# initialise our own registry to avoid conflicts
_ur = ScmUnitRegi... |
#!/usr/bin/env python
import argparse as ap
import pandas as pd
import logging
import datetime
from collections import defaultdict
from os import path
def initialize_frame(processedFilePrefix, reportType):
if reportType == 'truncater':
header = ['Total_Reads_Processed',
'Truncated',
... |
## Pok On Cheng 74157306. ICS 32 Lab 1 Project 5.
import tkinter
import OthelloGameLogic
from math import ceil
DEFAULT_FONT = ('Times New Roman', 12)
class CreatingOthelloGUI:
def __init__(self):
self._creating_GUI = tkinter.Toplevel()
ask_row1_label = tkinter.Label(master = self._cr... |
import random
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import operator
class GAError(Exception):
'''Base class for throw exception error in this module.'''
pass
class InitializationError(GAError):
'''Exception for initialization errors.'''
pass
class GAManager:
def ... |
import pandas as pd
import numpy as np
from gtda.time_series import SlidingWindow
import matplotlib.pyplot as plt
from math import atan2, pi, sqrt, atan2, sin, cos, radians
import h5py
import json
import glob
from scipy.signal import savgol_filter
from geographiclib.geodesic import Geodesic
from tqdm import tqdm
import... |
from models.diffusion.fp16_util import convert_module_to_f32, convert_module_to_f16
from models.diffusion.gaussian_diffusion import get_named_beta_schedule
from models.diffusion.nn import timestep_embedding, normalization, zero_module, conv_nd, linear
from models.diffusion.respace import SpacedDiffusion, space_timestep... |
import torch.nn.functional as F
from module.model import *
from helper.utils import *
import torch.distributed as dist
import time
import copy
from multiprocessing.pool import ThreadPool
from sklearn.metrics import f1_score
def calc_acc(logits, labels):
if labels.dim() == 1:
_, indices = torch.max(logits,... |
# This file is NOT licensed under the GPLv3, which is the license for the rest
# of ycmd.
#
# Here's the license text for this file:
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in sourc... |
# -*- coding: Utf-8 -*
from typing import Optional, Any, Union, Callable, Iterator, Sequence
import pygame
from pygame.sprite import Sprite
from pygame.math import Vector2
from .surface import create_surface
from .theme import ThemedObject
from .clock import Clock
class Drawable(Sprite, ThemedObject):
def __init... |
from __future__ import unicode_literals
import frappe
import datetime
from datetime import datetime, timedelta
from datetime import date
from frappe import msgprint
from frappe.utils.file_manager import save_url, save_file, get_file_name, remove_all, remove_file
import json
from frappe.model.document import Document
@... |
#!/usr/bin/env python
#this specify that the script is written in python. Every ROS node in
#python should start with this line (or else it won't work properly.)
#############
### USAGE ###
#############
"""
1.
# Create an obstacles model generator specifying the following fields:
# (name of the simulation, obstacle... |
import torch
from torch import nn
import time
import torchtext
import numpy as np
import random
from collections import defaultdict, Counter
from get_arguments import *
class DeepBiaffineScorer(nn.Module):
def __init__(self, rnn_size, mlp_size, out_size, bias_x, bias_y):
super().__init__()
mlp_a... |
import tensorflow as tf
import tensorflow_addons as tfa
from ctc import ctc_decode
from ctc import greedy_decode
@tf.function
def balanced_sample_weight(labels, maxlen):
# Sort
labels = tf.sort(labels, axis=-1, direction='DESCENDING')
# Reduce each label combination to unique sequence
def reduce_concat(input, ... |
import datetime
import decimal
import json
import logging
from unittest import TestCase
import pytest
import requests
from mock import patch, Mock
from .. import alooma_pysdk as apysdk, consts, py2to3, \
pysdk_exceptions as exceptions
STRING_EVENT_REPORTED = 'reported_event'
ALL_WRAPPER_FIELDS = [getattr(consts,... |
"""GUI using QT to regenereate private key from the secrets engraved on COINPLUS SOLO"""
import sys
import os
from PyQt5.QtWidgets import QApplication, QWidget, QGroupBox, QPushButton, QGridLayout, QLabel,\
QLineEdit, QRadioButton, QHBoxLayout, QVBoxLayout, QMainWindow, QScrollArea, QMessage... |
#from pip._vendor.colorama.win32 import COORD
from _io import open
from xml.dom.expatbuilder import parseString
from ctypes.wintypes import DOUBLE
from math import sqrt
from symbol import power
# from goto import with_goto
# import goto
# from goto import _find_labels_and_gotos
# from goto import _inject_ops
# from got... |
# encoding: utf-8
from datetime import datetime, timedelta
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils.timezone import now
from dateutil.tz import tzlocal
from core.utils import slugify
from pytz import timezone
class Setup(object):
def __init__(self)... |
# -*- coding: utf-8 -*-
import codecs
import datetime
import logging
import re
import json
from google.appengine.api import memcache, users
from google.appengine.ext import ndb
class PropertyWriteTracker(ndb.Model):
_dirty = False
def __init__(self, *args, **kw):
self._dirty = False
super(PropertyWriteTracker... |
import numpy as np
import dill as pickle
import matplotlib.pyplot as plt
from scipy.sparse import csr_matrix
from numba import njit
import pygalmesh
import meshio
@njit
def _get_candidate_elements( point, ecentroids, eradius ):
"""Find all elements that could contain a point based on their bounding radii.
Thi... |
import tensorflow as tf
class TrainLogger:
def __init__(self, filepath):
self._filepath = filepath
try:
with open(filepath) as f: pass
except FileNotFoundError:
with open(filepath, 'w') as f:
f.write(','.join(['train_loss', 'validatio... |
# Gfx
"""Defines an abstract base class for a (simple) graphics interface.
The purpose of modules 'Plotter.Gfx' is to define a simple graphics
interface that can be implemented for different GUI or printing
libraries. In order to implement a driver for a certain GUI or
graphics device, the class Driver (and possibly ... |
import os
import torch
from tqdm import tqdm
import numpy as np
from scipy.stats import norm
import sklearn.preprocessing as preprocessing
import argparse
from dataset import Dataset
from model import DeepPunctuation
from config import *
parser = argparse.ArgumentParser(description='Punctuation restoration test')
pa... |
import numpy as np
import torch
from math import exp, pi, log
from torch import nn, distributions
from torch.nn import functional as F
from scipy.optimize import linear_sum_assignment
from torch.autograd import Variable
import torch.nn.init as init
from models.decoders import Discriminator
from models.layers import Lam... |
#!/usr/bin/env python
"""
Hadoop stream API emulator for python mapper/reducer
@Author: <NAME>
Created: September 19, 2014
"""
from __future__ import print_function
import os
import sys
import tempfile as tf
import shutil as su
import hseexceptions as excp
from TextInputFormat import input_formatter
from TextOutput... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""OSC message responses sent from the device."""
import ast
import re
from dataclasses import dataclass as _dataclass
from dataclasses import field
from typing import Any, Callable, Dict, Tuple, TypeVar, Union
# Pylance custom dataclass work around
_T = TypeVar("_T")
... |
from collections import defaultdict
from contextlib import contextmanager
import io
import os
import stat
from unittest.mock import MagicMock
import pytest
from hop import models
from hop.io import StartPosition
# example GCN circular from https://gcn.gsfc.nasa.gov/gcn3_circulars.html
GCN_TITLE = "GCN GRB OBSERVATI... |
import uuid
from flask import request
from flask_sqlalchemy import SQLAlchemy
sqldb = SQLAlchemy()
def generate_uuid():
return str(uuid.uuid4())
class Account(sqldb.Model):
id = sqldb.Column(sqldb.VARCHAR(255), primary_key=True, default=generate_uuid)
first = sqldb.Column(sqldb.Text, nullable=True)
... |
# Copyright 2021 DeepMind Technologies Limited
#
# 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 agr... |
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from torch.utils.data import DataLoader
import copy
import sys
import logging
import random
import itertools
import argparse
import configparser
import math
import os
import numpy as np
import re
import shutil
import time... |
import math
import numpy as np
import pandas as pd
import os
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
##Relu Output---
def relu_output(value):
if(value>=0):
return(value)
else:
return(0)
def sigmoid_output(value):
if(value>=(-709)):... |
import cyipopt
import math
import numpy as np
from scipy import sparse
from matplotlib import pyplot as plt
class IpoptSmootherProblem:
def __init__(self, Q, P, num_of_points):
self.Q = Q
self.P = P
self.num_of_points = num_of_points
self.num_of_pos_variables = 2 * num_of_points
... |
# coding=utf-8
# Copyright 2019 The Interval Bound Propagation 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://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... |
import numpy as np
import pytest
from lagom.utils import Seeder
import gym
from gym.spaces import Box
from gym.spaces import Discrete
from gym.spaces import Tuple
from gym.spaces import Dict
from gym.wrappers import ClipReward
from lagom.envs import RecordEpisodeStatistics
from lagom.envs import NormalizeObservatio... |
# Copyright 2020 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, subl... |
from __future__ import absolute_import, division, print_function
import os.path
import torch
import torch.utils.data as data
import numpy as np
from torchvision import transforms as vision_transforms
from .common import read_image_as_byte, read_calib_into_dict
from .common import kitti_crop_image_list, kitti_adjust_i... |
#-------------------------------------------------------------------------------
# *** Requires the AltaLIS V4-1 grid to function ***
#
# Name: ATS_to_DD
# Purpose: Using a script tool in ArcMap or ArcCatalog, and an input table containing ATS coordinates, output a feature class / shapefile of the po... |
"""
Collection of formatting helper functions
and the final Renderer to generate the output
"""
from .c_types import *
INDENT = " "
def to_c_string(text):
"""
Make 'text' agreeable as C/C++ string literal
:return: str
"""
text = text.replace("\\", "\\\\")
text = text.replace("\n", "\\n")
... |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
External Kernel connection widget
"""
# Standard library imports
import os.path as osp
# Third party imports
from jupyter_core.paths import jupyter_runtime_dir
... |
# -*- coding: utf-8 -*-
# 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 o... |
#!/usr/bin/env python3
import os.path
import tensorflow as tf
import helper
import warnings
from distutils.version import LooseVersion
import project_tests as tests
import matplotlib.pyplot as plt
import numpy as np
# Check TensorFlow Version
assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use Tens... |
from torch.nn.utils.prune import L1Unstructured, RandomUnstructured
from copy import deepcopy
import numpy as np
import torch
from collections import OrderedDict
from torch.nn.utils.prune import RandomStructured, LnStructured, identity
def init_for_pruning(smodel, to_be_pruned: [str], last_layer_index=-1):
# do... |
#!/usr/bin/env python
# Copyright 2014-2020 The PySCF Developers. 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
#
# U... |
# BridgeDB by <NAME>.
# Copyright (c) 2007-2009, The Tor Project, Inc.
# See LICENSE for licensing information
"""
This module has functions to decide which bridges to hand out to whom.
"""
import bridgedb.Bridges
import bridgedb.Storage
import bridgedb.Util as Util
import logging
import re
import time
from ipaddr i... |
'''
Implementations for the obi tasks
- obi clean
- obi stop
- obi build
- obi go
'''
from __future__ import print_function
import hashlib
import fabric
import os
import stat
import time
import yaml
import re
from fabric.api import env # the global env variable
from fabric.api import (local, run) # the global env var... |
from __future__ import print_function
from __future__ import division
from builtins import str
from builtins import range
from py.utils.BioUtils import *;
from py.utils.GenBankToolbox import *;
from os import walk;
import os;
#TODO: make function that processes string input of message files separated by ::: EDIT not a... |
import numpy as np
import matplotlib.pyplot as plt
def rgb2gray(rgb_image: np.ndarray) -> np.ndarray:
if rgb_image.dtype.char in np.typecodes["AllInteger"]:
rgb = rgb_image.astype(float) / 255
else:
rgb = rgb_image
r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2]
gray = 0.2989 * r + ... |
from copy import deepcopy
from os.path import join
import cv2
import matplotlib.pyplot as plt
import numpy as np
from PIL import ImageFont, ImageDraw, Image
from numpy import asarray
from highway_disagreements.get_trajectories import trajectory_importance_max_min, \
trajectory_importance_max_avg, trajectory_import... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.