text stringlengths 3.07k 12.6k |
|---|
#!/usr/bin/env python
import csv, math, numpy, random, sys
import xml.etree.ElementTree as ElementTree
# random.seed(44) # for testing
def setup_svg(width, height):
# SVG output.
ElementTree.register_namespace('', 'http://www.w3.org/2000/svg')
svg = ElementTree.Element(
'{http://www.w3.org/2000/... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
"""
Saved Query API module.
"""
import sys
import click
import requests
from lecli import api_utils
from lecli import response_utils
def _url(provided_path_parts=()):
"""
Get rest query url of account resource id.
"""
ordered_path_parts = ['query', 'saved_queries']
ordered_path_parts.extend(provi... |
# -*- coding: utf-8 -*-
"""
Infoblox host record management.
functions accept api_opts:
api_verifyssl: verify SSL [default to True or pillar value]
api_url: server to connect to [default to pillar value]
api_username: [default to pillar value]
api_password: [default to pillar value]
"""
# Import Py... |
import pandas as pd
import re
import torchvision
from PIL import Image
import clip
import torch
import os
from torch.utils.data import Dataset, DataLoader
from transformers import CLIPTokenizer, CLIPProcessor
# import pandas as pd
# gtin_mapping=pd.read_csv(os.path.join(os.getcwd(),"dvc-manual/520_gtin_product_name.csv... |
import numpy as np
from interfaces.SentenceOperation import SentenceAndTargetOperation
from tasks.TaskTypes import TaskType
from nltk import tokenize
"""
Adds a positive labelled emoji as well as a positive emoteicon for positive sentences and vice versa.
And neutral smiley for unlabelled and neutral sentences.
Sinc... |
# SPDX-License-Identifier: Apache-2.0
# Copyright 2019 Blue Cheetah Analog Design 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
#
# U... |
# Copyright (c) 2015 <NAME> <<EMAIL>>
# Author: <NAME> <<EMAIL>>
#
# 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... |
#! /usr/bin/python
# -*- coding: UTF-8 -*-
# Copyright 2012-2018 <NAME>, TestLink-API-Python-client developers
#
# 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... |
import json
import os
import queue
import socket
import struct
import subprocess
import sys
import threading
import traceback
import pathlib
# noinspection PyUnresolvedReferences
import bpy
my_args = {}
if "--" in sys.argv:
args_list = sys.argv[sys.argv.index("--") + 1:]
my_args = {args_list[i - 1]: args_list... |
from typing import Callable, Union, List
from inspect import signature
import warnings
import numpy as np
import scipy as sp
import pandas as pd
from scipy.special import comb, binom
from scipy.optimize import linprog
from ._helper import *
# This is not a solution I like, but I don't want to spam the user with
# ... |
import copy
from PySide2.QtGui import QBrush
from PySide2.QtGui import QColor
from PySide2.QtGui import QPen
import math
import random
class Neuron:
def __init__(self, previous=None):
self.inputs = []
self.weights = []
self.output = 0.0
if previous:
for input_ in previ... |
import requests, re, json
class Angle:
def __init__(self, deg : int, min : int, sec : float):
self.deg = deg
self.min = min
self.sec = sec
class AnglePair:
def __init__(self, dec : Angle, asc : Angle):
self.dec = dec
self.asc = asc
SPEC_TYPE_REGEX = r"Spectral type:[ ... |
"""
Simple cleaner to re-confirm number of words in CSV file prepped for IBM Watson
"""
#-------------------------------------------#
# Import dependencies #
#-------------------------------------------#
import time
import re
import string
import numpy as np
import pandas as pd
import matplotlib... |
from tkinter import*
from tkinter.ttk import*
import paho.mqtt.client as mqtt #import paho-mqtt as mqtt client
import json #import json library
import time
broker_address="cf8da10a-0d29-41a9-9c59-beb2051be054.ka.bw-cloud-instance.org"
# root = Tk()
# root.wm_title("Gewächshaus GUI")
# root.config(background = "#FFFFFF... |
# -*- coding: utf-8 -*-
"""
User defined functions for LightPipes for Python
"""
import numpy as _np
from .field import Field
from .core import BeamMix
def RowOfFields(Fin,Ffield,Nfields,sep,y=0.0):
"""
*Inserts an row of fields in the field*
:param Fin: input field
:type Fin: Field
:param F... |
"""Implementation of EdgeConv using arbitrary functions as h
for more information see https://git.rwth-aachen.de/niklas.langner/edgeconv_keras
authors: <NAME>, <NAME>
"""
import tensorflow as tf
import tensorflow.keras.layers as lay
from tensorflow import keras
class SplitLayer(lay.Layer):
""" C... |
from tkinter import *
from tkinter import filedialog, ttk, messagebox
from tkinter.ttk import *
import tkinter as tk
import csv
import defs.database
from defs.check import calcTime, logCheck, checkTimeDif
from defs.database import insertDataBase
########################################################################... |
""" Convert and load Cameca and L'image look-up tables.
Module to load Look-Up Tables (LUTs) from the Cameca-supplied lut files and
the L'image colour table file. Loaded LUTs are converted to Matplotlib
Colormaps, and registered with Matplotlib. Use mpl.colormaps() to see all
registered Colormaps and m... |
from optgasmix.gases import Gas, GasMixture
from optgasmix.constants import NA, kB, pi
def shomates_cp(x, A, B, C, D, E):
# x = T / 1000 in Kelvin
# returns J/(mol*K)
return A + B * x + C * x**2 + D * x**3 + E/x**2
# between 298 and 6000 K
# almost constant, and equal to 5R/2, as expected for a monatomic... |
"""
InFi-Reuse functions
"""
import tensorflow as tf
from tensorflow.keras import layers
from .modality_nn import build_image_nn, build_video_nn, build_audio_nn, build_text_nn, build_vec_nn
import time
from pathlib import Path
import os
def build_infi_reuse(modality, input_shape, n_dense, dropout=0.5,
... |
import torch
from torch.utils.data import Dataset
import os
from collections import defaultdict
import numpy as np
from torchvision import transforms
import redis
from collections import Counter
import utils
from densenet import Model
from retrieve_images import retrieve_image
from joblib import Parallel, delayed
impor... |
from __future__ import absolute_import, division, print_function
import os
import sys
import numpy as np
import pytest
import tables as tb
import subprocess
path = os.path.realpath(__file__)
sys.path.append(os.path.dirname(os.path.dirname(path)))
directory = os.path.dirname(path)
db_exp_file = directory + '/2step_non_... |
#!/usr/bin/env python
# coding: utf-8
# This calculates MJDs and BJDs of light curve maxima, as observed at MacAdam, U Louisville, and Mt. Kent in Australia
# created 2018 Jan 02 by E.S.
import astropy
from astropy.io import fits
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
from o... |
# Here are the libraries I am currently using:
import math
import random
# You are welcome to add any of these:
# import time
# import numpy
# import scipy
# import sys
from matts_tree_helpers import get_coords_pixels, FrameManager
# Play with these values to change how coarse the 3D Fire effect is.
# Smaller value... |
import operator as op
import pytest
from xy import simeq
class ElementwiseAddition:
"""
For objects that implement a elementwise addition and subtraction.
"""
base_cls = None
@pytest.fixture
def equiv(self):
return [tuple]
@pytest.fixture
def add_uv(self, u, v):
re... |
"""Tests for everything that is defined within throttling.py."""
from urllib.parse import quote
from unittest.mock import patch
from django.core.cache import cache as default_cache
from django.core.exceptions import ImproperlyConfigured
from rest_framework.test import force_authenticate
from rest_framework.test impo... |
import torch
import torch.nn.functional as F
import gdnet_lib
import utils
def calc_cost(left_image, right_image, disparity, kenel_size, method):
batch, channel, height, width = left_image.size()
min_disparity, max_disparity = disparity
assert left_image.is_contiguous()
assert right_image.is_contiguous... |
import pandas as pd
import json
def create_hourly_elective_prob_json(
path_to_patient_df_csv: str, output_directory: str = "."
) -> pd.DataFrame:
"""
This function uses data from "patient_df.csv" to create "hourly_elective_prob.json". This is needed
to create the forecast. It is important that "patien... |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import Optional, Union
import torch
import torch.nn as nn
import torchvision
from egg.core.interaction import LoggingStrategy
from... |
import numpy as np
import torch
from torch.distributions import normal
from torch.distributions import dirichlet
from typing import List, Dict
__all__ = [
'ensemblecategoricals',
'ensembledirichlets',
'diagonalgaussianoverlogits',
'isotropicgaussianoverlogits',
'diagonalgaussianoverlogdirichlets'... |
from __future__ import print_function
import numpy
import ctypes as C
from pytest import raises
try:
from mock import patch, Mock
except ImportError:
from unittest.mock import patch, Mock
from kernel_tuner.c import CFunctions, Argument
from kernel_tuner.core import KernelSource, KernelInstance
def test_rea... |
from util.symmetric_key import SymmetricKey
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
import base64
import logging
import binascii
backend = default_backend()
class EnvelopeFileCryptor(object):
def __init__(self, symmetri... |
import datetime
from django.contrib.auth import get_user_model
from django.http import Http404
from django.shortcuts import get_object_or_404
from rest_framework.exceptions import PermissionDenied
from rest_framework.validators import UniqueTogetherValidator
from rest_framework import serializers
from apps.app.models ... |
#1- Definir una función max() que tome como argumento dos números y devuelva el mayor de ellos
def max(num1,num2):
if num1 > num2:
return num1
else:
return num2
print(max(2,3))
#Definir una función max_de_tres(), que tome tres números como argumentos y devuelva el mayor de ellos.
def max(num1... |
# -*- coding: utf-8 -*-
# Use RMSProp as optimizer and MSELoss as loss function
import os
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
SEED = 1
np.random.seed(SEED)
torch.manual_seed(SEED)
DIAGRAM_DIR = "diagrams/q2"
SHOW_DIAGRAM = False
SAVE_DIAGRAM = True
def diagram_func(... |
#!/usr/bin/env python
# encoding: utf-8
from redisco import models as db
from application.utils import format_now_datetime
from .user import User
__all__ = ['Category', 'Tag', 'Post', 'POST_STATUS']
POST_STATUS = ('PUBLISHED', 'DELETED', 'EDITING', 'SCHEDULING')
COMMENT_STATUS = ('APPROVED', 'PENDING', 'DELETED')
... |
from collections.abc import Iterable
from datetime import date
from typing import Union
from fpdf import FPDF
from afvalwijzer.models import Adres, Regel, Straat
PAGE_WIDTH = 210
MARGIN_LEFT = 31
MARGIN_RIGHT = 29
MARGIN_TOP = 10
MARGIN_BOTTOM = 27
CONTENT_WIDTH = PAGE_WIDTH - MARGIN_LEFT - MARGIN_RIGHT
FONT_FILE =... |
from __future__ import print_function
import argparse
import os
import shutil
def parse_args():
# Construct argument parser.
parser = argparse.ArgumentParser(description = "Utility to extract frames from videos.")
parser.add_argument("--filename", type = str, help = "Video filename.", required = True)
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gzip
import os
import re
import tarfile
import argparse
from six.moves import urllib
from tensorflow.python.platform import gfile
from tqdm import *
import numpy as np
from os.path import join as pjoin... |
# @ Copyright Inria, Ecole Polytechnique
# Shared under the MIT license https://opensource.org/licenses/mit-license.php
# This file contains all the functions that are used in the time detection
# The main part of the code is the function find_time, that will be used elsewhere in the code
# The other functions are a... |
from fhirclient import client
from fhirclient import models
import fhirclient.models.fhirdate as fhirdate
import fhirclient.models.questionnaireresponse as qresponse
import fhirclient.models.fhirreference as fhirref
import fhirclient.models.observation as obs
from fhirclient.models.bundle import Bundle
from fhirclient.... |
import pandas as pa
import pymongo
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from pymongo import MongoClient
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer,TfidfTransformer
from sklearn.naive_bayes ... |
"""
The MIT License (MIT)
Copyright © 2021 <NAME> (https://walkline.wang)
https://gitee.com/walkline/remote-wol-micropython
[Customize Button v1.1]
Author: <NAME>
Email: <EMAIL>
GitHub: walkline80
Gitee: walkline
License: MIT
# IMPORTANT: THIS MODULE ONLY TESTED ON ESP32 BOARD
"""
import micropython
from machine im... |
from scipy.sparse import csr_matrix
import fenics as df
import numpy as np
from numpy import arange
from petsc4py import PETSc
import warnings
def refine(mesh, N=1):
for i in range(N):
mesh = df.refine(mesh)
return mesh
def ExtractDirichletValues(bcs):
if not isinstance(bcs, list):
bc... |
# Copyright (c) 2022, NVIDIA CORPORATION. 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 appli... |
"""
15N–1HN TROSY CPMG
==================
Analyzes 15N constant-time TROSY CPMG relaxation dispersion experiments for
measurement of ΔD NH in protein systems undergoing millisecond-time-scale
exchange dynamics. Resulting magnetization intensity after the CPMG block is
calculated using the (6n)×(6n), two-spin matrix, w... |
"""
Functions for running a Motne Carlo Simulation
"""
import math
import random
def calculate_total_energy(coordinates, box_length, cutoff):
"""
Calculate the total energy of a set of particles using the Lennard Jones potential.
Parameters
----------
coordinates : list
A nested list ... |
from mistletoe.block_token import BlockToken
from mistletoe.span_token import SpanToken
from mistletoe import span_token
import re
import rich
from rich.logging import RichHandler
import logging
FORMAT = "%(message)s"
logging.basicConfig(
level="NOTSET", format=FORMAT, datefmt="[%X]", handlers=[RichHandler()]
)
... |
import numpy as np
import pandas as pd
from candidate_handler import candidates_update
#interdependent modules, it has to be imported like below,otherwise it wont work
import solver as solver
import itertools
#%% Y-WING
#find if there is a key cell in the "rectangular formation y-wing"
def find_rect_key(comb):
#ch... |
import torch
import torch.nn as nn
from piq import FID, ssim, SSIMLoss, LPIPS
import cv2
import numpy as np
class Metrics():
"""
Bag of evaluation metrics.
"""
def __init__(self):
self.res = dict()
self.count = 1e-8
# self.Hausdorff = Hausdorff()
self.PixAcc = PixAcc... |
#!/usr/bin/env python3
"""
This script is like check-basics.py, but specific to the documentation.
It's split off into a separate script, so that it can be easily run on its own.
"""
import re
import sys
import urllib.parse
import urllib.request
from pathlib import Path
OMZ_ROOT = Path(__file__).resolve().parents[1... |
from nonebot import on_command, on_shell_command, on_notice
from nonebot.typing import T_State
from nonebot.rule import ArgumentParser
from nonebot.adapters.cqhttp.bot import Bot
from nonebot.adapters.cqhttp.event import Event, GroupMessageEvent, PokeNotifyEvent
from .data_source import get_mcstatus, get_mc_uuid, get_... |
import torch
import torch.nn as nn
import random
random.seed(1234)
class Encoder(nn.Module):
def __init__(self, input_dim, emb_dim, hid_dim, dropout):
super().__init__()
self.hid_dim = hid_dim
self.embedding = nn.Embedding(input_dim, emb_dim)
self.rnn = nn.GRU(emb_dim, hid_dim) # ... |
# encoding=utf-8
import base64
import json
import os
import ssl
import urllib2
import urlparse
import socket
from .docker_client import DockerClient
__all__ = ['PluginSDK', 'PluginSDKException']
TIMEOUT = 10
CONFIG_MAX_SIZE = 1024 * 1024
DCE_CONTROLLER_DB_PATH = os.getenv('DCE_CONTROLLER_DB_PATH') or '/var/local/dc... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "<NAME>"
__version__ = "1.0.0"
__license__ = "MIT"
__copyright__ = "Copyright 2021, @MeganeBoujeant"
from tree_node import TreeNode
class HuffmanCompression:
""" Class of Huffman Compression. """
def __init__(self, sequence: str):
self.seq... |
from django.contrib.auth import authenticate, get_user_model, update_session_auth_hash
from django.contrib.auth.forms import SetPasswordForm
from django.utils.translation import ugettext_lazy as _
from django.utils.http import urlsafe_base64_decode
from django.contrib.auth.tokens import default_token_generator
from res... |
# Copyright 2016 NEC 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 ag... |
from flask import Flask, render_template, redirect, session, url_for, request
from splitwise import Splitwise
from splitwise.expense import Expense
from splitwise.user import ExpenseUser
import config as Config
import sys
import csv
import datetime
import iso8601
from dateutil import tz
import os
import io
import panda... |
# Copyright 2019 Google 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/LICENSE-2.0
#
# Unless required by applicable l... |
################################################################################
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this... |
#!/usr/bin/python
#################################################
# Basic Classifier #
# Constructing a simple data set #
# Linear classifier #
# Nearest neighbors classification #
# Sk. <NAME> #
#################################################
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial ... |
import numpy as np
from numpy.linalg import norm
import tensorflow as tf
from sklearn.cluster import KMeans
import random
class KMeansTF26:
def __init__(self, n_clusters, max_iter=100, random_state=123):
self.n_clusters = n_clusters
self.max_iter = max_iter
self.random_state = random_state
... |
'''
Test the accuracy of similarity estimation using data sketches
Must be using Python 2 as pyhash does not support Python 3
'''
import time, logging, random, struct
import pyhash
import numpy as np
from datasketch.hyperloglog import HyperLogLog
from datasketch.minhash import MinHash
from datasketch.b_bit_minhash impo... |
#!/usr/bin/env python3
"""
Utility functions
=================
"""
from collections import Iterable
import numpy as np
import dynet as dy
from . import operations
def _default_value(argument, default):
"""Returns ``default`` if ``argument`` is ``None``"""
if argument is None:
return default
els... |
import sys
from collections import defaultdict
from copy import copy
from typing import Any, Dict, Callable, List
JUMPS = {
1: 4,
2: 4,
3: 2,
4: 2,
5: 3,
6: 3,
7: 4,
8: 4,
9: 2,
}
class Operator:
"""An Intcode operator with potential parameters.
Attributes:
c... |
import collections
import os
import json
import numpy
import requests
from django import template
from django.conf import settings
from django.urls import reverse
from mxlive.utils import xdi
GOOG20_COLORS = [
"#3366cc", "#dc3912", "#ff9900", "#109618", "#990099", "#0099c6", "#dd4477", "#66aa00", "#b82e2e",
... |
'''@file ops.py
some operations'''
import tensorflow as tf
def pyramid_stack(inputs, sequence_lengths, numsteps, axis=2, scope=None):
'''
concatenate each two consecutive elements
Args:
inputs: A time minor tensor [batch_size, time, input_size]
sequence_lengths: the length of the input se... |
"""
京东验证码识别
---
JDcaptcha(cpc_img_path, pcp_show_picture_path) 传入图片路径
JDcaptcha_base64(cpc_img_path_base64, pcp_show_picture_path_base64) 传入图片base64值
"""
import io
from PIL import Image, ImageDraw
import numpy as np
import base64
# 调整以下几个参数可以有效改变速度与准确度的关系
# 颜色压缩度
GRAIN = 16
# 区块大小
BLOCK = 16
# 压缩倍数
ZOOM = 3
def JDc... |
"""
Copyright 2021 Max-Planck-Gesellschaft
Code author: <NAME>, <EMAIL>
Embodied Vision Group, Max Planck Institute for Intelligent Systems, Tübingen
This source code is licensed under the MIT license found in the
LICENSE.md file in the root directory of this source tree or at
https://opensource.org/licenses/MIT.
"""
... |
#################################################################################
# The Institute for the Design of Advanced Energy Systems Integrated Platform
# Framework (IDAES IP) was produced under the DOE Institute for the
# Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021
# by the softwar... |
"""Collect Bach chorales dataset."""
import argparse
import logging
import operator
import random
from pathlib import Path
import joblib
import music21.converter
import muspy
import tqdm
from arranger.utils import load_config, setup_loggers
# Load configuration
CONFIG = load_config()
NAMES = {
"soprano": "Sopra... |
import pytest
def test_analysis_step_2_3(registry, upgrader, analysis_step_1, threadlocals):
value = upgrader.upgrade('analysis_step', analysis_step_1, current_version='2', target_version='3', registry=registry)
assert 'signal of all reads' in value['output_file_types']
assert 'signal of multi-mapped read... |
import datetime
import time
import os
import json
from modules.WordleAnalyzer import WordleAnalyzer
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.common.by import By
def GetShadowRootObject (... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import datetime
import os.path
import asyncio
import logging
import argparse
import websockets
import socketserver
import configparser
import os
from collections import deque
from urllib.parse import urlparse, parse_qs
from ansi2html import Ansi2HTMLConverter
from os import ... |
import time
import sys
import os
import numpy
import gzip
import zipfile
import cPickle
import random
import PIL.Image
try:
import magic
ms = magic.open(magic.MAGIC_NONE)
ms.load()
except ImportError: # no magic module
ms = None
class fx_UnpickleError(Exception):
pass
def fx_pickle(file... |
from itertools import chain
import sklearn.metrics as metrics
import torch.nn.functional as F
import torch.optim as opt
import torch.utils.data
import torch.utils.data
from datasets import *
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class LSTMbase:
def __init__(self, vec_size=1, nu=... |
# -*- coding: utf-8 -*-
import os, sys
is_py3 = (sys.version_info[0] == 3)
python_dir = "python27"
if is_py3:
python_dir = "python36"
current_path = os.path.dirname(os.path.abspath(__file__))
root_path = os.path.abspath( os.path.join(current_path, os.pardir))
if root_path not in sys.path:
sys.path.append(root... |
"""
This file contains some frame inspection methods. No class to be instanced as these do not need a state.
"""
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import numpy as np
from utilities import plotting
import core.properties as P
def plot_frame_spectra(original_frame, original_bandpass=None, de... |
import csv
import logging
import multiprocessing
import time
from concurrent.futures import ThreadPoolExecutor
from itertools import repeat
from pathlib import Path
import pandas as pd
import requests
THREAD_POOL = multiprocessing.cpu_count()
session = requests.Session()
session.mount(
"https://",
requests.a... |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import numpy as np
import rotation
import shapes
import heuristic_perception
from base_agent.dialogue_objects import SPEAKERLOOK, is_loc_speakerlook
from base_agent.util import ErrorWithResponse
from util import pos_to_np, to_block_center, to_block_pos
from wor... |
"""
Utils
"""
from ios_device.util.service_info import MyServiceInfo
__all__ = ['DictAttrProperty', 'DictAttrFieldNotFoundError']
import socket
import struct
import threading
from zeroconf import Zeroconf, ServiceBrowser, ServiceInfo
_NotSet = object()
class cached_property(object):
def __init__(self, func):
... |
"""TIMEWAVE
Create periodic events over periods of human time"""
# To "and" use min(), to "or" use max()
#
# Copyright (c) 2017 DevicePilot Ltd.
#
# 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 So... |
import numpy as np
import torch
from torch import nn
from . import distance
from typing import Optional, Union, Callable
def sigma_median(x: torch.Tensor, y: torch.Tensor, dist: torch.Tensor) -> torch.Tensor:
"""
Bandwidth estimation using the median heuristic :cite:t:`Gretton2012`.
Parameters
------... |
# Prints all symbols, choices, menus, and comments that reference a symbol with
# a particular name in any of their properties or property conditions.
# Demonstrates expression fetching and walking.
#
# Usage:
#
# $ make [ARCH=<arch>] scriptconfig SCRIPT=Kconfiglib/examples/find_symbol.py SCRIPT_ARG=<name>
#
# Exampl... |
from datacube import Datacube
from datacube.api.query import query_group_by
import numpy as np
from collections import Sequence
from types import SimpleNamespace
from pathlib import Path
from datacube.testutils import (
mk_sample_dataset,
mk_test_image,
)
from datacube.testutils.io import write_gtiff, rio_slur... |
import random
import uuid
from plone.uuid.interfaces import IUUID
from persistent import Persistent
from repoze.catalog.catalog import Catalog as BaseIndexer
from repoze.catalog.indexes.field import CatalogFieldIndex
from repoze.catalog.indexes.text import CatalogTextIndex
from repoze.catalog.indexes.keyword import Ca... |
# 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 python3
import argparse
from re import compile, match
from sys import stdin, exit
from time import time
### FUNCTIONS ###
def is_base(base_pattern, str):
"""
base_pattern is a compiled python3 regex.
str is a string object.
return True if the string match the base_pattern or False if ... |
import gym
from gym import spaces, logger
import numpy as np
from gym.envs.registration import register
from gym_snake.envs.snake_base import SnakeEnv
from gym_snake.base.direc import Direc
class SnakeGoalEnv(SnakeEnv, gym.GoalEnv):
"""
Description:
Implementation of the classic game of Snake as a grid... |
import imutils
import pickle
import random
import numpy as np
import copy
import glob
import time
import cv2
import os
import re
from itertools import repeat
AVATAR_SIZE = 50
def load_palette(config=None):
if config:
pal_path = config['palpath']
else:
pal_dir = os.path.abspath(os.path.join(o... |
# COCO style evaluation for custom datasets derived from AbstractDataset
# Warning! area is computed using binary maps, therefore results may differ
# because of the precomputed COCO areas
# by botcs@github
import numpy as np
import torch
import pycocotools.mask as mask_util
from mega_core.data.datasets.abstract impo... |
import argparse
import os
import os.path as osp
import numpy as np
import onnx
import onnxruntime as ort
import torch
from mmcv.ops import get_onnxruntime_op_path
from mmcv.tensorrt import (TRTWraper, is_tensorrt_plugin_loaded, onnx2trt,
save_trt_engine)
from mmcv.visualization.image import ... |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
#!/usr/bin/env python
# ... |
import time
import datetime
from collections import deque
from enum import IntEnum
from queue import Queue
from uptime import uptime
from data.observable import Observable
from data.configurations import ConfigurationManager
class AlertCodes(IntEnum):
OK = 0
# medical alerts
PRESSURE_LOW = 1 << 0
P... |
from persiantools import utils
EN_TO_FA_MAP = {
"0": "۰",
"1": "۱",
"2": "۲",
"3": "۳",
"4": "۴",
"5": "۵",
"6": "۶",
"7": "۷",
"8": "۸",
"9": "۹",
}
AR_TO_FA_MAP = {
"٠": "۰",
"١": "۱",
"٢": "۲",
"٣": "۳",
"٤": "۴",
"٥": "۵",
"٦": "۶",
"٧": "۷",
... |
from __future__ import division, print_function
from warnings import warn
import numpy as np
from Florence.Tensor import makezero, makezero3d, unique2d
class GeometricPath(object):
"""Construct a geometric path for mesh extrusions
"""
def __init__(self):
pass
def ComputeExtrusion(self, base_... |
import argparse
import latextools
from . import diagram
def parse_gate(gate_str):
name = gate_str.translate({ord(digit): '-' for digit in '0123456789'}
).split('-')[0]
args = tuple(int(arg) for arg in gate_str[len(name):].split(','))
return name, args
def draw_diagram(n_qubi... |
#Licensed under Apache 2.0 License.
#© 2021 Battelle Energy Alliance, LLC
#ALL RIGHTS RESERVED
#.
#Prepared by Battelle Energy Alliance, LLC
#Under Contract No. DE-AC07-05ID14517
#With the U. S. Department of Energy
#.
#NOTICE: This computer software was prepared by Battelle Energy
#Alliance, LLC, hereinafter the Cont... |
##from: https://github.com/mpariente/pystoi
import numpy as np
import scipy
from scipy.signal import resample_poly
EPS = np.finfo("float").eps
def _resample_window_oct(p, q):
"""Port of Octave code to Python"""
gcd = np.gcd(p, q)
if gcd > 1:
p /= gcd
q /= gcd
# Properties of the an... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.