text stringlengths 3.07k 12.6k |
|---|
"""Compute and Visualize outcome curves"""
import numpy as np
import solve_credit as sc
def get_thresholds(loan_repaid_probs, pis, group_size_ratio, utils, score_change_fns, scores):
"""get thresholds for all 3 fairness criteria"""
# unpacking bank utilities
utility_default, utility_repaid = utils
br... |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import skimage as skimage
from skimage import transform, color, exposure
from skimage.transform import rotate
from skimage.viewer import ImageViewer
import random
import numpy as np
from collections import deque
import json
from keras.models... |
# coding=utf-8
# /usr/bin/env python
'''
Author: wenqiangw
Email: <EMAIL>
Date: 2020-07-03 17:31
Desc: 规划中,,,,不可用
BMap
Bar
Boxplot
Funnel
Geo
HeatMap
line
bar
Map
Pie
Scatter
WordCloud
图形组件
组合组件
[Bar,Line]
Scatter
HeatMap
'''
import webbrowser
import os
import pandas as pd
from pyecharts.components import Table
fr... |
#!/usr/bin/env python3
import ctypes
import random
from time import time
import os
import torch
import torch.nn as nn
import torchvision.models as models
from progress.bar import IncrementalBar
from torch.utils.data import DataLoader
from torchvision import transforms
from torchvision.datasets import ImageFolder
imp... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File : main.py
@Time : 2021-11-21 22:39:20
@Author : <NAME>
@Email : <EMAIL>
@License : Apache License 2.0
"""
import os
import argparse
import cv2
import numpy as np
from ffmpy3 import FFmpeg
from PIL import Image, ImageDraw, ImageFont
pa... |
import json
import csv
import matplotlib.pyplot as plt
import ground_truth as gt
# Import in the Clarifai gRPC based objects needed
from clarifai_grpc.channel.clarifai_channel import ClarifaiChannel
from clarifai_grpc.grpc.api import resources_pb2, service_pb2, service_pb2_grpc
from clarifai_grpc.grpc.api.status impo... |
# Copyright 2017 Catalyst IT Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
import discord
from discord.ext import commands
from util.logger import logger
from util.colors import colors
from util.emojis import *
import oyaml as yaml
class TempChannels(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name='setup',
desc='Setup for the temporary v... |
# Copyright (c) 2018-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
"""Wrappers for saving and loading DWIs of 3D printed phantoms.
In this module, images are classified as DWIs or derived images. A DWI
should be the raw 4D data from a diffusion MRI scan, and have associated
information about the diffusion gradients. A derived image should be
(usually) 3D data from analysis of a DWI.
... |
# -*- coding: utf-8 -*-
import jieba
import random
import re
from idna import unichr
import codecs
# base_dir = './Keras-Project-Template/'
base_dir = '../'
def read_stop_word(stop_path):
stop_set = set()
# with open(stop_path, 'r') as stops:
with codecs.open(stop_path, 'r', encoding='utf-8') as stops:
... |
#!/bin/python
"""
Update eeschema symbol fields from specified CSV BOM file.
"""
import sys
import os
import logging
import argparse
from Queue import Queue
lib_path = os.path.join(os.path.dirname(sys.argv[0]),'..')
lib_path = os.path.normpath(lib_path)
if lib_path not in sys.path:
sys.path.append(lib_path)
from li... |
import os
import json
import ctypes
PWD = os.path.abspath(os.path.dirname(__file__))
FUNCTION_POINTERS_TEMPLATE = """
#cython: language_level=3
from cpython.long cimport PyLong_FromVoidPtr
cimport scipy.special.cython_special as sc
functions = {{
{FUNCTIONS}
}}
"""
NUMBA_OVERLOADS_TEMPLATE = """
import ctypes
im... |
# This module gives functions for setting up the excel worksheet including stylising the table, appending
# the scraped jobs and sorting the job data. It also provides functions for saving and loading workbooks.
from datetime import datetime
from openpyxl.styles import Font, PatternFill
from openpyxl import Workbook
f... |
import discord, asyncio # imports the base discord package
from discord.ext import (
commands,
) # imports discord.ext and it's commands wrapper, "commands"!
import aiohttp # this is what we're going to use to make http requests to reddit!
import json # this is how we will manupulate the json response of the re... |
# 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, software
# distributed under th... |
"""
Operations associated with logging
"""
import logging
import os
import sys
from logging.handlers import SysLogHandler
# setup from command line
_lrgasp_logger = None
def getLrgaspLogger():
return _lrgasp_logger
def getFacilityNames():
return tuple(SysLogHandler.facility_names.keys())
def getLevelNames(... |
from dtpattern.unicode_translate.translate import all_uc_to_ucname
from dtpattern.unicode_translate.uc_models import FIX_COMB_SYM, VAR_COMB_SYM, FIX_SYMB, VAR_SYMB, UC_SYMBOLS, \
OPT_PATTERN, OPT_SYMB, SYMB_GROUP
from multipledispatch import dispatch
import structlog
log = structlog.get_logger()
def subpattern_to... |
# Copyright 2016 <NAME>. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... |
from collections import namedtuple
from typing import Any, Dict
import os
import boto3
import numpy as np
import torchvision.transforms as transforms
from torch import nn
from sklearn.metrics import average_precision_score
from determined.pytorch import (
DataLoader,
LRScheduler,
PyTorchTrial,
PyTorc... |
import argparse
import logging
import traceback
from typing import List
from sys import exit
import click
from cli.echo import Echo
from common.errors import BaseError
from vm_providers.factory import get_provider_for
from vm_providers.errors import ProviderNotFound
from common import definitions
logger = logging.ge... |
INFINITY = float('inf')
class MinHeap:
"""
Binary min-heap using array method.
Supports operations extract_min, decrease_key, insert, merge.
"""
def __init__(self, arr = None, already_heap = False):
"""
Creates an empty heap when passed with no parameters.
Initializes self.arr when passed with a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Script to generate QR-CODE for the BOLLHOFF's products .
Usage:
1 - Add display 'name' and shorten link 'url' to a dict (product).
1.1 If you are performing a bulk operation. Add the product dict to the list 'products'.
2 - Call 'convert(product:dict)' or 'conver... |
"""
Script to convert existing data sets from the ScrAPD 2 to the ScrAPD 3 format.
"""
import argparse
import datetime
import json
import sys
from scrapd.core import date_utils
from scrapd.core import model
from scrapd.core.formatter import to_json
def main():
"""Define the main entrypoint of the program."""
... |
# -*- coding: utf-8 -*-
#
# This file is part of Sequana software
#
# Copyright (c) 2016 - Sequana Development Team
#
# File author(s):
# <NAME> <<EMAIL>>
#
# Distributed under the terms of the 3-clause BSD license.
# The full license is in the LICENSE file, distributed with this software.
#
# website: https... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012 Team-XBMC
#
# 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 License, or
# (at your option... |
# coding=utf-8
import types
import datetime
from func import enable_channel_wrapper, route_wrapper
from support.i18n import is_localized_string, _
from support.items import get_item_thumb
from support.helpers import get_video_display_title, pad_title
from support.ignore import get_decision_list
from support.lib import... |
# Copyright 2015 Puppet 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/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
"""Snippets for managing S/MIME certificate for a user's account.
These snippets appear at:
https://developers.google.com/gmail/api/guides/smime_certs
"""
import base64
import csv
import datetime
from apiclient import errors
# [START create_smime_info]
def create_smime_info(cert_filename, cert_password=None):
"... |
from datetime import datetime
import pytest
from pytz import timezone
from nro.nro_datapump import nro_data_pump_update, create_expiry_date
from namex.models import Request, Name, State, User
expiry_date_test_data = [
('using epoch utc', # test descriptive name
datetime(1970, 1, 1, 00, 00, tzinf... |
# Tencent is pleased to support the open source community by making GNES available.
#
# Copyright (C) 2019 THL A29 Limited, a Tencent company. 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... |
# Copyright L.P.Klyne 2013
# Licenced under 3 clause BSD licence
# $Id: TestScheduleProcessor.py 2612 2008-08-11 20:08:49Z graham.klyne $
#
#
import sys, logging, time, os
from os.path import exists
import time
import unittest
from MiscLib.DomHelpers import *
from EventLib.Event import Event
from EventLib.EventAg... |
"""
This script includes some help functions for the EEG tutorial of
the course Methods in Cognitive Neuroscience @ Max Planck School of Cognition
Prepared by <NAME> @ MPI CBS, Leipzig, Germany, <EMAIL>
June 2020
"""
import numpy as np
import scipy.signal as sp
from matplotlib import pyplot as plt
import mne
def... |
import numpy as np
from scipy import constants
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib as mpl
import meep
import meep_ext
from numpipe import scheduler, pbar
import miepy
job = scheduler()
nm = 1e-9
um = 1e-6
### Parameters
radius = 75*nm
height = 110*nm
material = m... |
import json
from flask import jsonify
from db import database
from general import mongo_clean, max_score
import create_action
RANKED_LIST_DESCRIPTION = 'A collection of maps from the <map_pool_name> Hitbloq map pool used for the associated ranked ladder. Check out https://hitbloq.com for more info.'
def action_list... |
import socketserver
import struct
import time
import json
from random import randint
from httpdns_api import *
#import _thread
import threading
from black_list import black_list as blist
def rand_ip():
return str(randint(0,255))+"."+str(randint(0,255))+"."+str(randint(0,255))+"."+str(randint(0,255))
class SinDNSQu... |
"""
iPlant authentication models..
"""
from datetime import timedelta
import hashlib
import uuid
import logging
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import models, transaction
from django.db import IntegrityError
from django.utils import timezone
from .settin... |
import math
def add_vec(u, v):
return (u[0]+v[0], u[1]+v[1])
def norm_vec(v):
return math.sqrt(v[0]*v[0] + v[1]*v[1])
def sub_vec(u, v):
return (u[0]-v[0], u[1]-v[1])
def rot90_vec(v):
return (v[1], -v[0])
def scal_vec(alpha, v):
return (alpha*v[0], alpha*v[1])
def unit_vec(v):
L = norm_ve... |
import sys
import os
import time
import string
import random
from subprocess import *
from math import floor
import numpy as np
import pandas as pd
from shared.args import get_valued_arg, is_arg_passed, get_int_valued_arg
from shared.moduleloading import load_resel_mode
def print_usage (show_help_line=False):
"... |
import numpy as np
import plotly.offline as py
import plotly.graph_objs as go
py.init_notebook_mode(connected=True)
def plot1d(data_list, data_names=None, x_title='', y_title='',
x_log=False, y_log=False, show_dx=True, width=600, height=400):
"""
Produce a 1D plot
@param data_list: list ... |
from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
import os
"""
This is the adapted version of the example code for Amazon SageMak... |
import torch.nn as nn
import torch.nn.functional as F
import torch
class PPMBilinear(nn.Module):
def __init__(self, num_classes=7, fc_dim=2048,
use_aux=False, pool_scales=(1, 2, 3, 6),
norm_layer = nn.BatchNorm2d
):
super(PPMBilinear, self).__init__()
... |
import sys
import os
import logging
import configparser
import uuid
import requests
script_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
def read_config():
if os.path.isfile(os.path.join(script_dir, 'frontend.cfg')):
# Load the configuration file.
try:
my_config = {}
... |
#!/usr/bin/env python
from __future__ import print_function
import json
import os
import unittest
from WMCore_t.ReqMgr_t.TestConfig import config
from WMCore.REST.Test import fake_authz_headers
from WMCore.ReqMgr.Auth import getWritePermission
from WMCore.Services.ReqMgr.ReqMgr import ReqMgr
from WMQuality.REST.RES... |
"""
Once all NEXRAD radar images have been downloaded, convert them to images.
In order to parallelize the process of making images of the data, we run files
from each radar separately. For our research we had 81 radars and ran this file
81 times in parallel on schooner (OU super computer)
Example command:
python Cre... |
import random
class App:
def __init__(self):
self.total = 0
self.opponent_total = 0
self.dice_count = 6
self.put_away_dices = []
self.turn_total = 0
self.dice_declination = {1: "dice", 2: "dices", 3: "dices", 4: "dices", 5: "dices", 6: "dices"}
# sets declin... |
# Copyright 2016 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
import argparse
import os
import json
import logging
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
from utils import bd
from glob import glob
rcParams['axes.labelsize'] = 20
rcParams['xtick.labelsize'] = 20
rcParams['ytick.labelsize'] = 20
rcParams['legend.fonts... |
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
try:
import tensorflow as tf
if int(tf.__version__.split('.')[0]) < 2:
import keras
from keras.models import load_model
from keras.callbacks import M... |
import os
# For reading, visualizing, and preprocessing data
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.model_selection import GroupKFold
from sklearn.preprocessing import StandardScaler
from xgboost import XGBClassifier
from alaska2.dataset import METHOD_TO_INDEX
from a... |
from __future__ import annotations
from typing import Tuple, List, Optional, Union
import numpy as np
from n_in_a_row.chip import Chip
from n_in_a_row.win_state import WinState
from n_in_a_row.hashable import Hashable, pack_ints
from n_in_a_row.config import max_grid_shape
from .grid_index import GridIndex
from .ce... |
# coding=utf-8
import os
import subliminal
import helpers
from items import get_item
from lib import get_intent, Plex
from config import config
def get_metadata_dict(item, part, add):
data = {
"item": item,
"section": item.section.title,
"path": part.file,
"folder": os.path.dirn... |
import numpy as np
import pytest
from napari import layers
from napari.layers.utils._link_layers import (
layers_linked,
link_layers,
unlink_layers,
)
BASE_ATTRS = {}
BASE_ATTRS = {
'opacity': 0.75,
'blending': 'additive',
'visible': False,
'editable': False,
'shear': [30],
}
IM_ATTRS... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.linear import Linear
from torchsummary import summary
# 用于ResNet18和34的残差块,用的是2个3x3的卷积
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=1):
super(BasicBlock, self).__init__()... |
from collections import defaultdict
from typing import DefaultDict, Optional, Set
import redis
from ...config import Config
from ...koji_query import query_image_build
from ...koji_utils import get_koji_session
from ...models import RegistryModel, TagHistoryModel, TagHistoryItemModel
from ...redis_utils import get_re... |
#!/usr/bin/env python3
#<---------------------------------------- 100 characters ---------------------------------------->#
import sys
from dataclasses import dataclass
from typing import Dict, List, Set, TextIO, Tuple
@dataclass
class Patch:
"""A patch to some code."""
name: str
befores: List[str]
... |
from Products.CMFCore.utils import getToolByName
from bika.lims.interfaces import ISample, IAnalysisService, IAnalysis
from bika.lims import logger
from bika.lims.utils import tmpID
from bika.lims.utils.sample import create_sample
from bika.lims.utils.samplepartition import create_samplepartition
from bika.lims.workflo... |
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from django.utils.timezone import localtime, now
from django.urls import reverse
from django.db.models.signals import post_save
from django.core.exceptions import ObjectDoesNotExist
# from nadine.models.resource... |
"""Utility functions for Airshare."""
import mimetypes
import os
import pyperclip
import re
import socket
import tempfile
from time import strftime
from zipfile import ZipFile
from zeroconf import IPVersion, ServiceInfo, Zeroconf
from .qrcode import ErrorCorrectLevel, QRCode
__all__ = ["get_local_ip_address", "qr... |
# ----------------------------------------------------------------------
# Copyright (c) 2022
#
# See the LICENSE file for details
# see the AUTHORS file for authors
# ----------------------------------------------------------------------
#--------------------
# System wide imports
# -------------------
import os
im... |
#!/usr/bin/env python3
'''
Run `ros2 test single_drone.test.py`
'''
from launch import LaunchDescription
from launch_ros.actions import Node as lNode
import launch_testing
import rclpy
from rclpy.action.client import ClientGoalHandle
from rclpy.duration import Duration
from rclpy.node import Node
from rclpy.executors ... |
# -*- coding: utf-8-unix ; tab-width: 2 -*-
# Version: Python 3.6.7
### System modules
import sys
sys.path.append('/home/chihiro/.pyenv/versions/3.6.7/lib/python3.6')
sys.path.append('/home/chihiro/.pyenv/versions/3.6.7/lib/python3.6/lib-dynload')
sys.path.append('/home/chihiro/.pyenv/versions/3.6.7/lib/python3.6/site... |
"""A simple muid key server supports registering a key and fetching key
that hasn't been used by anybody before"""
import os
import sys
import logging as log
import muid
import databases
import sqlalchemy
import http
from fastapi import FastAPI, HTTPException, Response
from pydantic import BaseModel
MIN_DIFFICULTY... |
import math
import random
from enum import Enum
from operator import itemgetter
from functools import singledispatch
from typing import List, Tuple, Dict, Optional
import numpy as np
from text_rank.graph import Graph, AdjacencyList, AdjacencyMatrix, Vertex
ConvergenceType = Enum("ConvergenceType", "ALL ANY")
def su... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 23 10:33:13 2021
@author: Tom
"""
from scipy.interpolate import interp1d, interp2d
import numpy as np
import pandas as pd
import os
import liionpack
from skspatial.objects import Plane
from skspatial.objects import Points
ROOT_DIR = os.path.dirname(os.path.abspath(liionp... |
from __future__ import absolute_import
from __future__ import division
import torch as t
from torch import nn
from torch.nn import functional as F
import numpy as np
import cupy as cp
from data.dataset import preprocess
from utils import array_tool as at
from utils.config import opt
from model.utils.bbox_tools import... |
from keras.preprocessing.image import load_img, img_to_array
import numpy as np
from keras.applications import vgg19
from keras import backend as K
from scipy.optimize import fmin_l_bfgs_b
from scipy.misc import imsave
import time
target_image_path = 'data/transfer-target.png' # 想要变化的图像路径
style_reference_image_path = ... |
import numpy as np
import cv2
import os
#os.chdir("C:\Users\<NAME>\Desktop")
def nothing(x):
pass
#ret,frame = vc.read()
def hand_count(ret, frame):
#vc = cv2.VideoCapture(0)
#ret,frame = vc.read() # Reading one image frame from webcam.
cv2.createTrackbar("hue_lower","h... |
from data_layer import FeaturizeData
from sklearn import linear_model
from sklearn.utils import class_weight
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from sklearn.metrics import classification_report
import matplotlib
matplotlib.use('Agg')
import ... |
#
# validate the policy rules and apps across a set of SCM instances.
# policy rules include
# inbound (NAT Rules)
# outbound (Firewalling rules)
# pathrules ( Path Selection, Traffic Steering)
#
def donothing(x,y):
''' a funtion that just returns its two inputs, needed for a map operation to joint the
... |
""" pixel neighborhood definitions """
import numpy as np
nbrlist = None
neighbors = None
nbr_range = np.arange(-1,2)
lattice_basis = None
def gaussian_mask(sites, radius, sigma_squared=1, a=None, cutoff=0.01):
if a is None:
a = 1/(np.sqrt(2*sigma_squared*np.pi))
id_range = np.arange(-radius,radius+1)
dist... |
import logging
from ctypes import *
import math
from typing import Tuple, Dict, Any, Optional
from dmm.parsers.fixed_size_data import FixedSizeRawData, FixedSizeData
from dmm.definitions import (
ElectricUnit,
UnitScale,
DMMRangeMode,
DMMMode,
DMMCaptureMode,
)
logger = logging.getLogger(__file__... |
# ----------------------------------------------------------------------------------
# # Visualising the Bitcoin Price Series
# ----------------------------------------------------------------------------------
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates impor... |
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http... |
# Copyright (c) 2019, CRS4
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribu... |
'''
Decode model from alpha
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from torch.autograd import Variable
from utils.compute_flops import *
from nets.se_module import SELayer
import argparse
from pdb import set_trace as br
__all__ = ['resnet_decode']
def _we... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 24 03:19:10 2018
@author: akshita
"""
import sys
import warnings
import os, argparse
warnings.simplefilter("ignore")
import spacy
import cv2, numpy as np
from keras.models import model_from_json
from keras.optimizers import SGD
from sklearn.externals import joblib
from ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
HTW-PV3 - Weatherdata functions
SPDX-License-Identifier: AGPL-3.0-or-later
"""
__copyright__ = "© <NAME>"
__license__ = "GNU Affero General Public License Version 3 (AGPL-3.0)"
__url__ = "https://www.gnu.org/licenses/agpl-3.0.en.html"
__author__ = "Ludee;"
__versio... |
from typing import Optional, List, Tuple, Generator
from ..models import Teacher, Subject, Lessons
from datetime import datetime, timedelta
from ..utils import datetime_now_tz, get_last_date_of_month, get_weekday_number
from dataclasses import dataclass
from ..data_classes.teachers import DailyLessonsReport, WeeklyLess... |
"""Abstractions for common serialization formats."""
import json
import re
from enum import Enum
from pathlib import Path
from typing import IO
from typing import TYPE_CHECKING
from typing import Any
from typing import Dict
from typing import NamedTuple
from typing import Optional
from typing import Union
import yam... |
#
# CanvasRenderQt.py -- for rendering into a ImageViewQt widget
#
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
from ginga.qtw.QtHelp import QtGui, QtCore, QFont, QPainter, QPen, \
QPolygonF, QPolygon, QColor, QPainterPath
from ginga import colors
f... |
from typing import Optional, Tuple, Union
import torch
from torch.autograd import Function
from torch.cuda.amp import custom_bwd, custom_fwd
import torchsparse.backend
from torchsparse import SparseTensor
from torchsparse.nn import functional as F
from torchsparse.nn.utils import get_kernel_offsets
from torchsparse.u... |
import itertools
import math
import zarr
try:
from itertools import accumulate
except ImportError:
# see https://docs.python.org/dev/library/itertools.html#itertools.accumulate
import operator
def accumulate(iterable, func=operator.add):
"Return running totals"
# accumulate([1,2,3,4,5]... |
# -*- coding: utf-8 -*-
# @Author : 3zz
# @Time : 2019-08-08 19:19
# @File : usercf.py
from __future__ import division
import reader
import math
import operator
def transfer_user_click(user_click):
"""
get item by user_click
:param user_click: key userid, value: [itemid1, itemid2]
:return: dict, k... |
# Copyright (c) 2022 Boston Dynamics, Inc. All rights reserved.
#
# Downloading, reproducing, distributing or otherwise using the SDK Software
# is subject to the terms and conditions of the Boston Dynamics Software
# Development Kit License (20191101-BDSDK-SL).
"""Provides a programmatic estop to stop the robot."""
... |
# FIXME: Dicts should be replaced by OrderedDict when 3.6 support is dropped
from pathlib import Path
from typing import Dict, List, Optional, Union
from pydantic import BaseModel
from pydantic.networks import IPvAnyInterface, IPvAnyNetwork
from typing_extensions import Literal
from .board import (
Board,
De... |
# SPDX-License-Identifier: MIT
# Copyright (c) 2019 Akumatic
import cv2, argparse, numpy
##############
# Exceptions #
##############
class UnsupportedFileType(Exception):
pass
class UnsupportedNumberOfPages(Exception):
pass
class MissingArg(Exception):
pass
####################
# Argument Parsing #
#... |
'''
This example collects data from one or more Vernier GDX devices and displays and
graphs the readings.
Note that if your computer is slow, the graph may not keep up with the data collection.
This program supports up to three sensors.
You can stop data collection with a control-c keypress.
This program uses ... |
"""Command runners.
The :class:`~isct.runner.Runner` is responsible for evaluating commands. By
providing differents implementations for :meth:`~isct.runner.Runner.run` the
behaviour can be changed to, for example, logging commands, running commands
sequentially, to emitting instructions for parallel evaluation.
"""
i... |
import numpy as np
import pandas as pd
FEATURES = [
'x',
'x_diff_1', 'x_diff_2','x_diff_3','x_diff_4',#'x_diff_5','x_diff_6',#'time_diff',
'norm_diff_1', 'norm_diff_2','norm_diff_3','norm_diff_4',
'mean_2','mean_4','mean_6',# 'mean_20', 'mean_50',
'std_2','st... |
"""
Author : <NAME>
Date: 01.01.2020
Project Details:
1- Calculating the amortization and sinking fund. Also constructing a table with our calculation. Please see the project itself. --> https://github.com/francose/amortizationSchedule
2- Calculating Present and Accumalted Value. Please see the project itself. --... |
# This file is part of the MapProxy project.
# Copyright (C) 2012 Omniscale <http://omniscale.de>
#
# 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... |
'''basics'''
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
from collections import Counter
from typing import Iterable, Tuple
'''features'''
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text im... |
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import cv2
from warper import rotation_matrix
my = 30 / 720 # meters per pixel in y dimension
mx = 3.7 / 700 # meters per pixel in x dimension
def fit_lines(img_shape, left_line_pixel_indices, right_line_pixel_indices):
l_fit_c... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : Apr-17-20 02:45
# @Author : <NAME> (<EMAIL>)
# @Link : http://example.org
import os
import json
import pandas as pd
import numpy as np
import torch
from torch import nn, optim
from torch.autograd import Variable
import torch.nn.functional... |
"""
Module for testing functionality associated with calculating the
plasma frequency.
- `~plasmapy.formulary.frequencies.plasma_frequency`
- `~plasmapy.formulary.frequencies.plasma_frequency_lite`
- `~plasmapy.formulary.frequencies.wp_`
"""
import astropy.units as u
import numpy as np
import pytest
from astropy.cons... |
from pdb import set_trace as T
import gym
import numpy as np
from griddly.util.vector_visualization import Vector2RGB
from griddly import GymWrapper
class ValidatedMultiDiscrete(gym.spaces.MultiDiscrete):
"""
The same action space as MultiDiscrete, however sampling this action space only results in valid act... |
import fileinput
import math
from collections import defaultdict
from queue import PriorityQueue
from typing import Dict, List, Optional, Tuple
import numpy as np
Coords = Tuple[int, int]
def main(input_path: Optional[str] = None): # pylint: disable=too-many-locals
r"""
>>> from _pytest.monkeypatch import ... |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 ... |
import scipy as sp
from scipy.sparse.linalg import spsolve
from matplotlib import pyplot as plt
def Problem2Real():
beta = 0.95
N = 1000
u = lambda c: sp.sqrt(c)
psi_ind = sp.arange(0,N)
W = sp.linspace(0,1,N)
X, Y = sp.meshgrid(W,W)
Wdiff = Y-X
index = Wdiff <0
Wdiff[index] = 0
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.