text stringlengths 3.07k 22.1k |
|---|
# -*- coding: utf-8 -*-
"""
Python program for measureing the run time for GR4J model
"""
import numpy as np
from numba import jit
import time
import os
# Values of the S curve (cumulative HU curve) of
# GR unit hydrograph UH1
def SS1(I,C,D):
FI = I
if FI <= 0.0:
SS1 = 0.0
elif FI < C:
S... |
import numpy as np
import os
from functools import partial
import logging
# Used to set default value for workers
from multiprocessing import cpu_count
import naturalselection as ns
class NN(ns.Genus):
''' Feedforward fully connected neural network genus.
INPUT:
(int) max_nm_hidden_layers
(... |
# Checks for proper python version
# Imports
import sys
import os
import ctypes
import urllib.request
import requests
import mimetypes
import platform
import math
import subprocess
import praw
import progressbar
import configparser
import prawconfig
# Checks system version
if sys.version_info[0] != 3 or sys.version_... |
import datetime
import math
from functools import reduce
import statistics
import numpy as np
import pandas as pd
from pandas.plotting import scatter_matrix
from sklearn.metrics import r2_score, mean_squared_error,mean_absolute_error
from sklearn.model_selection import train_test_split
from sklearn import linear_model... |
#This program parses in a list of french verbs and
#quizzes the user on conjugations of that verb in the desired tense
from graphics import *
from Verb import *
#Generates the title screen
def titleScreen():
win = GraphWin("Verb Conjugater", 600, 400)
win.setBackground("light blue")
#title text
title... |
import math
import numpy as np
R = 6378.1 #Radius of the Earth in Km
''' From 1 coordinate point, a set distance and the angle we get the 2nd coordinate point. The
angleRad variable is usually know as bearing (in RAD unit) '''
def getCoordinatePoint(originLat, originLon, angleRad, distance):
originLat = np.deg2r... |
# coding: utf8
import itertools
from kafkaka.define import (
DEFAULT_SOCKET_TIMEOUT_SECONDS,
DEFAULT_KAFKA_PORT,
DEFAULT_RETRY_TIMES,
)
from kafkaka.define import (
KafkaError,
ConnectionError,
LeaderNotAvailable,
UnknownTopicOrPartition,
check_and_raise_error,
)
from kafkaka.conn import... |
import cv2
import scipy.io
import pickle
import numpy as np
# Class containing a configuration of histograms for a quant level
class HistogramConfig:
# so here we have the default parameters for the testing class
# otherwise we siply take the passed parameters
# this is defined as the instance variable
... |
#!/usr/bin/env python3
import os
import json
from keras_cv_attention_models.coco import data, losses
from keras_cv_attention_models.imagenet import (
compile_model,
init_global_strategy,
init_lr_scheduler,
init_model,
train,
)
def parse_arguments(argv):
import argparse
parser = argparse.A... |
"""
Created on 2021.06.03 16:08:57
Author : <NAME>
"""
# %env JAX_ENABLE_x64=1 # not sure what this does yet, but it might be important
import jax.numpy as jnp # differentiable numpy library
from jax import numpy as jnp
from jax.numpy.fft import fft,ifft,fftshift,ifftshift,rfft,irfft
from jax import custom_jvp
from ... |
import os
import sys
import csv
import time
import argparse
import logging
import pickle
import yaml
import numpy as np
import pandas as pd
from random import shuffle
from sklearn.metrics import roc_auc_score, roc_curve
from trackml.score import score_event
import trackml.dataset
# import matplotlib; matplotlib.use(... |
import functools
import math
from typing import Any, Callable, Optional, Tuple, Union
import torch
import torch.nn as nn
from torch import Tensor
from torch import linalg as LA
from torch.nn import Parameter
from torch.nn.utils import spectral_norm, weight_norm
from firewood import utils
from firewood.layers.linear i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 6 10:57:34 2021
@author: <NAME>
"""
import sys
import os
import glob
sys.path.append(os.getcwd())
sys.path.append(os.getcwd()+'/scripts/')
import warnings
warnings.filterwarnings('ignore')
from dmg.deeplearning.generativeModel import Generativ... |
import itertools
import re
from .common import InfoExtractor
from ..utils import (
int_or_none,
str_to_int,
try_get,
url_or_none,
unified_strdate,
parse_duration,
)
class TedBaseIE(InfoExtractor):
_VALID_URL_BASE = r'https?://www\.ted\.com/(?:{type})(?:/lang/[^/#?]+)?/(?P<id>[\w-]+)'
... |
"""
Contains a modeladmin class that shows links to all related items in its change_view.
If you want to use :class:`InvisibleModelAdmin` make sure easymode comes before
``django.contrib.admin`` in the ``INSTALLED_APPS`` because it has to
override admin/index.html to make it work.
"""
from django.http import HttpResp... |
import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.web import StaticFileHandler
from tornado.web import Application, RequestHandler
from tornado.options import define, options
import socket
import torna... |
from aeternity.signing import Account
from aeternity import transactions, exceptions, identifiers as idf, hashing
import pytest
from pytest import raises
import json
from munch import Munch
def _execute_test(test_cases, NODE_CLI):
for tt in test_cases:
# get a native transaction
txbn = transactio... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Fetching YouTube video metadata given a video id.
Feature set: vid, title, channel_id, keywords, category, description, duration, publish_date, snapshot_pt_time, view_count, num_like, num_dislike, transcript, num_comment, comment_list
Usage: python 9_scrape_youtube_vi... |
# File: agreement.py
# Template file for Informatics 2A Assignment 2:
# 'A Natural Language Query System in Python/NLTK'
# <NAME>, November 2012
# Revised November 2013 and November 2014 with help from <NAME>
# Revised November 2015 by <NAME>
# Revised October 2017 by <NAME> with help from <NAME>
# PART C: Syntax an... |
# -*- coding:utf-8 -*-
# python >= 3.6
# used with perf_level=3 and show_table_properties is on
import sys
import math
skip_thread=[]
# for jitter
# now we monitor block_read_time/count jitter
skip_start=60
def parse_perf_context(line):
metrics = {}
fields = line.replace(',', '').replace('=', '').split()[2:]... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import utool as ut
import re
from itertools import combinations
#import sys
print, rrr, profile = ut.inject2(__name__, '[rules]')
# TODO: remove static class. just use the module
#INF = sys.maxint
#HAS_NUMPY = F... |
from ifaint import *
import os
# Fixme: Duplicates test-save-svg.py. Generalize. :)
# Fixme: Also totally fails.
def style_lw1(obj):
obj.linewidth = 1
def style_lw2(obj):
obj.linewidth = 2
def style_lw20(obj):
obj.linewidth = 20
def style_none(obj):
obj.fillstyle = 'none'
obj.l... |
""" Generate modern Python clients from OpenAPI """
from __future__ import annotations
import json
import shutil
import subprocess
import sys
from pathlib import Path
from typing import Any, Dict, Optional
import httpx
import yaml
from jinja2 import Environment, PackageLoader
from openapi_python_client import utils
... |
from PyQt5.QtGui import QPixmap, QIcon, QFont, QFontMetrics, QPainter
from PyQt5.QtCore import Qt, QRectF
from PyQt5.QtWidgets import QApplication, QFileDialog, QDialog
from os.path import join, expanduser, splitext
from sys import argv, exit
from os import remove
from base64 import b64decode
import numpy as np
... |
import itertools
import os.path as osp
import pandas as pd
import numpy as np
import torch
import torch.nn.functional as F
import torch.nn as nn
from torch_geometric.datasets import TUDataset
import torch_geometric.transforms as T
from torch_geometric.nn import ARMAConv,AGNNConv,global_mean_pool
from torch_ge... |
import lms_code.lib.rep2 as rep2
import lms_code.plots.plot_all as lms_plot
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.tri as mtri
# from matplotlib.mlab import griddata
from scipy.interpolate import griddata
cmap = plt.cm.coolwarm
cntr_opts = [lambda levels: {
'levels': levels,
'exte... |
""" Main Flask module to run the application and deals with alarms and notifications
This module is the main module that uses the Flask Library to run this python code on the HTML
Template as well as directly inject and interact with the Interface such as creating, deleting and
announcing alarms with relevant text not... |
# -*- coding: utf-8 -*-
from __future__ import division, absolute_import, print_function
from .. import __author__, __version__
from ..core import np as np
import operator as op
class Funlib(object):
""" Funlib
This class must be loaded by xl2py.core.processor as Funlib to parse
simple lambda-conversion r... |
import os
import errno
import subprocess
import math
from collections import defaultdict
import xml.etree.ElementTree as ET
from .settings import Settings, Defaults
from .utils import ProgressBar, Symbol
# RRD types
DATA_TYPES = {
'a': 'ABSOLUTE',
'c': 'COUNTER',
'd': 'DERIVE',
'g': 'GAUGE',
}
def r... |
"""
Created on 5 Jul 2017
@author: gavin
"""
from lib.core import settings
from lib.core.log import CustomLogger
from http.client import HTTPConnection, HTTPResponse
from io import StringIO
from OpenSSL import SSL
import collections
import socket
import datetime
import logging
import hashlib
logging... |
"""This is a model to produce dendrograms of the dtm."""
import math
from typing import NamedTuple, Optional
import pandas as pd
import plotly.figure_factory as ff
from plotly.graph_objs.graph_objs import Figure, Scatter
from plotly.offline import plot
from scipy.cluster.hierarchy import linkage
from scipy.spatial.di... |
import requests
import pandas as pd
import numpy as np
import json
import time
import warnings
import logging
import re
import ConfigParser
import os
import sys
environment = sys.argv[1]
root = os.path.dirname(os.path.abspath(__file__))
# changing working directory
os.chdir(root)
# getting paths from config file
confi... |
from typing import Mapping
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import Http404, JsonResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, redirect, render
from django.template.defaultfilters i... |
# third-party imports
from flask import Flask, request, abort, jsonify
from flask_cors import CORS
import random
# local imports
from config import app_config
from models import setup_db, Question, Category
QUESTIONS_PER_PAGE = 10
# method for paginating questions
def paginate_questions(selection):
page = reque... |
import pysurvive
import numpy as np
import matplotlib.pyplot as plt
from functools import partial
import math
from collections import defaultdict
def insert_blanks(v, time_s = .1):
rtn = []
last_time = None
for row in np.transpose(v):
t = row[0]
val = row[1]
if last_time is not None... |
# -*- coding: utf-8 -*-
#
# TARGET arch is: ['-I/usr/lib/clang/7/include/']
# WORD_SIZE is: 8
# POINTER_SIZE is: 8
# LONGDOUBLE_SIZE is: 16
#
import ctypes
class AsDictMixin:
@classmethod
def as_dict(cls, self):
result = {}
if not isinstance(self, AsDictMixin):
# not a structure, a... |
import os
import math
from numpy import random
import numpy as np
from scipy import ndimage
from skimage import measure, transform
from .common import BBoxCalc
from keras import layers, models, callbacks
from keras.layers import LeakyReLU, BatchNormalization
def cell_shape_images(img):
#number of objects
cellN... |
import msgpack
class ValidationError(Exception): pass
class InternalTypeError(Exception): pass
class Descriptor(object):
name = None
def __get__(self, instance, owner):
return instance._values.get(self.name, None)
def __set__(self, instance, value):
value = self._validate(value)
... |
import errno
import os
import shutil
import string
import re
import tempfile
import uuid
from sphinx.util.compat import Directive
from docutils import nodes
from docutils.parsers.rst import directives
from IPython.config import Config
from IPython.nbconvert import html, python
from IPython.nbformat import current as nb... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
stats.py - a script to collect statistics about the wiki.
usage:
python pwb.py stats [OPTIONS]
List of parameters
-sql The SQL query that will be executed to get the statsistics. These
statistics will then be saved on wiki as a table.
-out ... |
# filter schmid et al 2005 microarray conditions
import argparse
import os
import pandas as pd
import tspex
def parse_args(args):
parser = argparse.ArgumentParser(
description="filter_microarray_conditions"
)
parser.add_argument(
"input_file",
type=str,
help="Input locati... |
import sys
import collections
import random
import numpy
import os
import cPickle
import math
import operator
import scipy
import gc
import config_parser
from model import WordPairClassifier
def read_dataset(dataset_path):
dataset = []
with open(dataset_path, 'r') as f:
for line in f:
line... |
# ------------------------------------------------------------------------------------
# BaSSL
# Copyright (c) 2021 KakaoBrain. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------------------
import l... |
from uwsgi_tasks import *
from .models import *
from time import sleep
from requests import get
import transmissionrpc
from pprint import pprint
from base64 import b64decode
from urllib.parse import urlencode, quote
import PTN
from imdbpie import Imdb
import os
import subprocess
import requests
import magic
import json... |
from typing import Tuple
from typing import Optional
from typing import Union
import logging
import os
import gc
import numpy as np
import torch
import torch.nn as nn
import torch.backends
from torch.autograd import Variable
from torch.optim import Adam
from torch.optim import Optimizer
from torch.utils.tensorboard ... |
import pytest
import typing
from datetime import datetime as dtime
import enum
from attr import dataclass, attrib
import ctor
@pytest.fixture(scope="module")
def obj_converter_factory() -> ctor.ObjectConverterFactory:
return ctor.ObjectConverterFactory()
@pytest.fixture
def context():
return ctor.JsonSeri... |
import sec
import mp
import sys
import join_tiles
import numpy as np
import collada as dae
from intersect import get_z
"""
scene -> nodes (position) -> geometry nodes -> geometry data
"""
def create_geometry(v_arr, t_arr, altitude, tiles_count, water_mask=None):
vert_buf = []
norm_buf = []
for i, ve... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Flask, request, render_template, jsonify
import mysql.connector
import tweepy
import smtplib
from flask_mail import Mail, Message
import re
app = Flask(__name__)
app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAM... |
import os
from itertools import zip_longest
import pygame
from gym_pomdp.envs.coord import Coord, Tile
PATH = os.path.split(__file__)[0]
FILE_PATH = os.path.join(PATH, 'assets')
class GuiTile(Tile):
_borderWidth = 2
_borderColor = pygame.Color("grey")
def __init__(self, coord, surface, tile_size=100):
... |
"""Implementation of classic adaptive controllers and methods"""
import copy
import numpy as np
from collections import namedtuple
PressurePhase = namedtuple('PressurePhase', 'id time yellow')
def is_controller_periodic(ts_type):
if ts_type in ('rl', 'random', 'static', 'webster', 'centralized'):
return... |
import copy
import math
from collections import OrderedDict
import numpy as np
import torch.nn as nn
from mmcv.cnn.bricks import Swish
from ..builder import BACKBONES
DEFAULT_BLOCKS_ARGS = [{
'kernel_size': 3,
'repeats': 1,
'filters_out': 16,
'expand_ratio': 1,
'id_skip': True,
'strides': 1,
... |
import torch
import numpy as np
import pandas as pd
from tqdm import tqdm
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
# Local imports
from isonet.models import *
from isonet.models.resnet import BasicBlock
# Taken from
# The Singular Values of Convolutional Layers, Sedghi ... |
import time
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
import os
import git
import datetime
import Corona
watchDirectory = r"D:/DATA/Protect/IMPORTANT/Python/Harvard Course/HomeWork/Data/Corona by Johns Hopkins/csse_covid_19_data/csse_covid_19_time_series"
... |
from __future__ import print_function
import copy
import logging
import pickle
import sys
try:
from configparser import ConfigParser
except ImportError:
from ConfigParser import ConfigParser
import gym
import numpy as np
# Our agent types
from corerl.callbacks import CallbackList, make_callb... |
import os
from os.path import join as opj
from re import findall
import glob
import gdal
import logging
import itertools
from tempfile import TemporaryDirectory
from ost import Sentinel1Scene
from ost.helpers.utils import _create_processing_dict
from ost.multitemporal.utils import mt_extent, mt_layover
from ost.multit... |
#!/usr/bin/python
########################################################################################################################
#
# Copyright (c) 2014, Regents of the University of California
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permi... |
import numpy as np
import pytest
from geonotebook.annotations import Rectangle
from geonotebook.wrappers import RasterData, RasterDataCollection
from . import wrappers_data
from .conftest import enable_mock
def test_name(coords):
assert coords.name == "coords"
def test_bad_filetype():
with pytest.raises(N... |
# MIT License
#
# Copyright (c) 2019. <NAME> and <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, mo... |
import __builtin__
import math
import copy
import types
import llvm.core
import numpy as np
# from numpy.ctypeslib import _typecodes
import numba
from numba import llvm_types
from numba.minivect.minitypes import *
from numba.minivect.minitypes import map_dtype
from numba.minivect import minitypes
from numba.minivect.... |
# coding=utf8
class word(object):
"""docstring for Word"""
epsilon = None
def __init__(self, x, w):
if isinstance(x, word):
if w != x.w:
raise TypeError("word: wordsize of %d (%d) does not match with the given wordsize %d" % (x.x, x.w, w))
x = x.x
... |
import logging
from collections import OrderedDict, namedtuple
from datetime import date, datetime, timezone, timedelta
import numpy as np
import pandas as pd
from flask import current_app
from google.oauth2 import service_account
from googleapiclient.discovery import build
from .helpers import parse_timestamp_str
fr... |
"""
Class for reading and decoding the Coutrot1 [1] and Coutrot2 [2] datasets
[1] <NAME>., & <NAME>. (2014).
How saliency, faces, and sound influence gaze in dynamic social scenes.
Journal of vision, 14(8), 5-5.
[2] <NAME>., & <NAME>. (2015, August).
An efficient audiovisual saliency model to infer eye p... |
from flow.controllers.imitation_learning.run import *
from examples.train import *
def parse_args(args):
"""Parse training options user can specify in command line.
Returns
-------
argparse.Namespace
the output parser object
dict_args
dictionary version of the argparse
"""
... |
__all__ = ["User", "Room"]
import asyncio
from typing import (
TYPE_CHECKING,
Any,
Dict,
Iterable,
List,
Mapping,
MutableMapping,
NamedTuple,
Optional,
Union,
)
from aiohttp import ClientResponseError, web
from aiohttp_spotify import SpotifyAuth
from .auth import call_api, upd... |
from __future__ import print_function
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
from data import *
from data import VOC_CLASSES as labelmap
import torch.utils.data as data
from ssd import build_ssd
from eval import test_net
from train import train_epoch... |
import os
import re
import sys
import json
import shlex
import logging
import datetime
import subprocess as sp
from .settings import DEFAULT_CONFIG, load_video_config
from .exceptions import (
AudioTranscodeError,
PackingError,
VideoProbeError,
VideoStreamError,
VideoTranscodeError
)
SETTINGS_PREF... |
"""
Caching functions and decorators
"""
# Copyright 2021 Benedat LLC
# Apache 2.0 license
import time
import os
from os.path import exists, abspath, expanduser, join, exists
import shutil
from typing import Optional
import json
import binascii
from joblib.memory import Memory
from s3fs import S3FileSystem
from jobl... |
from math import *
import numpy as np
from tools import integrate
# Index parameters
indparams = {'NaID_classic':
{'w1': {'ww0': 5895.92, 'dww': 0.5}, # Core D1
'w2': {'ww0': 5889.95, 'dww': 0.5}, # Core D2
'wr1': {'ww0': 5805.0, 'dww': 10.0},
'... |
# %%
#### imports
from dataclasses import dataclass
from enum import Enum
import numpy as np
from numpy.random import randint, random, uniform, normal, choice
# %%
#### constants
max_tree_size = 8
max_leaf_value = 100
operators = {
"sum": lambda x,y : x+y,
"sub": lambda x,y: x-y,
"mul": lambda x,y: ... |
"""
set of useful function to determine if different process steps
that terminated without error generated the correct output.
Ex. missing positions after parsing the data
"""
from typing import *
import re
import sys
import pandas as pd
import numpy as np
from pathlib import Path
from dask import dataframe as dd
im... |
import tkinter as tk
from PIL import ImageTk,Image
import sqlite3
from tkinter import ttk
root = tk.Tk()
root.title('Address Book')
root.geometry("400x600")
# Databases
# create a database or connect to one
conn = sqlite3.connect('address_book.db')
# create cursor
c = conn.cursor()
# create table
'''
c.execute(""... |
#!/usr/bin/env python3
#coding: utf-8
'''vm_key.py'''
import argparse
import atexit
import socket
import sys
from pyVim import connect
from pyVmomi import vim
# Source : https://gist.github.com/MightyPork/6da26e382a7ad91b5496ee55fdc73db2
# Description HIDCode : ('KEY_NAME', 'HEX_CODE', [('VALUE1', [ 'MODIFIER1', 'MO... |
import os
import pickle
import shutil
from functools import partial, reduce
import numpy as np
import scanpy as sc
from odin.utils import md5_folder
from sisua.data.const import MARKER_GENES
from sisua.data.data_loader.cbmc_CITEseq import read_CITEseq_CBMC
from sisua.data.data_loader.childhood_leukemia_cALL import re... |
"""TD3 implementation."""
import copy
import logging
import pickle as pkl
from dataclasses import dataclass
from pathlib import Path
from typing import List, Union
import cloudpickle
import gin
import numpy as np
import torch
import torch.nn.functional as F
from src.objectives.gym_control.critics import MLPCritic
fro... |
# Copyright (c) 2016-2019, <NAME>
# Licensed under the BSD license
# http://opensource.org/licenses/BSD-3-Clause
from __future__ import absolute_import
from ...... import jni
from ......jvm.jstring import JString
# Class: org.pybee.rubicon.Python
# Method: native static int start(String pythonHome, String pythonPa... |
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.conf import settings
from django.views.generic import ListView, DetailView
from django.views import View
from django.core.mail import send_mail
from django.contrib.postgres.search import SearchQuery, SearchRank, Se... |
from flask import Flask, render_template, request, session, redirect, make_response, url_for, json, jsonify
from flask_cors import CORS
import json
import requests as re
import time
import random
from relu_engine import air_conditioning_re, Hygrometer_re, toolbar, database
app = Flask(__name__)
app.secret_key = '@#$DS... |
"""
owtf.cli
This is the command-line front-end in charge of processing arguments and call the framework.
"""
from __future__ import print_function
import os
import sys
import logging
from copy import deepcopy
from owtf.api.main import start_api_server
from owtf.cli.main import start_cli
from owtf.config import con... |
"""Pentomino puzzle solver - based on <NAME>'s clever Forth version
This program uses a brute force solution using code generation to solve all
possible tilings of the 12 free pentominoes on a 6x10 board (there are 2339
of them). Read more here: http://benhoyt.com/writings/python-pentomino/
Released under a permissiv... |
#!/usr/bin/env python
# coding: utf-8
import os
import ads
# if you don't want bibtexabs, pip install abs,
# otherwise pip install git+git://github.com/andycasey/ads@master
# this script currently has bibtexabs hardcoded in two places
# a simple find/replace should be safe to change it to bibtex
import requests # pip... |
import numpy as np
import logging
from functools import partial
from scipy.stats import norm
import random
"""
This class implements a distribution over the payoff matrix's expected values.
Each entry is modelled independently as a Gaussian, with prior mu and var specified.
The data is assumed to be drawn from a Gaus... |
import numpy as np
import matplotlib.patches as patches
from wzk.mpl.axes import get_aspect_ratio
from wzk.numpy2 import scalar2array, max_size
class DraggablePatch:
lock = None # only one can be animated at a time
def __init__(self, ax, vary_xy=(True, True), limits=None, callback=None, **kwargs):
... |
# Hotspotter imports
import helpers
import load_data2
import oxsty_results
import params
from Printable import DynStruct
# Scientific imports
import numpy as np
# Standard library imports
import datetime
import os
import subprocess
import sys
import textwrap
from itertools import izip
from os.path import realpath, join... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2014, Deutsche Telekom AG - Laboratories (T-Labs)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/lice... |
import os
import sys
import random
import math
import re
import time
import numpy as np
import cv2
import matplotlib
import matplotlib.pyplot as plt
# Root directory of the project
ROOT_DIR = os.path.abspath("../../")
print(ROOT_DIR)
# Import Mask RCNN
sys.path.append(ROOT_DIR) # To find local version of the library
... |
import logging
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchattacks
import nets
import utils
import settings
import losses
class Attack(object):
r"""
Base class for all attacks.
.. note::
It automatically set device to the device whe... |
# Licensed under an MIT style license -- see LICENSE.md
import numpy as np
import multiprocessing
from pesummary.gw.conversions import (
tilt_angles_and_phi_12_from_spin_vectors_and_L
)
from pesummary.utils.utils import iterator, logger
from pesummary.utils.exceptions import EvolveSpinError
from pesummary.utils.d... |
# MIT License
#
# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
#
# 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 th... |
import logging
import re
from builtins import map, range
from copy import deepcopy
from itertools import product
from sqlalchemy.sql import select
from fonduer.candidates.models import Candidate, TemporaryImage, TemporarySpan
from fonduer.parser.models import Document
from fonduer.utils.udf import UDF, UDFRunner
log... |
"""Tests for our configuration system"""
import StringIO
import datetime
import os
import shutil
import tempfile
from testify import *
from tron import config, mcp, scheduler
BASE_CONFIG = """
--- !TronConfiguration
working_dir: "./config_test_dir"
ssh_options: !SSHOptions
agent: true
identities:
- ... |
# import os
# os.environ["NUMBA_DISABLE_JIT"] = "1"
import unittest
import numpy as np
from scipy.sparse import coo_matrix
import numba_stream.grid as grid
import numba_stream.neighbors as neigh
def ragged_to_sparse(indices, splits, values, shape):
row_lengths = splits[1:] - splits[:-1]
i = np.repeat(np.a... |
import gaugette.ssd1306
import gaugette.platform
import gaugette.gpio
import time
import sys
import RPi.GPIO as GPIO
import json
import threading
import traceback
import board
import neopixel
from menu import MenuItem, Menu, Back, MenuContext, MenuDelegate
from drinks import drink_list, drink_options
GPIO.setmode(GPI... |
"""Chooses candidate probes using a naive approach.
In particular, reduces a set of candidate probes in a naive way: by
iterating through the set and, for each candidate probe P, removing all
others that satisfy a specified similarity criterion with P (i.e., are
deemed redundant to P).
Note that this is just a heuris... |
import SimpleITK as sitk
import pylab
import matplotlib.pyplot as plt
import os
from os.path import join
from os import listdir
import numpy as np
import scipy.misc as misc
colors = ['y', 'r', 'c', 'b', 'g', 'w', 'k', 'y', 'r', 'c', 'b', 'g', 'w', 'k']
view_results = False
def dispImages():
'''This function is u... |
from torch import nn
from torch.autograd import Variable
import torch
from torch.autograd.gradcheck import zero_gradients
from dataset import MNISTbyClass
from torch.utils.data import DataLoader
from argparse import ArgumentParser
from models import MLP_100, ConvNet, \
ConvNetRegressor, ConvConvNetRegressor, \
... |
# coding: utf-8
# In[20]:
from gym_torcs import TorcsEnv
import numpy as np
import random
import argparse
from keras.models import model_from_json, Model
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.optimizers import Adam
import tensorflow as tf
fro... |
import os
import argparse
import torch
import rlcard
from rlcard.agents import RandomAgent
from rlcard.utils import get_device, set_seed, tournament, reorganize, Logger
from rlcard.agents import NolimitholdemHumanAgent as HumanAgent
from fish_agent import FishAgent
from rlcard.utils import print_card
imp... |
# -*- coding: utf-8 -*-
"""
pyrseas.dbobject.textsearch
~~~~~~~~~~~~~~~~~~~~~~~~~~~
This defines eight classes: TSConfiguration, TSDictionary,
TSParser and TSTemplate derived from DbSchemaObject, and
TSConfigurationDict, TSDictionaryDict, TSParserDict and
TSTemplateDict derived from DbObjectDic... |
from graphik.robots.robot_base import RobotPlanar
from graphik.graphs.graph_base import RobotGraph
import numpy as np
from graphik.utils.manifolds.fixed_rank_psd_sym import PSDFixedRank
from graphik.solvers.solver_base import GraphProblemSolver
from graphik.utils.dgp import (
adjacency_matrix_from_graph,
dista... |
from __future__ import print_function, division
import os
import re
import pickle
import gzip
import numpy as np
from PyAstronomy.pyaC import pyaPermanent as pp
from PyAstronomy.pyaC import pyaErrors as PE
import six.moves.urllib as urllib
class KuruczMT:
"""
Provides access to individual models in a model gr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.