text stringlengths 3.07k 22.1k |
|---|
##############################################################################
#
# Copyright (c) 2001 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS I... |
#
# Copyright (c) 2010-2016, MIT Probabilistic Computing Project
#
# Lead Developers: <NAME> and <NAME>
# Authors: <NAME>, <NAME>, <NAME>, <NAME>
# Research Leads: <NAME>, <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Lic... |
#!/usr/bin/env python3
#PYTHON_ARGCOMPLETE_OK
import logging
import itertools
from dataclasses import dataclass
from simple_parsing import Serializable
from typing import Union, Tuple
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from torchvision.utils import save_image
... |
# GPLv3 License
#
# Copyright (C) 2020 Ubisoft
#
# This program 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, either version 2 of the License, or
# (at your option) any later version.
#
# This program is dis... |
from lxml import etree
import canmatrix.formats
import decimal
class OdxReader:
def __init__(self):
self.tree = None
self.root = None
self.ns = None
self.nsp = None
self.id_links = {}
def open(self, file):
self.tree = etree.parse(file)
self.root = self.... |
import gevent.monkey
gevent.monkey.patch_all()
import bs4
import time
import threading
import json
import re
import queue
import sys
import argparse
import codecs
from . import imgfilter
from . import downloader
from .pxelem import PixivUrl, PixivImage, PixivAuthors
from . import config
from .login import login
url_... |
from typing import Tuple
import time
from ophyd import (
Device,
EpicsSignal,
EpicsSignalRO,
Component as Cpt,
FormattedComponent as FCpt
)
from bluesky import plan_stubs as bps
class VectorSignalWithRBV(EpicsSignal):
"""
An EPICS signal that uses 'pvname-SP' for the setpoint and
'pvn... |
from unittest import mock
import pytest
import pandas as pd
from hetdesrun.adapters.exceptions import (
AdapterClientWiringInvalidError,
AdapterConnectionError,
)
from hetdesrun.adapters.generic_rest.external_types import (
ExternalType,
)
from hetdesrun.adapters.generic_rest import (
load_grouped_... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable, grad
from config import load_args
from preprocess import load_data
from model import StyleGAN, Discriminator
def requires_grad(model, flag=True):
for p in model.parameters():
... |
import csv
import json
import operator
import os
import time
from unittest import TestCase
from matplotlib import pyplot as plt
from scipy.sparse.csgraph import reverse_cuthill_mckee
from config.config import PROJECT_DIR, DROPBOX_DIR
from features.similarity import similarity_strings, similarity_tf
from features.term... |
#
# tsne.py
#
# Implementation of t-SNE in Python. The implementation was tested on Python 2.7.10, and it requires a working
# installation of NumPy. The implementation comes with an example on the MNIST dataset. In order to plot the
# results of this example, a working installation of matplotlib is required.
#
# The ... |
#!/usr/bin/env python3
# Copyright (c) 2021 The Bitcoin developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test building avalanche proofs and using them to add avalanche peers."""
from decimal import Decimal
from test_f... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
"""Generate fantasy map.
See http://mewo2.com/notes/terrain/.
"""
import argparse
import time
from collections import defaultdict
import numpy as np
import matplotlib.pyplot as plt
import scipy.spatial as spl
try:
from . import erosion
from . import plot_utils as ... |
import matplotlib
from matplotlib import pyplot as plt
matplotlib.rcParams['font.size'] = 18
matplotlib.rcParams['figure.titlesize'] = 18
matplotlib.rcParams['figure.figsize'] = [9, 7]
matplotlib.rcParams['font.family'] = ['KaiTi']
matplotlib.rcParams['axes.unicode_minus']=False
plt.figure()
import os
os.environ[... |
import asyncio
import datetime
import heapq
import itertools
import logging
import sys
from collections import defaultdict
from .exceptions import ReceptorBufferError, UnrouteableError
from .messages.framed import FramedMessage
from .stats import route_counter, route_info
logger = logging.getLogger(__name__)
class ... |
import numpy as np
import pandas as pd
import logging
import json
import pickle
import random
import altair as alt
import datetime
import yaml
from itertools import chain
import narrowing_ai_research
from narrowing_ai_research.utils.altair_utils import (
altair_visualisation_setup,
save_altair,
)
from narrow... |
# Copyright 2018 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, s... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# autocorr.py - <NAME> (<EMAIL>) - Jan 2017
'''
Calculates the autocorrelation for magnitude time series.
'''
from numpy import (
sum as npsum, arange as nparange, correlate as npcorrelate,
max as npmax, median as npmedian, array as nparray, abs as npabs
)
from ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.autograd import Variable
import parse
import os
def set_learning_rate(optimizer, lr):
"""Sets the learning rate to the given value"""
for param_group in optimizer.param_groups:
param_group['lr'] = lr
clas... |
import subprocess,urllib.request,random,sys,datetime,re,os
from pathlib import Path
report = ""
def print_banner(title):
print_append_to_report("==============================\n" + title + "\n==============================\n")
def system_call(command):
return print_append_to_report(subprocess.Popen(command,stdout=... |
import threading, time, cgi, os, re
import configuration
import helper_tools as ht
from motes import motes
import utils
import sensor_data
maybeIsInSubprocess = False
forceInterrupt = False
subprocessLock = threading.Lock()
def emitCodeMansOS(code, config):
with open(os.path.join("build", "main.c"), "w") as outFi... |
"""
Equilibrium
===========
Provides
--------
* Algorithm for calculating vapor-liquid phase equilibrium.
* Algorithm for calculating binary interaction parameters.
"""
import numpy as np
from scipy import optimize
from .equations import Phase, Predict, SRK, PR
from .mixture import Mixture
# TODO: improve al... |
from ctre import CANTalon
import math
class SwerveModule:
CIMCODER_COUNTS_PER_REV: int = 80
WHEEL_DIAMETER: float = 0.0254 * 3
DRIVE_ENCODER_GEAR_REDUCTION: float = 5.43956
# The VEX Integrated encoders have 1 count per revolution, and there
# is a 1:1 corrospondence to the angular position of th... |
# coding: utf-8
from __future__ import unicode_literals
import json
import unittest
import warnings
import datetime
from mock import patch
from nose.tools import nottest
from sure import expect
from django.conf import settings
from django.core.cache import cache
from django.template import Template, TemplateSyntaxErro... |
from typing import Union, List, Tuple
from functools import partial
import torch
import torch.nn as nn
import torch.nn.functional as f
from models.SimpleLSTMAutoencoder import LSTMEncoder, LSTMDecoder
class Conv1dUnit(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride):
... |
import os
import sys
import numpy as np
import pickle
import skimage.measure
import skimage.io
from sklearn.metrics import f1_score
from sklearn.metrics import accuracy_score
from sklearn.metrics import cohen_kappa_score
from scipy.spatial.distance import directed_hausdorff
from tqdm import tqdm
import multi... |
import os
import cv2
import sys
import json
import time
import flask
import mtcnn
import base64
import logging
import pyfiglet
import argparse
import warnings
import numpy as np
import tensorflow as tf
from PIL import Image
from utils import dbase
from utils import config
from flask import Flask, request
from flask_cor... |
# import the necessary packages
import time
import cv2
import numpy
# import RPi.GPIO as GPIO
# from matplotlib import pyplot as plt
# crop_ranges are y,y1,x,x1 from top left
mask_crop_ranges = ([300,475,20,580],[0,0,0,0])
pin_crop_ranges = ([235,260, 315,340],[205,230, 290,315],[205,230,365,390],[180,205, 260,280],[... |
import os
import numpy as np
import pandas as pd
import pydicom as dcm
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import cv2
from PIL import Image
import tensorflow as tf
from tensorflow.keras import datasets
def main():
"""
"""
various_test()
def various_test():
# convert_dcm_... |
"""
@package mi.instrument.um.thsph.thsph.driver
@file marine-integrations/mi/instrument/um/thsph/thsph/driver.py
@author <NAME>
@brief Driver for the thsph
Release notes:
Vent Chemistry Instrument Driver
"""
__author__ = '<NAME>'
__license__ = 'Apache 2.0'
import re
from datetime import datetime
from mi.core.ex... |
# Copy right (c) <NAME> and <NAME> 2020. All rights reserved.
#
#
import os
import math
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn import metrics
import logging
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.optimizers import Adam
fro... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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 ... |
import pickle
from random import random
import torch
import time
import pyautogui
import gc
import numpy as np
from threading import Thread
from tqdm import tqdm
import environment
from trainer import QTrainer, RainbowTrainer, TaikoTrainer
torch.set_printoptions(sci_mode=False)
pyautogui.MINIMUM_DURATION = 0.0
pyau... |
"""
pgmerge - a PostgreSQL data import and merge utility.
Copyright 2018-2021 <NAME> (<EMAIL>)
"""
import os
import logging
from typing import Any, List, Tuple, Optional, cast
from .utils import replace_indexes
from .db_config import TablesConfig, SubsetConfig
DEFAULT_FILE_FORMAT = "FORMAT CSV, HEADER, ENCODING 'UTF... |
import csv
import random
from functools import partial
from typing import Callable, Optional
from pdb import set_trace as st
import os
import random
import pandas as pd
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union
import numpy as np
import tensorflow as tf
from foolbox.attacks import (
FGSM... |
#!/usr/bin/env python3
######################################################
## Python implementation of the following examples ##
## https://github.com/IntelRealSense/librealsense/blob/master/doc/post-processing-filters.md
## https://github.com/IntelRealSense/librealsense/tree/master/wrappers/opencv/depth-filter
##... |
from heapq import heappush, heappop
from typing import Tuple, Generator, Callable
from hwt.doc_markers import internal
from hwt.hdl.value import Value
from hwt.pyUtils.uniqList import UniqList
from hwt.simulator.hdlSimConfig import HdlSimConfig
from hwt.simulator.simModel import mkUpdater, mkArrayUpdater
from hwt.simu... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Exaplanation: sumo_dashboard_export will take a list of dashboards and export results
Usage:
$ python sumo_dashboard_export [ options ]
Style:
Google Python Style Guide:
http://google.github.io/styleguide/pyguide.html
@name sumo_dashboard... |
from abc import ABC
import bisect
from datetime import datetime, timedelta
from typing import List, NamedTuple, Optional, Tuple
from astropy.units import Quantity
from astropy import units as u
from astroquery.jplhorizons import Horizons
from dateutil.parser import parse
from dateutil.tz import tzutc
from salt_finder... |
import csv
import io
import random
from typing import Callable, Dict, List, Tuple, Union
from flask import Config
from webapp.dto import (
AppConfig,
ExternalTaskDto,
GroupDto,
TaskDto,
TaskStatusDto,
VariantDto
)
from webapp.models import FinalSeed, Group, Message, Task, TaskStatus, Variant
f... |
def readfile():
str_maze = []
file = open(f"C:\\input_hw1.txt", 'r', encoding='utf-8')
with file as f:
lines = f.readlines()
txt = [[i.replace("\n", "")]for i in lines]
for i in range(0, len(txt)):
middle_list = txt[i][0].split(" ")
if "" in middle_list:
... |
import tensorflow as tf
from tensorflow.python.framework.ops import EagerTensor
from keras import backend
from keras.utils.control_flow_util import smart_cond
from keras.utils.generic_utils import register_keras_serializable
from keras.utils.losses_utils import ReductionV2 as Reduction
from .weighted_wrapper import Wei... |
'''
Created on 14.01.2021
MIT License
Copyright (c) 2021 <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, cop... |
## License: Apache 2.0. See LICENSE file in root directory.
## Copyright(c) 2021 Intel Corporation. All Rights Reserved.
#####################################################
## auto calibration ##
#####################################################
import argparse
import json
import ... |
import torch.nn as nn
import config as cfg
import torch.nn.functional as F
from torchvision import datasets,models
import torch
from facenet_pytorch import MTCNN, InceptionResnetV1, fixed_image_standardization,training
from head import ArcFace, CirriculumFace
import pickle
from backbone.irse import Backbone
from backbo... |
import streamlit as st
from bert_serving.client import BertClient
from client.elastic_client import ElasticClient
from client.utils import get_elasticsearch_vector
import pandas as pd
import plotly.graph_objects as go
from data_utils import compute_sbert_vectors, compute_bert_vectors
bc = BertClient()
# default ES: c... |
import json
import click
import cv2
import nibabel as nib
import numpy as np
import torch
from pathlib2 import Path
from torch.utils.data import DataLoader, SequentialSampler
from tqdm import tqdm
import utils.checkpoint as cp
from dataset import KiTS19
from dataset.transform import MedicalTransform
from network impo... |
"""
This script is intended to be used with Google Appengine. It contains
a number of demos that illustrate the TropoPython API.
"""
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import cgi
import logging
import ciscotropowebapi
import GoogleS3
from xml.dom import minidom
from go... |
#to test the code run:> python ./knapsack.py -d H_Beds.csv -t 150000 -n 3
#node can be a city, hospital, distribution center, store, or etc.
#capacity is the maximum content that can be allocated at the node
#e.g. sick people, people it can serve, vaccines or products it can hold;
#status is the currently utilized... |
from collections import namedtuple
from datetime import date
from datetime import datetime
from datetime import timedelta
from mandarin_twitter_bot.aws_client import AWSClientError
from mandarin_twitter_bot.aws_client import get_and_delete_unprocessed_word
from mandarin_twitter_bot.aws_client import get_earliest_tweet_... |
# Copyright (C) 2015-2020 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from collections import namedtuple
import re
import cxxfilt
from operator import itemgetter
# Groups for the FRAME_PATTERN below
# 1 - frame number + one space
# 2 - function name + optional arguments
# 3 - rest of the line
# 4 - module... |
import os.path
import math
import SofaPython.Tools
import SofaPython.units
from SofaPython.Tools import listToStr as concat
from SofaPython import Quaternion
import Sofa
class Image:
""" This class proposes a high-level API to build images. It support multiple meshes rasterization.
"""
class Mesh:
... |
import abc
import functools
import warnings
from typing import Sequence, Union
import numpy as np
class Manifold(metaclass=abc.ABCMeta):
"""Riemannian manifold base class.
Abstract base class setting out a template for manifold classes.
Args:
name: String representation of the manifold.
... |
# requires python-osc
from pythonosc import osc_message_builder
from pythonosc import udp_client
import plugin_interface as plugintypes
import numpy as np
from scipy.signal import welch
from scipy.stats import zscore, norm
from sklearn.base import BaseEstimator, TransformerMixin
import time
from math import log
from s... |
#!/usr/bin/env ipython
# author: <NAME>
# get stats about endpoints and so on
# to report: for each patient
# -- # events of each level (unknown, 0, 1, 2, 3, maybe_1, etc.)
# -- average duration of each level
# -- time to first event of each type
# -- fraction of time spent in each level
# -- # deteriorations
# -- to... |
import logging
from nlglib.macroplanning import Document, Paragraph
from nlglib.microplanning import is_clause_type
from nlglib.features import category, NUMBER, GENDER, CASE, TENSE, NEGATED, MODAL, FeatureGroup
from nlglib.utils import flatten
__all__ = ['Realiser']
# a complementiser group
complementiser = Feature... |
#
# The contents of this file are subject to the terms listed in the LICENSE file you received with this code.
#
# Project: Atmosphere, iPlant Collaborative
# Author: <NAME>
# Twitter: @seungjin
# GitHub: seungjin
#
from django.http import HttpResponse
from django.template import Context
from django.template.loader im... |
__version__ = '0.5.7'
from symgroupy import symgrouplib
import numpy as np
def _get_connectivity_vector(connect, na, central_atom=0):
matrix = np.zeros((na, na), dtype=float)
try:
for pair in connect:
matrix[pair[0]-1, pair[1]-1] = 1.0
matrix[pair[1]-1, pair[0]-1] = 1.0
... |
import operator
import os
import shutil
from functools import reduce
Seasons = {"Spring": ["Spring"],
"Summer": ["Summer"],
"Fall/Autumn": ["Fall", "Autumn"],
"Winter": ["Winter"]}
SeasonSet = set(reduce(operator.add, Seasons.values()))
def box(name, dir):
'''
Make a zip arc... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
##############
# GaudiMM: Genetic Algorithms with Unrestricted
# Descriptors for Intuitive Molecular Modeling
#
# https://github.com/insilichem/gaudi
#
# Copyright 2017 <NAME>, <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... |
import numpy as np
from numpy import expand_dims
from keras.models import load_model
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.backend import resize_images
from matplotlib import pyplot
from matplotlib.patches import Rectangle
import cv2
# load and pre... |
import calendar
import datetime
from django.db.models import Q, Sum
from django.db.models.signals import post_save
from django.dispatch import receiver
from model_utils.models import SoftDeletableModel, TimeStampedModel
from schedule.settings import MEDIA_URL
from django.contrib.auth.models import User, Permission
fr... |
# -*- coding: utf-8 -*-
import os
import cv2
import time
import random
import argparse
import numpy as np
from skimage.color import hsv2rgb
from scipy.interpolate import interp1d
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation
from tensorflow.keras.initializers impo... |
import functools
import os
from django.conf import settings
from django.core.checks import Warning, register
from django.db import models
from django.utils.translation import ugettext as _
from imagekit import ImageSpec
from imagekit.models.fields import ImageSpecField
from imagekit.processors import ResizeToFit, Res... |
from __future__ import division
import sys
import numpy as np
import wave
from contextlib import closing
import audiolabel
# Algorithms to detect synchronization pulses.
NORM_SYNC_THRESH = 0.2 # normalized threshold for detecting synchronizaton signal.
MIN_SYNC_TIME = 0.0005 # minimum time threshold must be exceed... |
from automateDJL import weather
import platform
import logging
import logging.config
import configparser
from datetime import datetime
import os
import sys
import getopt
import math
from datetime import time, timedelta, datetime, date
import http.client
import json
# todo - update NAS to run daily
# todo - web site to... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2016, Akamai Technologies
# Author: <NAME>
"""
Usage:
c2e [options]
c2e -h | --help
c2e --version
Options:
-h, --help Print this help
--version Show version number
-v, --verbose Print verbose... |
"""
pyart.aux_io.read_gamic
=======================
Utilities for reading gamic hdf5 files.
.. autosummary::
:toctree: generated/
read_gamic
_h5_to_dict
_h5_moments_to_dict
"""
import datetime
import h5py
import numpy as np
from ..config import FileMetadata
from ..io.common import make_time_unit_... |
''' Source: MBPO/mbpo/models/fake_env.py '''
import numpy as np
import torch as T
# T.multiprocessing.set_sharing_strategy('file_system')
class FakeWorld:
"""
source: https://github.com/Xingyu-Lin/mbpo_pytorch/predict_env.py
"""
def __init__(self, model, env_name="Hopper-v2", model_type='pytorch'):
... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import random
import numpy as np
import torch
import torchvision
from torchvision.transforms import functional as F
class Compose(object):
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, image, ta... |
import re
from xml.etree import ElementTree
"""Everything to do with generating ROBLOX instances as XML.
This module is for constructing ROBLOX Models from a folder structure and Lua
files, as well as importing existing Models when compiling.
"""
def _is_lua_comment(line):
"""Checks if a line of text is a Lua co... |
#!/usr/local/bin/python3
import os
import time
import csv
from subprocess import check_call, Popen, STDOUT
# CCS21 Experiments
OBLIVC_TESTS_DIR = "/Users/ian/Projects/obliv-c-extra/test/oblivc"
SYMPHONY_DIR = "/Users/ian/Projects/symphony-lang"
SYMPHONY_INPUTS_DIR = "{0}/{1}".format(SYMPHONY_DIR, "examples-input")
... |
"""An implementation of the old classic game, Minesweeper.
The objective is to pick cells in a grid where you don't believe there is a
mine (bomb). If you pick incorrectly you loose the game because the mine goes
off (it explodes).
TODO
- Add a clock/timer?
- Add handling for intergrating a user interface.
"""
impor... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 30 10:58:13 2017
@author: HGY
"""
import sys
import numpy as np
from statistics import median
from PIL import Image
import matplotlib.pyplot as plt
#%%
def MultipleStitch(Images, Trans, fileName='../results/pano.jpg'):
'''
MultipleStitch
This function stit... |
import logging
import os
import shutil
from pathlib import Path
from subprocess import CalledProcessError
import celery
import pandas as pd
from django.conf import settings
from django.db import IntegrityError
from library.django_utils.django_file_utils import get_import_processing_dir
from library.log_utils import l... |
"""
Parse disco_aws alarm configuration.
"""
import logging
import copy
from boto.ec2.cloudwatch import MetricAlarm
from . import DiscoAutoscale
from .disco_config import read_config
from .exceptions import AlarmConfigError
from .disco_aws_util import is_truthy
from .disco_elb import DiscoELB
logger = logging.getLo... |
# -*- coding: utf-8 -*-
import os
import sys
import cv2
import dlib
import numpy as np
import socket
from imutils import face_utils
from scipy.spatial import distance
import time
DEBUG = False
HOST = '127.0.0.1'
PORT = 12345
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
cascade = cv2.CascadeClassifier("ha... |
import logging
import hjson
import pathlib2
import nog.bdb
import nog.exc
log = logging.getLogger(__name__)
class BdbWrapper(object):
"""Wrap a minter BerkeleyDB and provide more convenient access to the values used by EZID.
Values are available as attributes with more descriptive names and strings parsed ... |
from __future__ import annotations
from kivy.app import App
from kivy.core.audio import Sound
from kivy.core.text import DEFAULT_FONT, LabelBase
from kivy.core.window import Window
from kivy.properties import ObjectProperty
from kivy.resources import resource_add_path
from kivy.uix.boxlayout import BoxLayout
from kivy... |
from abc import ABC, abstractmethod
from typing import Any, List, Tuple, Union, Callable, Optional, Sequence, TYPE_CHECKING
from itertools import chain
from scanpy import logging as logg
from scipy import ndimage as ndi
import numpy as np
from skimage.util import invert as invert_arr, img_as_float
from skimage.featu... |
# coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import logging
import math
from os.path import join as pjoin
import torch
import torch.nn as nn
import numpy as np
from torch.nn import CrossEntropyLoss, Dropout, Softmax, Linear, ... |
import datetime
import logging
import os
import pickle
import random
import numpy as np
import lmdb as lmdb
import torch
from torch.nn.utils.rnn import pad_sequence
from transformers import AutoTokenizer, AutoModel
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.dataloader import default_colla... |
import datetime
import pandas as pd
import geopandas as gpd
import numpy as np
import sys
from tqdm.auto import tqdm
import time
import logging
from builtins import isinstance
logging.basicConfig()
logger = logging.getLogger('geopandas_coloc')
logger.setLevel(logging.INFO)
if sys.gettrace():
logger.setLevel(loggi... |
"""
Some metrics for comparing two waveforms (e.g., original waveform against reconstructed)
"""
import tensorflow as tf
# import numpy as np
# from scipy.stats import pearsonr
# def batch_pearson(y_true, y_pred):
# assert y_true.shape == y_pred.shape, "Predicted and labels have different shapes"
# return np.... |
import tensorflow as tf
from sklearn.utils import shuffle
################## Place Holders Example #################
'''
placeholder nodes.
These nodes are special because they don’t
actually perform any computation, they just
output the data you tell them to output at
runtime. They are typically used to pass the ... |
import pickle
import os.path
import numpy as np
def get_metadata(experiment_id):
a = experiment_id.split('_')
dataset_name = a[0]
class_spec = dataset_name[-4:]
if '-C' in class_spec:
target_class_index = int(class_spec[class_spec.find('C')+1:])
dataset_whole = dataset_name[:dataset_name.find('-C')]
else:
t... |
#
# Copyright (c) nexB Inc. and others. All rights reserved.
# ScanCode is a trademark of nexB Inc.
# SPDX-License-Identifier: Apache-2.0
# See http://www.apache.org/licenses/LICENSE-2.0 for the license text.
# See https://github.com/nexB/scancode-toolkit for support or download.
# See https://aboutcode.org for more in... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from math import ceil
import re
from smtplib import SMTPException
from boards.models import Board, Reply
from boards.table import BoardTable
from core.utils import error_page
from django.conf import settings
from django.contrib.admin.views.decorators im... |
from random import randint
from numpy import array
from numpy import argmax
from pandas import concat
from pandas import DataFrame
import csv
import numpy as np
from tensorflow.python.keras.models import Sequential, load_model
from tensorflow.python.keras.layers import LSTM
from tensorflow.python.keras.layers ... |
import argparse
import os
import torch
from torch.utils.data import DataLoader
from torch import optim
import numpy as np
from data.syn_dataset import MUSIC_Dataset
from model.base_model2 import resnet18
from model.location_model import Location_Net_stage_two, Location_Net_stage_one
from sklearn import cluster, metri... |
"""
File contains visualization methods.
"""
import os
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from typing import Dict
from pathlib import Path
from scipy.signal import savgol_filter
from tensorflow.keras.callbacks import History
from pre_processing.raw_features im... |
# -*- coding: utf-8 -*-
##
# TRACK 9
# DAFT HOLLYWOOD
# <NAME> (<EMAIL>)
# This file builds the sequence file for use with ChucK from the data supplied
##
# Library dependancies
import collections
import csv
import json
import math
import os
from pprint import pprint
import sys
import time
# Config
BPM = 150 # Beats ... |
import csv
import random
from functools import partial
from typing import Callable, Optional
from pdb import set_trace as st
import os
import random
import pandas as pd
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union
import numpy as np
import tensorflow as tf
from foolbox.attacks import (
FGSM... |
"""Hexsphere generator"""
import math
def _normalize(x, y, z):
magnitude = math.sqrt(
x * x +
y * y +
z * z
)
return (
x / magnitude,
y / magnitude,
z / magnitude
)
class Vector3(object):
__slots__ = ['x', 'y', 'z']
def __init__(self, x, y, z)... |
# Version 2 of data ingestion Python script
'''
The following script does the following:
- checks for cloned Panacea Lab Twitter repo; if not present in
- current directory, clones the Repo
- pulls most recent data from Panacea repo, to ensure contents
- are up-to-date
- creates list of daily folders located in Panacea... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 3 16:59:59 2020
@author: khyeon
"""
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import pickle
from calibration import calibration, cal_undistort, unwarp
image = mpimg.imread('test_images/test1.jpg... |
"""
Implements the Azran-Ghahramani clustering algorithm outlined in the
paper "A New Approach to Data Driven Clustering", which we refer to as
"the paper".
"""
import itertools
import numpy as np
import random
from regimedetection.src.metrics import kl_divergence
from typing import Any
from typing import Callable
f... |
"""Application configuration parsing."""
from __future__ import annotations
import enum
import pathlib
import re
import shutil
import typing
from typing import Sequence, Type, TypeVar
import ruamel.yaml
import app.utils
import model
import ui.config
import ui.widgets
# Configuration paths
CONFIG_FILE = pathlib.Pa... |
import csv
import glob
import os
import sys
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
from os.path import dirname, abspath
import plot_results
def merge_csv(files_to_merge, merged_name):
combined_csv = pd.concat([pd.read_csv(f) for f in files_to_merge... |
from scipy import spatial
import numpy as np
from testing import forward_model
from testing import plot_results
from testing import image_processing
import os
def detect(img):
"""
Detects an adversarial example if one exists
Takes in a PIL image. Returns True if the image is an adversarial example
"""
orig_vec... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.