text stringlengths 3.07k 22.1k |
|---|
#!/usr/bin/env python3
# -*- coding: latin-1 -*-
import argparse
import os.path
import encodedcc
import sys
EPILOG = '''
Script to fix the controlled_by backfill problems
This is a dryrun default script, run with '--update' to PATCH data
Useage:
%(prog)s --infile MyFile.txt
%(prog)s --infile ENCSR000AAA
... |
"""
Generates the regret plot for an experiment. Includes the regret curves for
the random policy, conventional algorithms like SW-UCB, and the default and
best neural bandits.
Usage:
$ python3 regret_analysis.py experiment_folder/
With no additional flag this takes the 'best' rnn and ffnn po... |
from argparse import ArgumentError
import os
import numpy as np
import gym
# import cv2
import matplotlib.pyplot as plt
gym.logger.set_level(40)
os.environ['GYM_CONFIG_CLASS'] = 'Train'
os.environ["global_timeout"] = "1000"
os.environ["global_experiment_number"] = "1"
os.environ["global_dataset_name"] ... |
"""
Usage:
1. training
python run_this.py --action='train'\
-p ./train -v ./val
2. prediction
python run_this.py --action='predict'\
-p /test/**.jpg
"""
import time
import json
import argparse
import sys
sys.path.append('..')
from model.mobilenet import MobileNet
import numpy as np
import cv2
import os
from ke... |
import collections
import json
from django.conf import settings
from django.contrib import messages
from django.contrib.admin.models import LogEntry, ADDITION as ADDITION_LOG_ENTRY
from django.core.cache import cache
from django.db import models
from django.urls import reverse_lazy
from django.utils.formats import dat... |
# Importing Libraries
import pathlib
import warnings
from sklearn.model_selection import train_test_split
from tqdm import notebook
import time
import numpy as np
import pandas as pd
from sklearn.ensemble import *
from sklearn.preprocessing import StandardScaler
import socket
from sklearn.ensemble import A... |
import numpy as np
from scipy.interpolate import interp1d
from scipy.integrate import trapz
from astropy import units as u, constants as c, table as t
from speclite import filters
import astropy.io
from warnings import warn
l_eff_d = {'r': 6166. * u.AA, 'i': 7480. * u.AA, 'z': 8932. * u.AA}
l_wid_d = {'r': 550. * ... |
# Copyright 2021 Sony Group Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... |
import pytest
import io
from megastone import BufferMemory, ARCH_ARM, SegmentMemory, Memory, ISA_X86, MemoryAccessError, AccessType, ARCH_X86, MegastoneError, MappableMemory, Access
from .conftest import TEMP_FILE_DATA
SEG_NAME = 'seg'
SEG_ADDRESS = 0x1000
SEG_SIZE = len(TEMP_FILE_DATA)
INITIAL_DATA = b'A' * SEG_S... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2021 Cloudera, Inc. 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/LIC... |
"""Tests for the templatetags of the ``project-kairos`` project."""
from mock import Mock, patch
from django.contrib.contenttypes.models import ContentType
from django.template import Context, Template
from django.test import RequestFactory, TestCase
from .factories import SiteFactory
from ..templatetags import libs_... |
# -*- coding: utf-8
"""
This module is designed to hold functions for visualization.
This file is part of project dhnx (). It's copyrighted
by the contributors recorded in the version control history of the file,
available from its original location:
SPDX-License-Identifier: MIT
"""
import logging
from collections ... |
# -*- coding: utf-8 -*-
import gsxws
import phonenumbers
from django import forms
from datetime import date
from django.conf import settings
from django_countries import countries
from django.core.validators import RegexValidator
from django.utils.safestring import mark_safe
from django.utils.translation import ugett... |
### clue-thermal-camera v0.6
### Thermal camera display on CLUE or PyPortal
### This plots an 8833 8x8 thermal infrared sensor on the CLUE
### using ulab to interpolate the image
### Tested with an Adafruit CLUE (Alpha) and CircuitPython and 5.3.0
### and PyPortal and 5.3.1
### copy this file to CLUE board as code.py... |
'''Focal Related Utilities'''
import re
import warnings
from numba import prange
import numpy as np
from xarray import DataArray
from xrspatial.utils import ngjit
from xrspatial.utils import lnglat_to_meters
warnings.simplefilter('default')
DEFAULT_UNIT = 'meter'
# TODO: Make convolution more generic with numba ... |
import argparse
import unicodedata
from utils.tools import read_data, write_data
def convert_to_unicode(text):
"""Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode("utf-8", "ign... |
""" Row Level Permissions for FastAPI
This module provides an implementation for row level permissions for the
FastAPI framework. This is heavily inspired / ripped off the Pyramids Web
Framework, so all cudos to them!
extremely simple and incomplete example:
from fastapi import Depends, FastAPI
from fastapi.... |
# -*- coding: utf-8 -*-
"""
Created in January 2020
@author: <NAME> (<EMAIL>)
[DL-course: Utilitary functions for exercise 1]
"""
import time
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
# Colors for plots
colors = ["b", "r", "g", "o", "p"]
def plot_2d_dataset(
points_trainin... |
from model import *
from dataset import *
from common import *
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '3'
#
# def load_pretrain(net, pretrain_file):
#
# #raise NotImplementedError
# print('\tload pretrain_file: %s'%pretrain_file)
# pretrain_state_dict = torch.load(pretrain_file)
# state_dict =... |
import os
import sys
import cv2
import argparse
import glob
import math
import numpy as np
import matplotlib.pyplot as plt
from skimage import draw, transform
from scipy.optimize import minimize
from scipy.optimize import least_squares
import objs
import utils
#fp is in cam-ceil normal, height is in ca... |
"""
Sampling in 1D
===============================
We discuss the performances of several Monte Carlo samplers on a toy 1D example.
"""
######################
# Introduction
# -------------------
#
# First of all, some standard imports.
import numpy as np
import torch
from matplotlib import pyplot as plt
plt.rcPar... |
"""Measurement model class."""
from __future__ import annotations
from abc import abstractmethod
from collections.abc import Sequence
from typing import Optional, cast
from packaging.version import InvalidVersion, Version
from model.metric import Metric
from model.source import Source
from server_utilities.function... |
# Copyright (c) 2020 UT Longhorn Racing Solar
import curses
import textwrap
import time
import battery
import ADC
import Lights
import CAN
import SPI
import Strobelight
import Fans
import WDTimer
import PLL
import I2C
import logging
import config
import Timer
import os
import sys
import traceback
# Global configura... |
import glob
import logging
import os
import re
import shutil
import subprocess
import tempfile
from boto.s3.key import Key
from boto.s3.connection import S3Connection
"""
The functions below are minimal Python wrappers around Ghostscript, Tika, and
Tesseract. They are intended to simplify converting pdf files into u... |
# This file is part of rinohtype, the Python document preparation system.
#
# Copyright (c) <NAME>.
#
# Use of this source code is subject to the terms of the GNU Affero General
# Public License v3. See the LICENSE file or http://www.gnu.org/licenses/.
import os
from os import path
import docutils
from docutils.nod... |
# -*- coding: utf-8 -*-
# Copyright 2014 Google Inc. All rights reserved.
#
# Modifications Copyright (C) 2018 HeiGIT, University of Heidelberg.
#
#
# 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... |
import six
import unittest
import warnings
from scrapy.settings import Settings, SettingsAttribute, CrawlerSettings
from tests import mock
from . import default_settings
class SettingsAttributeTest(unittest.TestCase):
def setUp(self):
self.attribute = SettingsAttribute('value', 10)
def test_set_gre... |
from ..workflow_obj import workflow_obj
from ..writer import save_epi_csv, save_csv
from ..formatter import add_cols, cap_all, format_sex, unkwn
import datetime
class WorkflowObj6(workflow_obj):
# constructor
def __init__(self):
self.id = "WF_6"
# methods
def get_json(self):
super().g... |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
#!/usr/bin/env python
# Libs
from dotenv import load_dotenv
from flask import Flask, jsonify, abort, request, make_response
from pymongo import MongoClient, ReturnDocument
from flask_httpauth import HTTPBasicAuth
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from string import hex... |
import numpy as np
import mathutils
import itertools
class Environment:
def __init__(self, dimension, num_peaks, initial_angle):
self.H = np.zeros((dimension, num_peaks))
self.W = np.zeros((dimension, num_peaks))
self.C = np.zeros((dimension, num_peaks))
self.S = 2 # initial angle
... |
# Lint as: python3
"""Utility class and function for tests."""
import collections
import itertools
import re
import sys
import tokenize
from pytype import compat
from pytype import errors
from pytype import state as frame_state
from pytype.pyc import loadmarshal
from pytype.pyc import opcodes
import six
import unit... |
# Copyright (c) 2009-2012 <NAME>. See LICENSE for details.
import sys
from gevent.hub import greenlet, getcurrent, get_hub, GreenletExit, Waiter, PY3, iwait, wait
from gevent.timeout import Timeout
from collections import deque
__all__ = ['Greenlet',
'joinall',
'killall']
class SpawnedLink(ob... |
from IMLearn.learners.classifiers import Perceptron, LDA, GaussianNaiveBayes
from typing import Tuple
from utils import *
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.express as px
from math import atan2, pi
pio.templates.default = "simple_white"
def load_dataset(filename... |
import json
import sys
from functools import lru_cache
from itertools import tee
from pathlib import Path
from typing import Any, Dict, Iterator, List, Mapping, Optional
import requests
import yaml
from hexbytes import HexBytes
from importlib_metadata import PackageNotFoundError, packages_distributions
from importlib_... |
import logging
from io import StringIO
from typing import Union
from asyncio import TimeoutError
import discord
from discord.ext import commands
from bot import constants
from bot.cogs.utils.embed_handler import authored, failure, success, info
from bot.cogs.utils.checks import check_if_it_is_tortoise_guild
from bot.... |
import os
import tensorflow as tf
from tensorflow.keras.layers import GlobalAveragePooling2D, GlobalMaxPooling2D, Flatten, Dropout
from tensorflow.keras import regularizers
import dku_deeplearning_image.dku_constants as constants
from dku_deeplearning_image.keras_applications import APPLICATIONS
import threading
impo... |
#coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import argparse
import shutil
import numpy as np
import PIL.Image as Image
import tensorflow as tf
import pandas as pd
import retrain as retrain
from count_ops import load_... |
"""
Tools for data visualization.
"""
import abc
import collections
import json
import textwrap
import warnings
import dh.utils
import dh.data
try:
from matplotlib import pyplot as plt
PLT_ERROR = None
except ImportError as e:
plt = None
PLT_ERROR = e
###
#%%
###
def scatter(xs, ys, labels=None, ... |
"""Weave"""
# pylint: disable= no-member, arguments-differ, invalid-name
import dgl.function as fn
import torch
import torch.nn as nn
import torch.nn.functional as F
__all__ = ['WeaveGNN']
# pylint: disable=W0221, E1101
class WeaveLayer(nn.Module):
r"""Single Weave layer from `Molecular Graph Convolutions: Moving... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import tarfile
import cv2
import copy
import numpy as np
import tensorflow as tf
from utils.curve import points_to_heatmap_rectangle_68pt
from six.moves import xrange
from six.moves import... |
from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
from fontTools.misc import sstruct
from fontTools.misc.textTools import safeEval
from itertools import *
from functools import partial
from . import DefaultTable
from . import grUtils
import struct, operator, warnings
G... |
import os
import random
import logging
import time
from unicards import unicard
# 0:s, 1:h, 2:d, 3:c (-1: None)
# 0:2, 1:3, ..., 8:T, 9:J, 10:Q, 11:K, 12:A (-1: None)
S = 0
H = 1
D = 2
C = 3
RANK_TO_CARD = {
0: 2,
1: 3,
2: 4,
3: 5,
4: 6,
5: 7,
6: 8,
7: 9,
8: 'T',
9: 'J',
1... |
#!/usr/bin/python
# Copyright (c) 2017 Alibaba Group Holding Limited. <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General... |
import os
from os import listdir
from tqdm import tqdm
import json
from collections import Counter
import itertools
import random
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
import tensorflow as tf
import tensorflow_hub as hub
import networkx as nx
def get_papers_dict(areas:list, yea... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Contains the base objects for use when creating a sanitizer using
PyCIRCLean. Subclass or import from FileBase/KittenGroomerBase and implement
your desired behavior.
"""
import os
import hashlib
import shutil
import argparse
import stat
import traceback
from pathlib... |
import io
import zipfile
import urllib.request
import warnings
from itertools import chain
from typing import List, Tuple
import pandas
from Bio.SeqUtils import ProtParam
from mzqc import MZQCFile as mzqc
from qccalculator import utils
"""
Calculate id based metrics from MaxQuant result files
"""
def loadMQZippedR... |
import logging
import os
import os.path
import galaxy.tools.parameters.basic
import galaxy.tools.parameters.grouping
from galaxy.tool_util.verify.interactor import ToolTestDescription
from galaxy.util import (
string_as_bool,
string_as_bool_or_none,
unicodify,
)
try:
from nose.tools import nottest
ex... |
#!/usr/bin/env python3
# T42 Teletext Stream to In-vision decoder
#
# Copyright (c) 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 limit... |
# Copyright 2012 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""This module defines Isolate Server frontend url handlers."""
import datetime
import webapp2
from google.appengine.api import users
import acl
impo... |
from jinja2 import Environment, FileSystemLoader
import json
import os
import shutil
from datetime import datetime
from fuzzyset import FuzzySet
import os
currentDir = os.getcwd()
VARS = {
"site-detail":os.path.normpath(currentDir+"/database/site-detail.json"),
"gallery":os.path.normpath(currentDir+"/database... |
import pytest
import requests
import base64
import time
from .common import random_test_name
from .common import get_user_client_and_cluster
from .common import create_project_and_ns
from .common import get_project_client_for_token
from .common import create_kubeconfig
from .common import wait_for_app_to_active
from .c... |
import math
import gpxpy
import gpxpy.gpx
from . import maplib_sip as maplib_sip
from .errors import MapLibError, FileLoadError, FileOpenError, FileParseError
class GPSData:
"""GPS data backend"""
def __init__(self, fname):
"""Load GPS data from a file or pass a GPX object directly"""
self.... |
from skimage import metrics
from torchvision.transforms import InterpolationMode
from torchvision import transforms
import cfg
import os
import numpy as np
import torch
import cv2
from PIL import Image
class Point(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
class Line(object):
... |
import numpy as np
import scipy.special as ss
import scipy.signal as ss2
import scipy
from numpy import abs, sin, cos, real, exp, pi, sqrt
def psi_s(z, x, beta):
"""
2D longitudinal potential
Eq. (23) from Ref[1] with no constant factor (e*beta**2/2/rho**2).
Ref[1]: <NAME> and <NAME>, PRAB 23, 014402 ... |
#!/usr/bin/env python3
"""
Wi-Fi Machine-in-the-Middle - command line interface
Automation of MitM Attack on WiFi Networks
Bachelor's Thesis UIFS FIT VUT
<NAME>
2016
"""
import argparse
import logging
import subprocess
import sys
import time
import warnings
from enum import Enum, unique
from pprint import saferepr
fr... |
import json
from typing import Any, ClassVar, Dict, Iterable, List, Tuple
import attr
from ...parameters import Parameter
from .converter import to_json_schema_recursive
@attr.s(slots=True, eq=False)
class OpenAPIParameter(Parameter):
"""A single Open API operation parameter."""
example_field: ClassVar[str... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 28 21:21:23 2020
@author: Matt
"""
from wasserplan import Pair
# Python tools for output, directory management, and graph management
from functools import partial
import geopandas as gpd
from networkx import is_connected, connected_components
#gerry chain... |
#
# This file is implemented based on the author code of
# Lee et al., "A simple unified framework for detecting out-of-distribution samples and adversarial attacks", in NeurIPS 2018.
#
import os
import torch
import numpy as np
def compute_confscores(model, test_loader, outdir, id_flag):
total = 0
if id_fl... |
"""pypyr step that runs another pipeline from within the current pipeline."""
import logging
from pypyr.context import Context
from pypyr.errors import (ContextError,
ControlOfFlowInstruction,
KeyInContextHasNoValueError,
KeyNotInContextError... |
###################################################################################################
# Python Script for copying SW packages
# Author : <NAME>
# Requires Python 3.4, BeautifulSoup library
#
# CHANGELOG
# v2.9 - 20150623 Modified regex to have additional branches
# v2.8 - 20150603 Modified regex to hav... |
# --------------------------------------------------
# Name: Jessica
# Program: CelticaJM.py
# --------------------------------------------------
# Program purpose: part 2 of the Celtica Game
from graphics import *
import random
## to jump to display/gui-related functions and settings, search "GUI settings"
## to... |
# -*- coding: utf-8 -*-
# ProDy: A Python Package for Protein Dynamics Analysis
#
# Copyright (C) 2010-2012 <NAME>
#
# 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 3 of the Licen... |
from fastapi import FastAPI, APIRouter, HTTPException
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from fastapi_utils.tasks import repeat_every
from app.api import predict, viz, getdata
from pydantic import BaseModel, Field, validator
import pandas as pd
import praw
import os
import requests
from... |
# Copyright (C) 2021 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
#!/usr/bin/python3
import numpy as np
from pathlib import Path
import pdb
import torch
from mseg.utils.names_utils import (
load_class_names,
get_universal_class_names,
get_classname_to_dataloaderid_map
)
from mseg.utils.tsv_utils import read_tsv_column_vals
from mseg.taxonomy.taxonomy_converter import (
parse_e... |
# Copyright 2018 Google LLC.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
#... |
import json
import os
import keras
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import requests
from keras.layers import Dropout, Dense, LSTM, TimeDistributed
from keras.models import Sequential
from sklearn.preprocessing import normalize, MinMaxScaler
"""
Created by <NAME> on 7/25/18.
... |
"""Forward and back projector for PET data reconstruction"""
import logging
import cuvec as cu
import numpy as np
from .. import mmraux
from ..img import mmrimg
from . import petprj
log = logging.getLogger(__name__)
ISUB_DEFAULT = np.array([-1], dtype=np.int32)
# ====================================================... |
from __future__ import print_function
import pickle
import os.path
import email
import httplib2
import logging
import tweepy
import json
from base64 import urlsafe_b64decode
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Requ... |
# File: qintelqwatch_helper.py
#
# Copyright (c) 2009-2021 Qintel, 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 b... |
import glob
import os
import sys
import random
import argparse
from stable_baselines3 import PPO # pip install stable-baselines3
from stable_baselines3.common.callbacks import EvalCallback
from stable_baselines3.common.utils import set_random_seed, get_schedule_fn
from stable_baselines3.common.vec_env import SubprocV... |
import kfac
import CustomOp as co
import RL_farmwork.experience_replay as rl
from models.official.resnet.cifar10_main import *
from models.official.resnet.cifar10_main import input_fn, _WEIGHT_DECAY, _NUM_IMAGES
from train_val.problems import *
def get_filenames(training_type, data_dir):
"""Returns a list of fil... |
#!/usr/bin/env python
import argparse
import csv
import io
import json
import logging
import os
from dataclasses import dataclass, field
from math import ceil
from typing import Optional, Union, Any
from dap_orchestration.types import DapSurveyType
from gcsfs.core import GCSFileSystem
log = logging.getLogger(__name_... |
"""
" Tests for evaluator.py
"""
import pytest
from ..src import playingcard as pc
from ..src import evaluator as ev
from . import tools
@pytest.fixture
def ace():
return pc.PlayingCard('A', 's')
def test_iswheel_A234_returnsFalse():
cards = tools.to_cards(['As', '2c', '3d', '4d'])
assert ev.is_whee... |
# -*- coding: UTF-8 -*-
import copy
import csv
import os
import sys
import traceback
def get_filepath(type, nickname):
"""获取结果文件路径"""
file_dir = os.path.split(
os.path.realpath(__file__))[0] + os.sep + 'weibo' + os.sep + nickname
if type == 'img' or type == 'video':
file_dir = file_dir + ... |
from typing import Dict, TypeVar, Optional, List, Tuple
from datetime import datetime
from os import path, getcwd
from shutil import copyfileobj
from posixpath import join as urljoin
import requests
def day_of_year(dt: datetime) -> int:
"""
Gets the day of the year from a datetime as an int
:param dt: d... |
import numpy as np
import datetime
import matplotlib.pyplot as plt
def createnosignaldata(n, d):
"""
Data points are random Gaussian vectors.
Class labels are random and uniform
"""
X_train = np.random.normal(0, 1, (n, d + 1))
X_train[:, d] = np.sign(X_train[:, d])
X_holdout = np.rando... |
import random
import heapq as hp
import numpy as np
import time
def generate_instance(graph_type, graph_generator_inputs, demand_generator_inputs):
# this function generates an intances according to the asked caracteristics :
# - first a graph is generated : a grid graph or a random graph
# - then commodit... |
#! /usr/bin/env python3
import re
import sys
import os
import subprocess
import time
import json
import logging
import smtplib
import datetime
import glob
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
def log_rotation(config):
... |
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import os
import sys
import xesmf as xe
import xarray as xr
import numpy as np
import pandas as pd
import math
from dask.diagnostics import ProgressBar
class color:
PURPLE = '\033[35m'
CYAN = '\033[36m'
BLUE = '\033[34m'
LBLUE='\033[94m'
GREEN = '\033[32m'
LGREEN='\033[92m'
YELLOW = '\033[33m'
... |
"""Utility functions used across hydrolink modules.
Author
----------
<NAME>: <EMAIL>
"""
# Import packages
import geopandas as gpd
import pandas as pd
from shapely.geometry import Point, LineString
import shapely.wkt
import re
import difflib
##########################################################################... |
import re
import os
import subprocess
from datetime import datetime
from typing import Dict
from urllib.parse import urlparse
from .result import ExecResult
def _get_path(x):
return x["path"]
class Nghttp:
def __init__(self, path, connect_addr=None, tmp_dir="/tmp"):
self.NGHTTP = path
... |
#
# Classes which help define scenes for a RadioRA installation. These classes are not required to use the functionality
# of the package, but they can simplify the declaration of a set of scenes. See the test files for samples.
#
# Copyright (C) 2017 <NAME> <<EMAIL>>
#
# SPDX-License-Identifier: MIT
"""\
Scenes a... |
from typing import Optional
import torch
from detectron2.structures import ImageList
from torch import nn
from torch.nn import functional as F
class SeparableConv(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, padding=1):
super().__init__()
self.depthwise = nn.Conv2d(
... |
import random
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pickle
import seaborn as sns
sns.set_style("whitegrid")
sns.set_context("paper", rc={"font.size":14,"axes.titlesize":14,"axes.labelsize":14})
import matplotlib as m
import matplotlib.pyplot as plt
import matplotlib.gridspec ... |
from abc import ABC, abstractmethod
from enum import Enum
from functools import lru_cache
import pathlib
import subprocess
import tempfile
import numpy as np
from pyschism.mesh.hgrid import Hgrid
def C_of_sigma(sigma, theta_b, theta_f):
assert theta_b <= 0. and theta_b <= 1.
assert theta_f <= 0. and theta_f... |
#!/usr/bin/env python
"""Complement VCF with simple pileup info from BAM files
"""
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__copyright__ = "2014 Genome Institute of Singapore"
__license__ = "The MIT License"
# --- standard library imports
#
import sys
import os
import argparse
import logging
from collections imp... |
"""
Classification.py
"""
import os
import json
import gzip
import json
import numpy as np
from datetime import datetime
from sklearn.linear_model import LogisticRegression, SGDClassifier
from arxiv_public_data.embeddings.util import load_embeddings, fill_zeros
import arxiv_public_data.tests.cocitation_category_feat... |
import os, copy, cProfile, pstats, io
import numpy as np
import gdspy as gp
import gds_tools as gdst
def profile(fnc):
"""A decorator that uses cProfile to profile a function"""
def inner(*args, **kwargs):
pr = cProfile.Profile()
pr.enable()
retval = ... |
#!/usr/bin/env python
"""
populate_data_request.py
Populates the PRIMAVERA-DMT DataRequest table with details from the PRIMAVERA
data request spreadsheet.
Uses the Google Sheets API:
https://developers.google.com/sheets/quickstart/python
To load the spreadsheet at:
https://docs.google.com/spreadsheets/d/1ewKkyuaUq99H... |
#!/usr/bin/env python3
# # -*- coding: utf-8 -*-
"""
Default package.
________________________________________________________________________________
Created by brightSPARK Labs
www.brightsparklabs.com
"""
# standard libraries
import os
import sys
from pathlib import Path
from typing import Dict, Iterable
# vendor... |
#!/usr/bin/env python
# For python 2.6-2.7
from __future__ import print_function
# For python2.5
# from __future__ import with_statement
from Utilities import *
import textwrap
class module:
def __init__(self, name):
# what do we need?
self.name = ''
self.declarations = []
self.imp... |
import asyncio
import discord
from discord.ext import commands
import json
class Paginator(discord.ui.View):
def __init__(self, entries, color, title, ctx):
self.page = 0
self.entries = entries
self.color = color
self.title = title
self.ctx = ctx
super().__init__()
... |
from __future__ import print_function
import unittest
from unittest import TestCase
import numpy as np
from numpy.testing import assert_, assert_raises
from numpy.testing import assert_array_equal, assert_array_almost_equal
from hmmlearn.utils import normalize
from autohmm import tm
np.seterr(all='warn')
def tes... |
# -*- coding: UTF-8 -*-
import sys
if sys.version_info >= (3, 0):
import http.cookiejar as cookiejar
import urllib.parse as urllib_parse
import urllib.request as urllib_request
if sys.version_info < (3, 0):
import cookielib as cookiejar
import urllib as urllib_parse
import urllib2 as urllib_re... |
# Copyright (c) 2020, <NAME> (@e-bug).
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import glob
import logging
import _pickle as cPickle
import random
import numpy as np
import torch
from torch.utils.data import Dataset
from d... |
# -*- coding: UTF-8 -*-
# Copyright 2011-2017 <NAME>
# License: BSD (see file COPYING for details)
from __future__ import unicode_literals
from builtins import str
from django.db import models
from lino.api import dd, rt, _
from lino.modlib.users.mixins import My
from lino.modlib.users.desktop import Users
from etge... |
import json
import os
import shutil
import subprocess
import sys
import threading
import time
import urllib.request
try:
import spotipy
import urllib3
from pynput import keyboard
from pynput.keyboard import Key, Controller
except ImportError:
print("DEPENDENCIES NOT INSTALLED!"
"\nPlease ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.