text stringlengths 3.07k 12.6k |
|---|
'''
Helper classes for writing tests with this test library.
* :func:`log_call`
A wrappper around Popen which behaves like
`subprocess.check_call()` but will pipe output to the
log at a low verbosity level.
* :func:`cacheresult`
A function decorator which will cache results for a function given the
... |
from tensorflow.keras.models import load_model
from tensorflow.keras.metrics import categorical_accuracy, top_k_categorical_accuracy
from tensorflow.keras.applications.mobilenet import preprocess_input
from flask import Flask, request, flash, jsonify, render_template, url_for
# from skimage import io
from urllib.reques... |
from webpie import WPApp, WPHandler, app_synchronized
from webpie import Response as BaseResponse
from configparser import ConfigParser
from UI import UConDBUIHandler
from wsdbtools import ConnectionPool
from ucondb import UConDB, Version
from ucondb.backends import UCDPostgresDataStorage
try: from ucondb.backend... |
try:
import sim
except:
print ('--------------------------------------------------------------')
print ('"sim.py" could not be imported. This means very probably that')
print ('either "sim.py" or the remoteApi library could not be found.')
print ('Make sure both are in the same folder as this file,'... |
# -*- coding: utf-8 -*-
"""Create and Manage Launch Templates"""
import os
import time
import boto3
import botocore
def create_security_group(security_groups=None, ips=None, ports=None, rules=None, ec2=boto3.resource("ec2")):
"Create Security Group"
vpc_id = ec2.meta.client.describe_vpcs().get('Vpcs', [{}])[... |
# -*- coding: utf-8 -*-
# [TODO] - Support for Python2
# [TODO] - Add testsuite
# [TODO] - Support for GitHub
# [TODO] - Support for Bitbucket
# [TODO] - Support for Asana
# [TODO] - Support for GitLab
# [TODO] - Support for Jira
import pkg_resources # part of setuptools
import click
from os import getcwd, path
from... |
from mock import patch
from nose.tools import assert_raises, assert_equal
import requests
from matplotlib import image as img
import os
import yaml
from StringIO import StringIO
import numpy as np
from ..map import Map
def test_init_type_fail():
with open(os.path.join(os.path.dirname(__file__), 'fixtures', 'broke... |
import yaml
import os
import sys
import numpy as np
import cv2 as cv
import yolov5_module
import gripper_control as gripper
from realsense_wapper import realsense
from franka.FrankaController import FrankaController
def read_cfg(path):
with open(path, 'r') as stream:
out = yaml.safe_load(stream)
ret... |
from django.contrib.auth.models import User
from django.test import TestCase, Client
from django.urls import reverse
from ..models import Plan, Editor, Place
import datetime
class EditViewTest(TestCase):
"""Initialize setUp for all Edit and View Planner testing."""
def setUp(self):
"""Initialize use... |
from http import HTTPStatus
from typing import Any, Dict, List
import nanoid
from algoliasearch.search_index_async import SearchIndexAsync
from fastapi import APIRouter, Depends, HTTPException
from opentelemetry import trace
from pydantic import BaseModel, parse_obj_as, validate_model
from sqlalchemy import func
from ... |
import regex
import re
import pandas as pd
import regex_utils as ru
import entity_rules as er
from enum import Enum
class MatchType(Enum):
ONE_OR_MORE_MATCH =0
ONE_OR_MORE_EXACT_MATCH =1
ONE_OR_MORE_PARTIAL_MATCH =2
ALL_EXACT_MATCH =3
ALL_PARTIAL_MATCH ... |
#
# Copyright (c) 2016 <NAME>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer... |
import logging
import platform
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib import font_manager, rc
from pathlib import Path
log = logging.getLogger(__name__)
def save_figure(fig, fname=None, **kwargs):
if fname:
Path(fname).parent.mkdir(parents=True, exist_ok=True)
... |
# -*- coding: utf-8 -*-
'''
Return salt data via email
The following fields can be set in the minion conf file::
smtp.from (required)
smtp.to (required)
smtp.host (required)
smtp.port (optional, defaults to 25)
smtp.username (optional)
smtp.password (optional)
smtp.tls (optional, defaults ... |
#!/usr/bin/env python
import classad
import json
import os
import posixpath
import requests
import shutil
import socket
import sys
import time
try:
from urllib.parse import urlparse # Python 3
except ImportError:
from urlparse import urlparse # Python 2
DEFAULT_TIMEOUT = 30
GLUSTER_PLUGIN_VERSION = '1.0.0'
... |
#
# Elliptic Curve Digital Signature Algorithm (ECDSA)
#
# COPYRIGHT (c) 2010 by <NAME> <<EMAIL>>
#
from __future__ import unicode_literals, division, absolute_import, print_function
import hashlib
from os import urandom
from .elliptic import inv, mulf, mulp, muladdp, element
from .curves import get_curv... |
import random
import numpy as np
import time
import json
import keras
from keras.models import Sequential, load_model, Model
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.layers import Input, Dense, Convolution2D, LSTM, concatenate
from keras.optimizers import RMSprop, Adam
from keras.... |
"""
Used for running the module as an independent program rather than using it as a library.
"""
from .. import imagemanipulation, rowlist_to_html_css, data
import argparse
import sys
_sys = sys
from . import info
from PIL import Image
from .._typing import *
class FileTypeWithAppendMode(object):
"""Factory for c... |
import json
import math
import queue
import redis
import socket
import time
import threading
import pytest
from flask import jsonify
from requests.exceptions import HTTPError
def test_local_project_config(mini_sentry, relay):
project_id = 42
config = mini_sentry.basic_project_config(project_id)
relay_c... |
#!/usr/bin/env python3
#
# This file is part of Linux-on-LiteX-VexRiscv
#
# Copyright (c) 2019-2021, Linux-on-LiteX-VexRiscv Developers
# SPDX-License-Identifier: BSD-2-Clause
import json
import argparse
from migen import *
from litex.build.generic_platform import *
from litex.build.sim import SimPlatform
from lite... |
"""Rules for organizing thrift files."""
_thrift_filetype = FileType([".thrift"])
ThriftInfo = provider(
fields=[
"srcs", # The source files in this rule
"transitive_srcs", # the transitive version of the above
"external_jars", # external jars of thrift files
"transitive_external_j... |
import logging
import esgfpid.utils
from esgfpid.utils import loginfo, logdebug, logtrace, logerror, logwarn
LOGGER = logging.getLogger(__name__)
LOGGER.addHandler(logging.NullHandler())
class AssistantOneVersion(object):
def __init__(self, **args):
mandatory_args = ['drs_id', 'data_node', 'pre... |
# Copyright (c) 2021 PaddlePaddle Authors. 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... |
from typing import Tuple
from IMLearn.learners.classifiers import DecisionStump
from IMLearn.metalearners.adaboost import AdaBoost
from utils import *
pio.templates.default = "simple_white"
pio.renderers.default = "browser"
def generate_data(n: int, noise_ratio: float) -> Tuple[np.ndarray, np.ndarray]:
"""
... |
# Copyright (c) 2018 PaddlePaddle Authors. 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 app... |
# Copyright 2017 Division of Medical Image Computing, German Cancer Research Center (DKFZ)
#
# 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
#... |
import math
class function:
TYPE_FUNCTION = "f"
TYPE_OPERATOR = "o"
def __init__(self, eval, t=TYPE_FUNCTION, prec=5, left=True):
self.eval = eval
self.t = t
self.prec = prec
self.left = left
class node:
def __init__(self, val, func=True, unary=True):
self.val ... |
import torch
device = 'cpu'
def _get_min_range(a, b):
a_ = a.repeat(1, b.size(0)).reshape(a.size(0), b.size(0), 2)
b_ = b.repeat(a.size(0), 1).reshape(a.size(0), b.size(0), 2)
c = a[:,0,None].le(b[:,0]).unsqueeze(2) # (N, M, 1)
d = torch.where(c, a_, b_)
return d
def _get_max_range(a, b):
a_... |
# Utilities developed for custom detector using Detectron and TACO dataset.
import cv2
import copy
import os
import csv
import json
import time
from datetime import datetime
from pycocotools.coco import COCO
def ResizeWithAspectRatio(image, width=None, height=None, inter=cv2.INTER_AREA):
dim = None
(h, w) = im... |
# Copyright 1999-2021 Alibaba Group Holding Ltd.
#
# 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 a... |
"""
Evaluate superpixels quality regarding given annotation
Perform experiment with specified parameters and export output statistic
per image if the output path is given
Sample usage::
python run_eval_superpixels.py \
-imgs "data-images/drosophila_ovary_slice/image/*.jpg" \
-segm "data-images/dro... |
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions a... |
# Copyright 2020 DeepMind Technologies 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
# Copyright 2018 The TensorFlow Authors. 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 appl... |
#!/usr/bin/env python
# Copyright 2019 <NAME>
#
# 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... |
import ipas.collection_no_db.iceagg_collection as collect
import numpy as np
import time
from dask_jobqueue import SLURMCluster
from dask.distributed import Client
import dask
import pickle
import argparse
import time
import sys
def start_client(num_workers):
'''
initialize dask client
'''
cluster = SL... |
"""
Music Metadata - EDI is a base library for several EDI-based formats by CISAC,
most notably Common Works Registration (CWR) and Common Royalty Distribution
(CRD).
This file contains field descriptors."""
import html
from collections import OrderedDict
from .errors import *
class EdiField(object):
"""Base c... |
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA, KernelPCA
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_circles
from sklearn.preprocessing import MinMaxScaler
from sklearn.manifold import TSNE
#repace it with MulticoreTSNE
#from MulticoreTSNE import Mu... |
from re import L
from flask import Flask
from flask import jsonify
from flask import request
from flask_restful import Api, Resource, reqparse
import json
import sys
from get_details import get_name
from process_swipe import process_swipe
import requests
import random
from eventlet import wsgi
import eventlet
from redi... |
import random
import torch.utils.data
from torch import nn, optim
from MultitaskClassifier import MTLCNN
from Util import Util
from zz.autoEncoder import Autoencoder
from dataLoader import DataLoader
def main():
TEXTURE_LABELS = ["banded", "blotchy", "braided", "bubbly", "bumpy", "chequered", "cobwebbed", "crac... |
import torch
import torch.nn.functional as F
import math
import os
def conv3D_output_shape_f(i, input_shape, kernel_size, dilation, padding, stride):
"""
Calculate the original output size assuming the convolution is nn.Conv3d based on
input size, kernel size, dilation, padding and stride.
"""
ret... |
# -*- coding: utf-8 -*-
import csv
import mysql.connector
from mysql.connector import Error
from mysql.connector import MySQLConnection, Error
from mysql_config import connect
def insert_temperature(conn,cursor,date, city_id, T, Tn, Tx, Td, Tg):
query = "INSERT INTO mydb.temperature(date, city_id, T, Tn, Tx, Td, ... |
# $Id$
#
# Copyright (C) 2001-2006 <NAME> and Rational Discovery LLC
#
# @@ All Rights Reserved @@
# This file is part of the RDKit.
# The contents are covered by the terms of the BSD license
# which is included in the file license.txt, found at the root
# of the RDKit source tree.
#
"""testing code inspired by... |
"""
Suite of tests for Luci fitting function on a single synthetic spectrum just to test that the fitting algorithm isn't
giving crazy values!
"""
import numpy as np
from astropy.io import fits
from scipy import interpolate
from LUCI.LuciFit import Fit
from LUCI.LuciFunctions import Gaussian
from LUCI.LuciFitParameter... |
#!/usr/bin/python3
#coding=utf-8
import os
import cv2
import json
import torch
import numpy as np
import transform
from torch.utils.data import Dataset
class Config(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
self.mean = np.array([[[115.75, 120.83, 93.49]]])
s... |
""" reads job profiles from a text file, specification
- reads line by line, duplicates possible and no dedicated sort order necessary
- empty line is taken as separator between job descriptions
- interpretes lines as Job Title (looking for '(m/w/d)' signature ),
company (looking for AG,SE,GmbH and ... |
"""
Helper verbs
"""
from functools import wraps
import pandas as pd
import numpy as np
from ..types import GroupedDataFrame
from ..expressions import Expression
from ..operators import register_implementations
from .common import _get_groups, Selector, build_expressions
from .one_table import arrange, create, define... |
#!/usr/bin/env python3
import logging
import argparse
import random
import string
import os
import numpy as np
import spead2
import spead2.send
# pylint: disable=C0116,W1202
# A module to send a file over UDP using the spead2 data exchange protocol
#
# Author: <NAME>
# Email : <EMAIL>
class UdpSend():
"""
... |
import pytest
import time
import rospy
import math
import numpy as np
from ..c_ovrv_utils import *
from svea.svea_managers.path_following_sveas import SVEAPlatoonMember
from svea.localizers import LocalizationInterface
from svea.simulators.sim_SVEA import SimSVEA
from svea.models.bicycle import SimpleBicycleModel
from ... |
"""
Additional tests for PandasArray that aren't covered by
the interface tests.
"""
import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
from pandas.arrays import PandasArray
from pandas.core.arrays.numpy_ import PandasDtype
@pytest.fixture(
params=[
np.array(["a", "b"], dty... |
from .TesseractError import TesseractError
import numpy as np
import os
import sys
import ctypes
import ctypes.util
import platform
from urllib import request
from tqdm import tqdm
import logging
from pathlib import Path
logger = logging.getLogger(__name__)
HOME = str(Path.home())
def _is_pyinstaller():
return h... |
"""
Types for objects parsed from the configuration.
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import re
from collections import namedtuple
import six
from ..const import COMPOSEFILE_V1 as V1
from .errors import ConfigurationError
from compose.const import IS_WINDOW... |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
"""
Translation recognition for the Microsoft Cognitive Services Speech SDK
"""
import time
try:
import azure.cognitiveservi... |
import logging
import re
from pathlib import Path
from re import Match
from typing import Any, Dict, List, Optional, Union
import antlr4.tree.Tree
import sqlalchemy
from antlr4 import CommonTokenStream, InputStream, RecognitionException, Token
from antlr4.error.ErrorListener import ErrorListener
from antlr4.Recognizer... |
# -*- coding: utf-8 -*-
"""
Helper Code to convert strings in symbolic expression and vv
============================================================
Created on Mon Jul 20 17:52:06 2015
@author: oliver
"""
from sympy import symbols, sin, cos, tan, Matrix, sqrt, sign, re
from sympy.physics.mechanics import dynamicsymb... |
# Copyright 2017 StreamSets 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 writi... |
import sys
import os
import json
import types
import inspect
import collections
import traceback
command = sys.argv[1]
in_file = sys.argv[2]
out_file = sys.argv[3]
with open(in_file) as f:
in_data = json.load(f)
params = in_data['params']
# fake digdag_env module already imported
digdag_env_mod = sys.modules... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import bottle
import datetime
from dataclasses import dataclass, asdict
from mypy_boto3_dynamodb.service_resource import Table
import typing as t
from enum import Enum
from logging import Logger
from threatexchange.descriptor import ThreatDescrip... |
"""
Helpers for the Pawer discord bot
"""
import json
import sys
from datetime import datetime
from os import path, makedirs
import aiohttp
from discord.ext import commands
from bismuthclient.bismuthwallet import BismuthWallet
from bismuthclient.bismuthclient import BismuthClient
from bismuthclient.bismuthutil impor... |
"""Create devices table
Revision ID: 50188ffaf0cd
Revises: <KEY>
Create Date: 2017-05-19 19:39:22.021264
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<KEY>'
branch_labels = None
depends_on = None
def upgrade():
op.create_table(... |
import pygame, sys, random
def draw_floor():
screen.blit(floor_surface, (floor_x_pos,900))
screen.blit(floor_surface, (floor_x_pos + 576,900))
def create_pipe():
random_pipe_position = random.choice(pipe_height)
bottom_pipe = pipe_surface.get_rect(midtop = (700, random_pipe_position))
top_pipe = p... |
from pyscipopt import Model
from pyscipopt import quicksum
try:
import pytest
itertools = pytest.importorskip("itertools")
except ImportError:
import itertools
product = itertools.product
# Testing AND/OR/XOR constraints
# check whether any error is raised
# see http://scip.zib.de/doc-5.0.1/html/cons__... |
import torch
import torch.nn.functional as F
import numpy as np
from skimage.morphology import watershed
from skimage.segmentation import find_boundaries
from scipy import ndimage
import utils as ut
def lc_loss(model, batch):
model.train()
N = batch["images"].size(0)
assert N == 1
blob_dict = g... |
import os
from . import *
from ..core.util import concat
def load(path, data_type=None, dim=None, coord=None, verbose=False, *args, **kwargs):
"""Import data from different spectrometer formats
Args:
path (str, list): Path to data directory or list of directories
data_type (str): Type of spe... |
import datetime
from datetime import timedelta
import pytest
from constants import CONFIRMATION, EXPIRATION_DATE, NOTIFICATION_DATE
def test_add_notification_date_manually_handler(bot_app, update, context):
# fill data in 'context.user_data' to be able to show correct output to the user
context.user_data["e... |
# Copyright The PyTorch Lightning team.
#
# 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 i... |
# 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... |
# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @ Time : 0:55
# @ Author : Chenny
# @ Email : <EMAIL>
# @ File : 2gate_gpc.py
# @ Software: PyCharm
import wave
import os
import numpy as np
def sgn(data):
if data >= 0:
return 1
else:
return 0
# 计算每一帧的能量 256个采样点为一帧
def calEnergy(wave_... |
import unittest
import openmdao.api as om
from openmdao.utils.assert_utils import assert_rel_error
from openmdao.utils.general_utils import set_pyoptsparse_opt
import dymos as dm
from dymos.examples.brachistochrone import BrachistochroneODE
def brachistochrone_min_time(transcription='gauss-lobatto', num_segments=8,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-07-25 19:44:35
# @Author : <NAME> (<EMAIL>)
# @Link : http://iridescent.ink
# @Version : $1.0$
from __future__ import print_function
import torch as th
import torchsar as ts
def __fdnorm(X, p):
X = th.sum(X.abs(), axis=-1).sqrt()
... |
import time
from lib.config import *
import lib.config as globals
class Frame:
def __init__(self, img):
""" Constructor to the frame object that holds all the analyzed information and the source frame
Parameters:
img (ndarray): source img in numpy ndarray representation
"""
... |
import email
import imaplib
import re
from imapclient import IMAPClient
from utils import Utils
class DigestServer(object):
def __init__(self, server, mid, digest_folder_name):
self.digest_folder_name = digest_folder_name
self.digest_inbox = server
self.previous_message_id = mid
def... |
# Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. Crate licenses
# this file to you under the Apache License, Version 2.0 (the "License");
# you may not use this f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2021 Alibaba Group Holding Ltd.
#
# 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-... |
import mock
import datetime
import pytz
from django.test import TestCase
from global_map.models import Clan, Front, Province, ProvinceAssault
from global_map.management.commands.fetchdata import update_province
class ProvinceData(dict):
def __init__(self, *args, **kwargs):
super(ProvinceData, self).__ini... |
from __future__ import absolute_import, print_function, division
import unittest
from pony.orm.core import *
from pony.orm.tests.testutils import *
from pony.orm.tests import setup_database, teardown_database
db = Database()
class Student(db.Entity):
name = Required(str)
scholarship = Optional(int)
grou... |
from tkinter import Tk, Canvas, Frame, BOTH
import mypy
import random
import itertools
from winsound import Beep
class StaffGeometry():
def __init__(self):
self.x_offset = 10
self.y_offset = 100
self.length = 300
self.spacing = 20
self.c5_position = 3.0*self.spacing
class ... |
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../"))
import argparse
import numpy as np
import chainer
from chainer import cuda
from chainer import optimizers
from chainer import serializers
import alex
from mlimages.gather.imagenet import ImagenetAPI
from mlimages.label import LabelingM... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
=========================================
Testclient :mod:`jsonwspclient.testclient`
=========================================
"""
# pylint: disable=relative-import,invalid-name
from __future__ import print_function
import logging
from os.path import abspath, dirname, ... |
# Copyright 2017 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... |
# -*- coding: utf-8 -*-
"""Base object for interacting with Wiser Heat Hub API
The WiseBaseAPI is the root object for all classes that represent a /data/domain/[item] endpoint like
Room or Device. These inherit from WiserBaseAPI as this allow the base class to handle all the dirty work
translating queries ... |
"""
Main bot module.
Entry point for running the bot.
"""
import asyncio
import copy
import sys
import traceback
from typing import Optional
import yaml
from discord import ext as dext, TextChannel
from discord.ext import commands
from discord.ext.commands import Context
from loguru import logger
from ophelia import... |
import pickle
import pytest
from pyrsistent import plist, l
def test_literalish_works():
assert l(1, 2, 3) == plist([1, 2, 3])
def test_first_and_rest():
pl = plist([1, 2])
assert pl.first == 1
assert pl.rest.first == 2
assert pl.rest.rest is plist()
def test_instantiate_large_list():
asse... |
from __future__ import print_function
import math
import sys
from fractions import Fraction
from random import Random
from hiq.projectq.backends import SimulatorMPI
from hiq.projectq.cengines import GreedyScheduler, HiQMainEngine
try:
from math import gcd
except ImportError:
from fractions import gcd
import... |
# Copyright (c) 2014 <NAME>
# 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, softwa... |
""" A variety of classes using different libraries to implement `get_json` and `post_json` methods.
"""
import os
import json
import time
import logging as log
from collections import OrderedDict
# Try to import modules needed for Google App Engine just in case
try:
from google.appengine.api import urlfetch
fro... |
# Copyright (c) 2018 PaddlePaddle Authors. 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 app... |
import numpy as np
import time
class DataSystem:
def __init__(self, dim=2, num_points=1000, distribution = 'normal'):
"""
Parameters
dim (int) : Dimension of the data required
num_points (int) : Number of the data points required
distributi... |
"""Testcode for Android RPC.
To use it, start a rpc proxy with "python -m tvm.exec.rpc_proxy".
And configure the proxy host field as commented.
"""
import time
import argparse
import tvm
import nnvm.compiler
import nnvm.testing
from tvm.contrib import graph_runtime as runtime
import os
from tvm.contrib import rpc, uti... |
# Copyright 2019 <NAME>.
# This program is distributed under the MIT license.
import types
import sys
import re
import collections
import datetime as datetime_module
import six
def get_shortish_repr(item):
r = repr(item)
if len(r) > 100:
r = '{r[:97]}...'.format(**locals())
return r
def get_loca... |
# Module:
# Submodules:
# Created:
# Copyright (C) <date> <fullname>
#
# This module is part of the <project name> project and is released under
# the MIT License: http://opensource.org/licenses/MIT
"""
"""
# ============================================================================
# Imports
# =====================... |
# Copyright 2021 Zilliz. 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... |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import dataclasses
from enum import Enum
from typing import Any, Dict, List, Optional, Set
import torch.distributions as dist
from beanmach... |
from flask import request, jsonify, Blueprint
from flask_pydantic_spec import Response
from modules.swagger import api
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import StickerSendMessage, TextSendMessage, FlexSendMessage
from machine_leanning... |
import numpy as np
import pyglet
class ArmEnv(object):
viewer = None
dt = 0.1 # refresh rate
action_bound = [-1, 1]
goal = {'x': 100., 'y': 100., 'l': 40}
state_dim = 2
action_dim = 2
def __init__(self):
self.arm_info = np.zeros(
2, dtype=[('l', np.float32), ('r', n... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import os
import sys
from shutil import copyfile
import time
import click
import jsonschema
import ray
from ray.autoscaler.commands import (
attach_cluster,
exec_cluster,
create_or_u... |
class Node:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return str(self.value)
def get_next_node(self):
return self.next
def set_next_node(self, node):
self.next = node
def get_current_value(self):
return self... |
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
import tensorflow as tf
sess = tf.InteractiveSession()
from scipy import misc
import PIL
from PIL import Image
x = tf.placeholder(tf.float32, shape=[None, 784])
y_ = tf.placeholder(tf.float32, sh... |
#!/usr/bin/python
# Parse WinLink Position Report Email message files.
# ----------------------------------------------------------------------------
# WinLink message tools
# -----------------------------------------------------------------------------
# <NAME> - https://github.com/jfogarty - <EMAIL>
# ---------------... |
# Copyright (c) 2021 PaddlePaddle Authors. 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 app... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.