text stringlengths 1 927k |
|---|
import logging
from collections import Counter, defaultdict
import aiogram
from aiogram import Bot, types
from aiogram.utils.emoji import emojize
from detector import Detector
from gwevents import Events, time_ago
from keyboard import InlineKeyboard
from permanentset import PermanentSet
class GraceBot(Bot):
def ... |
import unittest
from logging import Logger, getLogger
from numpy import ndarray, power, allclose
from numpy.random import randn
from freq_used.logging_utils import set_logging_basic_config
from optmlstat.functions.function_base import FunctionBase
from optmlstat.functions.example_functions import get_sum_of_square_fu... |
# 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 file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
from __future__ import division, print_function
import sys
import os
import math
import random
from sklearn import datasets
import numpy as np
# Import helper functions
from mlfromscratch.utils.data_manipulation import normalize
from mlfromscratch.utils.data_operation import euclidean_distance, calculate_covariance_ma... |
from flask import g, abort, redirect, request, render_template, send_from_directory, url_for
from http import HTTPStatus
from os import getenv, path
from lnbits.core import core_app
from lnbits.decorators import check_user_exists, validate_uuids
from lnbits.settings import SERVICE_FEE
from ..crud import (
create_... |
"""
Dummy layout. Used when somebody creates an `Application` without specifying a
`Layout`.
"""
from quo.text import HTML
from quo.keys import KeyBinder
from quo.keys.key_binding.key_processor import KeyPressEvent
from .containers import Window
from .controls import FormattedTextControl
from .dimension import D
from ... |
import logging
import zipfile
import wget
from .utils import DOWNLOAD_DIR, make_dirs
baseurl = 'https://codeload.github.com/kocohub/{}/zip/master'
logger = logging.getLogger(__name__)
def download_dataset(dataset, verbose=True):
make_dirs(DOWNLOAD_DIR)
url = baseurl.format(dataset)
wget.download(url, ... |
import os
import json
import torch
import numpy as np
from torch.utils import data
from PIL import Image
from ptsemseg.utils import recursive_glob
from ptsemseg.augmentations import Compose, RandomHorizontallyFlip, RandomRotate
class mapillaryVistasLoader(data.Dataset):
def __init__(
self,
root,
... |
# Max Non Negative SubArray
# https://www.interviewbit.com/problems/max-non-negative-subarray/
#
# Find out the maximum sub-array of non negative numbers from an array.
# The sub-array should be continuous. That is, a sub-array created by choosing
# the second and fourth element and skipping the third element is invali... |
import model
import logging
import sys
sys.path.append('../../src/')
from simulator import Simulator
sys.setrecursionlimit(50000)
model = model.AutoDistPHOLD(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]))
sim = Simulator(model)
#sim.setVerbose(None)
sim.setTerminationTime(200)
sim.setMessageCopy('custom')
sim.... |
from django.conf.urls import include, url
from persons import views
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'physicaladdresses', views.PhysicalAddressViewSet)
router.register(r'companies', views.CompanyViewSet)
app_name = 'persons'
urlpatterns = [
url(r'^', inclu... |
import argparse
import os
import sys
from Util import SUCCESS, FAILURE
from Util import run_cmd
parser = argparse.ArgumentParser(description="install conda",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-w", "--workdir",
help="worki... |
# Simple Threads Pool
from multiprocessing.dummy import Pool as ThreadPool
from datetime import date
from datetime import datetime
import time
multiply_results = []
def squareNumber(n):
multiply_results.append(n ** 2)
dt_string = datetime.now().strftime("%H:%M:%S")
millis = int(round(time.time() * 1000))
... |
import pytest
@pytest.mark.slow
def test_long_computation():
...
@pytest.mark.timeout(10, method="thread")
def test_topology_sort():
...
def test_foo():
pass |
import time
import json
import argparse
import os
import sys
import logging
import shutil
from datetime import datetime
import glob
import random
from scipy.stats import mannwhitneyu
from scipy.stats import spearmanr
import numpy as np
from sklearn.metrics import roc_auc_score, precision_recall_curve, auc
import te... |
"""EDF+,BDF module for conversion to FIF"""
# Author: Teon Brooks <teon.brooks@gmail.com>
#
# License: BSD (3-clause)
from .edf import read_raw_edf |
from copy import deepcopy
import pygame
RED = (0,100,100)
WHITE = (255, 255, 255)
def minimax(position, depth, max_player, game):
if depth == 0 or position.winner() != None: #maximum depth reach or someone has won, returning position along with evaluating the position
return position.evaluate(), pos... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2019 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
""" QiBuild """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print... |
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
#!/usr/bin/env python
#
# Copyright 2007,2010,2012 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your ... |
"""Useful command to download and clean data from OpenFoodfact."""
import requests
keys = [
"id",
"product_name_fr",
"nutrition_grade_fr",
"url",
"image_front_url",
"image_ingredients_url",
]
class RequestData:
"""The class fetch the data and save it in to a json file."""
def __init_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayDataDataexchangeDtmorseSyncResponse(AlipayResponse):
def __init__(self):
super(AlipayDataDataexchangeDtmorseSyncResponse, self).__init__()
self._r... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
class CarhomeItem(scrapy.Item):
# define the fields for your item here like:
car_name = scrapy.Field()
car_url = scrapy.Field()
# 车辆评分... |
def default_outside(x=[]):
return x
a = default_outside()
a.append(1)
print a
b = default_outside()
b.append(2)
print b |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
from PyInquirer import prompt, Separator
# The menus displays a list of checkboxes, which allows the user to select the separators and modules he wants to use
def separators_menu(self):
# Get a list of all existing separators
separators = self.config["separators"]
separators_menu = [
{
... |
#!/usr/bin/pythonr
# -*- coding: utf-8 -*-
"""
File : base_service.py
Author : Zerui Qin
CreateDate : 2018-12-20 10:00:00
LastModifiedDate : 2018-12-20 10:00:00
Note : Agent基础服务类, 获取Agent数据服务相关方法
"""
import datetime
import psutil
import pytz
import requests
from watero_go.utils import hardware
from watero_go.utils.l... |
# Copyright 2017 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 law or a... |
import os
from pathlib import Path
DEFAULT_ROOT_PATH = Path(os.path.expanduser(os.getenv("SHL_ROOT", "~/.shl/mainnet"))).resolve() |
import shutil
import tempfile
from django.core.cache import cache
from http import HTTPStatus
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
from django.contrib.auth import get_user_model
from django.test import Client, TestCase, override_settings
from django.urls import ... |
import logging
def get_logger():
logger = logging.getLogger("debug")
hdlr = logging.FileHandler("debug.log")
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
return logger
logger = ge... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Imports --------------------------------------------------------------------------... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:copyright: (c) 2013-2016 by Mike Taylor
:license: CC0 1.0 Universal, see LICENSE for more details.
"""
import os
import json
import uuid
import types
import errno
import shutil
import logging
import datetime
import argparse
import pytz
import redis
import jinja2
impo... |
#!/usr/bin/env python
# Copyright 2018, Rackspace US, 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 applicabl... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
kwargs_tools
by Chris Cannon
====
Provides
1. kwargs_scan - convert header and values from csv into a dictionary
2. kwargs_db - instance = myclass(search='name')
is converted to
instance = myclass(param1, param2, ...)
... |
import posthoganalytics
import requests
from dateutil.relativedelta import relativedelta
from django.utils import timezone
from ee.clickhouse.client import sync_execute
from ee.models.license import License
from posthog.models import User
def send_license_usage():
license = License.objects.first_valid()
if n... |
#!/usr/bin/env python
# encoding: utf-8
# Below is the interface for Iterator, which is already defined for you.
#
# class Iterator:
# def __init__(self, nums):
# """
# Initializes an iterator object to the beginning of a list.
# :type nums: List[int]
# """
#
# def hasNext(self)... |
# standard
from importlib import import_module
# internal
import settings
def core_func(*args, **kwargs):
print('core_func executed with args={} + kwargs={}'.format(args, kwargs))
def set_middlewares(func):
for middleware in reversed(settings.MIDDLEWARES):
p, m = middleware.rsplit('.', 1)
mod = import_modul... |
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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 Lice... |
#By Zhenghang(Klaus) Zhong
#Box Plot of error distribution
from pandas import DataFrame
from pandas import read_csv
import pandas as pd
import numpy as np
from matplotlib import pyplot
# load results into a dataframe
filenames_128 = ['dis_diff_128.csv']
filenames_256 = ['dis_diff_256.csv']
filenames_512 = ['dis_diff_... |
import os
from dotenv import load_dotenv
from app.utils.cache import Cache
from app import ApplicationFactory
load_dotenv()
with open('./AppleMusicAuthKey.p8', 'r') as f:
os.environ['APPLE_KEY'] = f.read()
TITLE = 'Sharify'
DESCRIPTION = ''
DEBUG = os.environ.get('APP_DEBUG') or False
Cache.instance().init()
ap... |
# https://stackoverflow.com/questions/16974047/efficient-way-to-find-missing-elements-in-an-integer-sequence/16974075#16974075
from itertools import islice, chain
def window(seq, n=2):
"Returns a sliding window (of width n) over data from the iterable"
" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... ... |
import pytest
from krs.token import get_token
from krs import groups, users
from ..util import keycloak_bootstrap
@pytest.mark.asyncio
async def test_list_groups_empty(keycloak_bootstrap):
ret = await groups.list_groups(rest_client=keycloak_bootstrap)
assert ret == {}
@pytest.mark.asyncio
async def test_lis... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [ ]
setup_requirements = ['pytest-run... |
#import django.conf.global_settings as DEFAULT_SETTINGS
from .settings import *
import os
from django.utils.translation import ugettext as _
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = ['*']
ADMINS = (
('Admin User', 'jamesh@linkinulife.com'),
)
... |
from util import time_it
# Time complexity: O(N)
@time_it
def linear_search(list1: [], element) -> int:
"""Returns the index of a given element in a given sorted list, otherwise returns -1"""
for index, item in enumerate(list1):
if item == element:
return index
return -1
@time_it
de... |
"""
Created by Epic at 10/13/20
Original script by FireDiscordBot on GitHub
"""
import logging
from copy import copy
from logging import Logger, DEBUG
import sys
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
RESET_SEQ = "\033[0m"
COLOR_SEQ = "\033[1;%dm"
BOLD_SEQ = "\033[1m"
def getcolor(color=N... |
from sklearn.cluster import KMeans
from sklearn.neighbors import kneighbors_graph
from scipy.spatial.distance import pdist, squareform
from scipy.sparse.csgraph import laplacian
import numpy as np
"""Args:
X: input samples, array (num, dim)
n_clusters: no. of clusters
n_neighbours: neighborhood size
... |
from typing import Callable
class Solution:
def setZeroes(self, matrix: list[list[int]]) -> None:
"""Do not return anything, modify matrix in-place instead."""
first_column_zero = False
for row in matrix:
for j, cell in enumerate(row):
if cell != 0:
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('froide_campaign', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
... |
import torch
import numpy as np
from torch.hub import load_state_dict_from_url
from nnfabrik.utility.nn_helpers import load_state_dict
from nntransfer.models.resnet import resnet_builder
from nntransfer.models.utils import get_model_parameters
from nntransfer.models.vgg import vgg_builder
from nntransfer.models.lene... |
"""Tests for letsencrypt.client."""
import os
import shutil
import tempfile
import unittest
import OpenSSL
import mock
from acme import jose
from letsencrypt import account
from letsencrypt import errors
from letsencrypt import le_util
from letsencrypt.tests import test_util
KEY = test_util.load_vector("rsa512_ke... |
import unittest
import zserio
from testutils import getZserioApi
class AutoArrayTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.api = getZserioApi(__file__, "array_types.zs").subtyped_builtin_auto_array
def testBitSizeOfLength1(self):
self._checkBitSizeOf(self.AUTO_ARRAY_LE... |
# fileName: Configs/dm.py
# copyright ©️ 2021 nabilanavab
import os
#--------------->
#--------> CONFIG VAR.
#------------------->
class Config(object):
# get API_ID, API_HASH values from my.telegram.org (Mandatory)
API_ID = os.environ.get("API_ID")
API_HASH = os.environ.get("API_HASH")
... |
# -*- coding: utf-8 -*-
# *****************************************************************************
#
# Copyright (c) 2021
# Georgia Institute of Technology
# Tomoki Koike
# <tkoike3@gatech.edu>
#
# *****************************************************************************
#
# DESCRIPTION:
# Rigid body dynamics ... |
# -*- coding: utf8 -*-
from pandocfilters import toJSONFilter, Link, Str
def myfilter(key, value, form, meta):
if key == 'Link':
return Str("replaced_text")
if __name__ == "__main__":
toJSONFilter(myfilter) |
{##}#!${executable}
{##}# -*- coding: utf-8 -*-
{##}#
{##}# Copyright (C)2008-2009 Edgewall Software
{##}# Copyright (C) 2008 Noah Kantrowitz <noah@coderanger.net>
{##}# All rights reserved.
{##}#
{##}# This software is licensed as described in the file COPYING, which
{##}# you should have received as part of this dist... |
from lib.utils import token, nodes
from lib import errors
#######################################
# PARSE RESULT
#######################################
class ParseResult:
def __init__(self):
self.error = None
self.node = None
self.last_registered_advance_count = 0
self.advanced_count = 0
self.to_reverse_c... |
# -*- coding: utf-8 -*-
from collections import ChainMap
from datetime import timedelta
from itertools import chain
from wtforms import Form
from wtforms.csrf.session import SessionCSRF
from wtforms.meta import DefaultMeta
from wtforms.validators import DataRequired, StopValidation
from wtforms.fields.core import Fiel... |
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
def define_flags():
############
# Run mode
############
tf.app.flags.DEFINE_string('run', None, "Which operation to run. [train|inference]")
##########################
# Training parameters
###########################
tf.app.flags.... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Athul Cyriac Ajay and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
# import frappe
from frappe.utils.nestedset import NestedSet
class Account(NestedSet):
pass |
import myutils_cython
import numpy as np, numpy.random as ra, scipy.linalg as sla
from tqdm import tqdm
def rankone(X,Z,y,r,R=.1, C=.1, tolPred=0.01, tolTh=0.01, maxIter=400, verbose=False):
"""
matrix recovery with rank-one measurements using Burer-Monteiro approach
measurement model: (X[i,:] @ Theta) @ ... |
import numpy as np
import pandas as pd
import neurokit2 as nk
import nolds
from pyentrp import entropy as pyentrp
"""
For the testing of complexity, we test our implementations against existing and established ones.
However, some of these other implementations are not really packaged in a way
SO THAT we can easily im... |
# coding=utf-8
# Copyright 2020 The HuggingFace Inc. 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... |
# Copyright 2021 The Kubric 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
# Generated by Django 3.1.2 on 2021-09-20 06:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('booking', '0011_auto_20210920_0204'),
]
operations = [
migrations.AlterField(
model_name='appointment',
name='appoin... |
"""
Object model representation of a document represented as a collection
of XML files in METS/MODS format.
"""
from defoe.fmp.page import Page
from lxml import etree
import re
class Document(object):
"""
Object model representation of a document represented as a
collection of XML files in METS/MODS for... |
import tensorflow as tf
import matplotlib.pyplot as plt
# MNIST dataset parameters.
num_classes = 10 # 0 to 9 digits
num_features = 784 # 28*28
# Training parameters.
learning_rate = 0.001
training_steps = 1000
batch_size = 256
display_step = 100
# Network parameters.
n_hidden_1 = 128 # 1st layer number of neurons.
... |
import subprocess
import pytest
import testinfra
def pytest_addoption(parser):
parser.addoption("--image")
@pytest.fixture(scope="session")
def image(request):
return request.config.getoption("--image")
@pytest.fixture(scope="session")
def host(image):
run_command = ["docker", "run", "-d", image, "sl... |
# Copyright 2019 The Cirq 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
## @file
# Quick script to check that the wheel/package created is aligned on a git tag.
# Official releases should not be made from non-tagged code.
#
# Copyright (c) Microsoft Corporation
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
##
import glob
import os
import sys
p = os.path.join(os.getcwd(), "dist")
whlfi... |
def area(c, la):
print(f'A area de um terreno {c :.2f}m x {la :.2f}m é de {c * la :.2f}m².')
# Programa principal
print(f'{"Controle de Terrenos" :^30}\n'
f'{"-" * 30}')
comp = float(input('Comprimento (m)): '))
larg = float(input('Largura (m): '))
area(comp, larg) |
import os
import sys
import bpy
script_dir = os.path.dirname(os.path.abspath(__file__))
utils_dir = os.path.join(script_dir, "../../blender_utils")
sys.path.append(utils_dir)
from utils import clean_unused, import_obj_folder
model_id = sys.argv[-3]
obj_dir = sys.argv[-2]
save_dir = sys.argv[-1]
os.makedirs(save_dir,... |
from .openvr_mod_cfg import OpenVRModCfgSetting, OpenVRModSettings
class FsrSettings(OpenVRModSettings):
cfg_key = 'fsr'
format = 'cfg'
def __init__(self):
self.enabled = OpenVRModCfgSetting(
key='enabled',
name='Enabled',
category='FSR Settings',
d... |
import hashlib
import json
import os
import posixpath
import re
from collections import OrderedDict
from urllib.parse import unquote, urldefrag, urlsplit, urlunsplit
from django.conf import settings
from django.contrib.staticfiles.utils import check_settings, matches_patterns
from django.core.cache import (
Invali... |
# -*- Python -*-
# This file is licensed under a pytorch-style license
# See frontends/pytorch/LICENSE for license information.
# Some checks that we can import the various extensions and libraries and
# not have symbol collisions or other goings on.
# RUN: %PYTHON %s
import sys
print(f"PYTHONPATH={sys.path}")
impo... |
# 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 file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'UserBan.is_unbanned'
db.add_column('base_userban', 'is_unbanned', self.gf('django.db.model... |
# coding: utf-8
"""
Talon.One API
The Talon.One API is used to manage applications and campaigns, as well as to integrate with your application. The operations in the _Integration API_ section are used to integrate with our platform, while the other operations are used to manage applications and campaigns. #... |
#!/usr/bin/env python3
"""
List all users registered in <CWL_ICA_REPO_PATH>/config/user.yaml
"""
from classes.command import Command
from utils.logging import get_logger
import pandas as pd
from utils.repo import read_yaml, get_user_yaml_path
import sys
logger = get_logger()
class ListUsers(Command):
"""Usage:... |
from .censored_normal import CensoredNormal
from .censored_multivariate_normal import CensoredMultivariateNormal
from .truncated_normal import TruncatedNormal
from .truncated_multivariate_normal import TruncatedMultivariateNormal
from .truncated_boolean_product import TruncatedBernoulli |
from typing import Tuple
import pytest
from flake8_annotations.error_codes import Error
from testing.helpers import check_is_empty, check_is_not_empty, check_source
from testing.test_cases.dynamic_function_test_cases import (
DynamicallyTypedFunctionTestCase,
DynamicallyTypedNestedFunctionTestCase,
dynami... |
from main import Word, Wordgroup
print('start')
i = 22
wg = Wordgroup()
wg.create_wordgroup(f'wordgroup_test{i}')
wa = Word()
wa.create_word(f'word_test{i}a', wg)
wb = Word()
wb.create_word(f'word_test{i}b', wg)
wg = Wordgroup()
wg.load_wordgroup(f'wordgroup_test{i}')
wa = Word()
wa.load_word(f'word_test{i}a')
wb... |
# -*- coding: utf-8 -*-
import unittest
from mock import MagicMock, Mock, patch
from tornado.gen import Future
from .. import TestHandlerBase
@unittest.skip("TODO")
class AdminAPITest(TestHandlerBase):
def setUp(self):
self.client_mock = MagicMock(name="client_mock")
self.fake_context = MagicMoc... |
"""
Plotting utilities for example notebooks
"""
import matplotlib.pyplot as plt
import numpy as np
def plot_image(image=None, mask=None, ax=None, factor=3.5/255, clip_range=(0, 1), **kwargs):
""" Utility function for plotting RGB images and masks.
"""
if ax is None:
_, ax = plt.subplots(nrows=1, ... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.home , name="homepage"),
] |
from django.urls import path, include
from .views import (ProfileView, ApplicantView,
loginView, sign_out, SignupView)
app_name = 'accounts'
urlpatterns = [
path('profile/edit/', ProfileView.as_view(), name='edit_profile'),
path('profile/<option>/', ProfileView.as_view(), name='profile'),
... |
"""Support for Xiaomi Mi Flora BLE plant sensor."""
from datetime import timedelta
import logging
import btlewrap
from btlewrap import BluetoothBackendException
from miflora import miflora_poller
import voluptuous as vol
from homeassistant.components.sensor import (
PLATFORM_SCHEMA,
STATE_CLASS_MEASUREMENT,
... |
# Copyright (c) 2014 The Bitcoin Core developers
# Copyright (c) 2014-2015 The Dash developers
# Copyright (c) 2019 The Vzuh developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Helpful routines for regression testing... |
#!/usr/bin/python
#
# Copyright 2013 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 b... |
"""
This module contains errors/exceptions and warnings for astroML.
"""
from astropy.utils.exceptions import AstropyWarning
class AstroMLWarning(AstropyWarning):
"""
A base warning class from which all AstroML warnings should inherit.
This class is subclassed from AstropyWarnings, so warnings inherited ... |
# (C) Datadog, Inc. 2018-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import os
from sys import maxsize
import pytest
from pkg_resources import parse_version
from datadog_checks.dev import get_docker_hostname
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.pat... |
# Deepforest Preprocessing model
"""The preprocessing module is used to reshape data into format suitable for
training or prediction.
For example cutting large tiles into smaller images.
"""
import os
import numpy as np
import pandas as pd
import slidingwindow
from PIL import Image
import torch
import warnings
import... |
# bug 5
# https://asu-compmethodsphysics-phy494.github.io/ASU-PHY494/2019/02/05/05_Debugging/#activity-fix-as-many-bugs-as-possible
# Create a list of values -10, -9.8, -9.6, ..., -0.2, 0, 0.2, ..., 10.
h = 0.2
x = [-10 + i*h for i in range(100)] |
"""
Only the most essential features to :class:`csgo.client.CSGOClient` are found here. Every other feature is inherited from
the :mod:`csgo.features` package and it's submodules.
"""
import logging
import gevent
import google.protobuf
from steam.core.msg import GCMsgHdrProto
from steam.client.gc import GameCoordinato... |
import numpy as np
"""
This file implements various first-order update rules that are commonly used
for training neural networks. Each update rule accepts current weights and the
gradient of the loss with respect to those weights and produces the next set of
weights. Each update rule has the same interface:
def updat... |
# 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 json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class Kubern... |
import platform
import subprocess
import unittest
from conans import tools
from conans.client.conf.detect import detect_defaults_settings
from conans.test.utils.tools import TestBufferConanOutput
class DetectTest(unittest.TestCase):
def detect_default_compilers_test(self):
platform_default_compilers = {... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.