text stringlengths 2 999k |
|---|
from httplib import INTERNAL_SERVER_ERROR
from tornado import httpclient
class HttpClientException(Exception):
def __init__(self, response):
super(HttpClientException, self).__init__()
if issubclass(response.__class__, httpclient.HTTPError):
self.response = response.response
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# wcnt - A spartan word counter
# (C) 2016 - Emanuele Ballarin <emanuele@ballarin.cc>
words = 0
with open('file.txt', 'r') as text: # File opening is already I/O buffered ;-)
for line in text:
words = words + len(line)
print(" ") # This empty lines are just ty... |
"""This module contains the URLs exposed by the api subapp."""
from django.urls import path
from .views import add_labels_to_new_city, add_labels_to_existing_city, get_index, get_logs
urlpatterns = [
path('', get_index, name='get_index'),
path('cities/logs', get_logs, name='get_logs'),
path('cities/<city>'... |
# Copyright (c) 2012-2016 Seafile Ltd.
"""
The MIT License (MIT)
Copyright (c) 2013 Omar Bohsali
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 ... |
'''
* Copyright (C) 2019-2020 Intel Corporation.
*
* SPDX-License-Identifier: BSD-3-Clause
'''
import string
import shlex
import subprocess
import time
import copy
from threading import Lock
from threading import Thread
import shutil
import re
from collections import OrderedDict
from collections import namedtuple
from... |
import cv2
import numpy as np
import picamera, picamera.array
import time
import haar_detect
import dnn_detect as dn
import talker
from adafruit_servokit import ServoKit
import pid
# define pan function
prev_x = 0
prev_y = 0
class facetrack():
def __init__(self):
# set constants
sel... |
"""
This file offers the methods to automatically retrieve the graph Lactobacillus ingluviei.
The graph is automatically retrieved from the STRING repository.
Report
---------------------
At the time of rendering these methods (please see datetime below), the graph
had the following characteristics:
Datetime: 202... |
# Copyright 2019 The Feast 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... |
import sys
from setuptools import setup
from setuptools import find_packages
version = '0.20.0.dev0'
# Please update tox.ini when modifying dependency version requirements
install_requires = [
'acme=={0}'.format(version),
'certbot=={0}'.format(version),
'dnspython',
'mock',
# For pkg_resources. ... |
#!/usr/bin/env python3
import json
import os
import stat
import sys
import anchore_engine.analyzers.utils
analyzer_name = "file_suids"
try:
config = anchore_engine.analyzers.utils.init_analyzer_cmdline(
sys.argv, analyzer_name
)
except Exception as err:
print(str(err))
sys.exit(1)
imgname =... |
#!/usr/bin/env python3.9
"""Conduct runtime tests on heaps."""
import sys
from pathlib import Path
from timeit import default_timer
from heapq import heappop, heappush
sys.path.append(str(Path(__file__).parent.parent.absolute()))
from util import pairingheap, fibonacciheap, graph
def pairing_time(testdata: Path) ... |
#
# @lc app=leetcode id=172 lang=python3
#
# [172] Factorial Trailing Zeroes
#
# @lc code=start
class Solution:
def trailingZeroes(self, n: int) -> int:
res = 0
while n > 0:
n //= 5
res += n
return res
# @lc code=end
# Accepted
# 502/502 cases passed(32 ms)
# Your... |
#!/usr/bin/env python2
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.mininode import *
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
import time
from... |
import os
import sys
from osgeo import ogr
import rasterio
##
##
#Create storage vector
outfile_name = sys.argv[2] #"E:\\Base_Geo_QGIS\\Rasters\\mapbiomas_col5_stable_declividade\\POINTS\\stable5y_D2_points.shp"
if (os.path.isfile(outfile_name[:-4]+'.shp')==True) & (os.path.isfile(outfile_name[:-4]+'.... |
# The MIT License (MIT)
# Copyright (c) 2018 Massachusetts Institute of Technology
#
# Author: Guillaume Rongier
# This software has been created in projects supported by the US National
# Science Foundation and NASA (PI: Pankratius)
#
# Permission is hereby granted, free of charge, to any person obtaining a cop... |
import sys
import numpy as np
import torch
import utils
class Appr(object):
def __init__(self,model,nepochs=0,sbatch=0,lr=0,lr_min=1e-4,lr_factor=3,lr_patience=5,clipgrad=10000,args=None):
self.model=model
self.criterion=None
self.optimizer=None
return
def train(self,t,xtra... |
input = """
sat|e37|e34.
e34:-sat.
e37:-sat.
sat:-e34.
e36:-sat.
sat:-e55.
e21:-sat.
sat|e55:-e21.
e26:-sat.
e20:-sat.
sat:-e20.
e12:-sat.
sat|e20:-e12.
e50:-sat.
sat:-e50.
e33:-sat.
sat:-e33.
:-not sat.
"""
output = """
"""
|
from ConfigSpace.configuration_space import ConfigurationSpace
from ConfigSpace.hyperparameters import UniformFloatHyperparameter, CategoricalHyperparameter
from functools import partial
from autosklearn.pipeline.components.base import AutoSklearnPreprocessingAlgorithm
from autosklearn.pipeline.components.feature_prep... |
import logging
from copy import deepcopy
from pathlib import Path
import click.testing
import message_ix
import pandas as pd
import pytest
from ixmp import Platform
from ixmp import config as ixmp_config
from message_ix_models import cli, util
from message_ix_models.util._logging import mark_time, preserve_log_level
... |
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.
# The scope of the test is to verify that two nested SDFGs within the same state are generated
# as two different FPGA kernels.
# There are two different tests:
# - independent: the two nested SDFGs (vector addition and vector multiplicatio... |
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... |
# -*- coding: utf-8 -*-
# general imports
from .sensor import *
# EMG sensor
from . import emg
|
# public imports
import json
# local imports
from visualization import visualize
from data_into_csv import data_into_csv
def selection():
"""Returns user selection and catches input errors.
"""
input_value = input("Select a number: ").strip()
if input_value == "break":
return "break"
# ca... |
import pandas as pd
import numpy as np
import pickle
from scipy.stats import poisson,skellam
from scipy.optimize import minimize, fmin
from multiprocessing import Pool
def calc_means(param_dict, homeTeam, awayTeam):
return [np.exp(param_dict['attack_'+homeTeam] + param_dict['defence_'+awayTeam] + param_dic... |
import random #for initializing random weights and random biases
import numpy as np #for doing matrix calculations
import matplotlib.pyplot as plt
import matplotlib.colors as pltclr
import math #for isnan
import copy
#some linear function
if 1:
T_DATA_IN = []
T_DATA_OUT = []
points = 50
for a in range(points):
... |
import setuptools
with open("README.md") as fp:
long_description = fp.read()
setuptools.setup(
name="s3_migration_cluster",
version="1.0.1",
description="s3_migration_cluster",
long_description=long_description,
long_description_content_type="text/markdown",
author="huangzb@amazon.com"... |
# SPDX-License-Identifier: BSD-3-Clause
"""Test Database and VersionedDatabase functionality.
Every test case checks both the in-memory database (same db object on which
operations were performed) and the on-disk database (call to createDB()
after operations were performed).
"""
from pytest import fixture, mark, rai... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from typin... |
from rest_framework import viewsets
from .models import ListModel
from . import serializers
from .page import MyPageNumberPagination
from rest_framework.filters import OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.response import Response
from .filter import Filter
fro... |
# Copyright 2017-2020 TensorHub, 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 writ... |
#Exercício Python 19: Um professor quer sortear um dos seus
# quatro alunos para apagar o quadro. Faça um programa que ajude ele,
# lendo o nome dos alunos e escrevendo na tela o nome do escolhido.
from random import choice
al_1 = input('Primeiro aluno: ')
al_2 = input('Segundo aluno: ')
al_3 = input('Terceiro aluno: '... |
import random
import math
from pygame.locals import QUIT, KEYUP
from src.game_screens.screen import Screen
from src.misc.game_enums import Game_mode
from src.objects.cart import Cart
from src.objects.coin import Coin
from src.objects.bluecoin import BlueCoin
from src.objects.bomb import Bomb
class Game_screen(Scree... |
"""Cart-related utility functions."""
from functools import wraps
from uuid import UUID
from django.contrib import messages
from django.db import transaction
from django.utils.timezone import now
from django.utils.translation import pgettext_lazy
from prices import PriceRange
from satchless.item import InsufficientSto... |
import inspect
from functools import partial
from graphql import (
default_type_resolver,
get_introspection_query,
graphql,
graphql_sync,
introspection_types,
is_type,
print_schema,
GraphQLArgument,
GraphQLBoolean,
GraphQLEnumValue,
GraphQLField,
GraphQLFloat,
GraphQ... |
#! /usr/bin/python
# -*- encoding: utf-8 -*-
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Parameter
from models.ResNetBlocks import *
class ResNetSE(nn.Module):
def __init__(self, block, layers, num_filters, nOut, encoder_type='SAP', **kwargs):
print('Embedding ... |
from conans import ConanFile, CMake, tools
from conans.errors import ConanInvalidConfiguration
import os
import textwrap
required_conan_version = ">=1.33.0"
class LibmediainfoConan(ConanFile):
name = "libmediainfo"
license = ("BSD-2-Clause", "Apache-2.0", "GLPL-2.1+", "GPL-2.0-or-later", "MPL-2.0")
homep... |
from sklearn.linear_model import LinearRegression
from sklearn.utils import shuffle
# Trains linear regression model
def linear_regression_train(X_train, Y_train):
X_train, Y_train = shuffle(X_train, Y_train, random_state=0)
linear_reg_model = LinearRegression()
linear_reg_model.fit(X_train, Y_train)
... |
# 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... |
from civic_scraper.base.site import Site
def test_site_default():
"Site should receive a url"
class Example(Site):
pass
site = Example("https://foo.com")
assert hasattr(site, "url")
assert site.runtime.__class__.__name__ == "date"
assert not hasattr(site, "parser_kls")
def test_sit... |
"""General FarmOS Asset."""
from __future__ import annotations
from datetime import datetime
from typing import Dict, List, Optional, Union
from farmos_ext.farmobj import FarmObj
from farmos_ext.term import Crop, Season
class Asset(FarmObj):
def __init__(self, farm, keys):
if 'resource' ... |
PREFIX_PX_COOKIE_V1 = '_px'
PREFIX_PX_COOKIE_V3 = '_px3'
PREFIX_PX_TOKEN_V1 = '1'
PREFIX_PX_TOKEN_V3 = '3'
PREFIX_PX_DATA_ENRICHMENT = '_pxde'
PREFIX_PXVID = '_pxvid'
MOBILE_SDK_HEADER = "x-px-authorization"
MOBILE_SDK_ORIGINAL_HEADER = "x-px-original-token"
MOBILE_SDK_CONNECTION_ERROR_CODE = '2'
MOBILE_SDK_PINNING_ERR... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import met.metadataparser.models.base
class Migration(migrations.Migration):
dependencies = [
('metadataparser', '0002_add_entity_fields'),
]
operations = [
migrations.RunSQL(
... |
# coding=utf-8
# Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, 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.or... |
import argparse
from argparse import Namespace
import time
import os
import sys
import pprint
import numpy as np
from PIL import Image
import torch
import torchvision.transforms as transforms
sys.path.append(".")
sys.path.append("..")
from utils.common import tensor2im
from models.psp import pSp
from ... |
import datetime
import logging
import time
from functools import wraps
from html import escape as html_escape
import uuid
# noinspection PyPackageRequirements
from telegram import Update
# noinspection PyPackageRequirements
from telegram.error import TimedOut
from telegram.ext import CallbackContext, ConversationHandl... |
# -*- coding: utf-8 -*-
"""Record serializers."""
from invenio_records_rest.serializers.citeproc import CiteprocSerializer
from invenio_records_rest.serializers.response import (
record_responsify, search_responsify
)
from ..marshmallow import CSLRecordSchemaV1, RecordSchemaV1
from .json import MenRvaJSONSeriali... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
# Implementation of Deep Q-Network (DQN)
# Paper: https://www.nature.com/articles/nature14236
# And implementation of Prioritized Experience Replay (PER)
# Paper: https://arxiv.org/abs/1511.05952
device = torch.device("cuda" if torc... |
import sys, os, signal
import threading
def getsignalname(n):
for name, value in signal.__dict__.items():
if value == n and name.startswith('SIG'):
return name
return 'signal %d' % (n,)
timeout = float(sys.argv[1])
timedout = False
def childkill():
global timedout
timedout = True
... |
#!/usr/bin/env python3
# Yes, I am aware that I just switched from 2 spaces to 4 spaces. I installed linux on my desktop and this
# is the default formatting from vim, and also I remembered that it's the preferred tab-width for python.
# I am truly and deeply sorry if this has offended you. If you would like to seek fi... |
#!/usr/bin/env python3
#
# Copyright 2020 IBM
# 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 t... |
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2017, Anaconda, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#---------------------------------------------------... |
from convokit.model import Speaker
from convokit.util import deprecation
from collections import defaultdict
from typing import Callable, Tuple, List, Dict, Optional, Collection, Hashable, Union
CoordinationWordCategories = ["article", "auxverb", "conj", "adverb",
"ppron", "ipron", "preps... |
"""
Copyright 2020 The OneFlow 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 applicable law or agr... |
import rdkit.Chem as Chem
import numpy as np
elem_list = ['C', 'O', 'N', 'F', 'Br', 'Cl', 'S',
'Si', 'B', 'I', 'K', 'Na', 'P', 'Mg', 'Li', 'Al', 'H']
atom_fdim_geo = len(elem_list) + 6 + 6 + 6 + 1
atom_fdim_qm = 10 + 10 + 10 + 10
bond_fdim_geo = 6
bond_fdim_qm = 25 + 40
max_nb = 10
def get_atom_classe... |
"""Provides EntityDatabase, a class that keeps track of spec-defined entities and associated macros."""
# Copyright (c) 2018-2019 Collabora, 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... |
# Generated by Django 3.0.8 on 2020-07-26 18:15
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='User',
f... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-09-09 00:12
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('item', '0018_auto_20160906_0234'),
]
operations = [
migrations.AlterField(
... |
"""Constants for the P1 Monitor integration."""
from __future__ import annotations
from datetime import timedelta
import logging
from typing import Final
DOMAIN: Final = "p1_monitor"
LOGGER = logging.getLogger(__package__)
SCAN_INTERVAL = timedelta(seconds=5)
ENTRY_TYPE_SERVICE: Final = "service"
SERVICE_SMARTMETER... |
from lepl.apps.rfc3696 import HttpUrl
def validate_url(self, url):
"""Validate a HTTP URL.
Args:
url (str): a URL in string form
Returns:
bool: True if valld, False otherwise
"""
validator = HttpUrl()
return validator(url)
|
import sys
import pystache
from collections import deque
MAX_EVENTS_PER_CALL = 10000
END_OF_STREAM = object()
# TODO look into renaming this class / file to conform to standard naming conventions
class AWSLogGenerator(object):
MAX_EVENTS_PER_CALL = 10000
END_OF_STREAM = object()
# TODO figure out a... |
from plotly.basedatatypes import BaseTraceHierarchyType
import copy
class Gradient(BaseTraceHierarchyType):
# color
# -----
@property
def color(self):
"""
Sets the final color of the gradient fill: the center color for
radial, the right for horizontal, or the bottom for vertic... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Xwd(AutotoolsPackage, XorgPackage):
"""xwd - dump an image of an X window."""
homepag... |
#RANDOM FOREST
import pandas as pd
import numpy as np
import os
from sklearn.preprocessing import LabelEncoder
from sklearn.ensemble import RandomForestClassifier
class Mlmodel:
y_train_symp = []
y_train =[]
y_dict = {}
classifier= RandomForestClassifier(n_estimators= 10, criterion="entropy")
def __init__(self)... |
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.models import BaseUserManager
from django.conf import settings
class UserProfileManager(BaseUserManager):
"""Manager for user profiles"""
d... |
"""Create a note-taking program. When a user starts it up, it should prompt them for a filename.
If they enter a file name that doesn't exist, it should prompt them to enter the text they want
to write to the file. After they enter the text, it should save the file and exit.
If they enter a file name that alread... |
import httplib
import json
import sys, os
TEST = False
LB = 'tf-lb-20160919144416835471629f6y-2076752119.us-east-1.elb.amazonaws.com'
# test_region = 'Picardie'
regions = ["Bourgogne", "Lorraine", "Champagne-Ardenne", "Provence-Alpes-Cote-dAzur", "Ile-de-France", "Picardie", "Auvergne", "Franche-Comte", "Pays-de-la-... |
#!/usr/bin/python3
import redis
from redis.commands.search.field import VectorField
from redis.commands.search.query import Query
from img2vec_pytorch import Img2Vec
from PIL import Image
import numpy as np
NUMBER_SAMPLES = 200
FACE_IMAGE_VECTOR_FIELD='face_image_vector'
IMAGE_VECTOR_DIMENSION=1024
r = redis.Redis(ho... |
from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^$', views.homepage, name='homepage'),
url(r'^add_hood/$', views.add_hood, name='add_hood'),
url(r'^join_hood/(\d+)', views.join_hood, name='join_hood'),... |
from django.contrib import admin
from django.db.models import get_model
class ProductRecordAdmin(admin.ModelAdmin):
list_display = ('product', 'num_views', 'num_basket_additions', 'num_purchases')
class UserProductViewAdmin(admin.ModelAdmin):
list_display = ('user', 'product', 'date_created')
class UserR... |
class Solution(object):
def countDigitOne(self, n):
"""
:type n: int
:rtype: int
"""
counts = [(1, 0)]
index = 1
result = 0
while n >= pow(10, index):
zeros = counts[-1][0] + 9 * counts[-1][1]
ones = pow(10, index) + zeros
... |
# -*- coding: utf-8 -*-
import six
from olympia.addons.models import Category
from olympia.amo.tests import TestCase
from olympia.constants.applications import APPS
from olympia.constants.base import ADDON_EXTENSION, ADDON_PERSONA
from olympia.constants.categories import CATEGORIES
from olympia.landfill.categories imp... |
import logging
log = logging.getLogger('boundaries.api.load_shapefiles')
from optparse import make_option
import os, os.path
import sys
from zipfile import ZipFile
from tempfile import mkdtemp
from django.conf import settings
from django.contrib.gis.gdal import (CoordTransform, DataSource, OGRGeometry,
... |
# Copyright (c) 2019 - The Procedural Generation for Gazebo authors
# For information on the respective copyright owner see the NOTICE file
#
# 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
#
#... |
# coding: utf-8
# file generated by setuptools_scm
# don't change, don't track in version control
version = '0.1.dev5+g4383113.d20210608'
version_tuple = (0, 1, 'dev5+g4383113', 'd20210608')
|
# Copyright 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'includes': [
'../build/common.gypi',
],
'targets': [
{
'target_name': 'base',
'type': 'static_library',
'include_dirs': [... |
from xdist.scheduler.each import EachScheduling # noqa
from xdist.scheduler.load import LoadScheduling # noqa
from xdist.scheduler.loadfile import LoadFileScheduling # noqa
from xdist.scheduler.loadscope import LoadScopeScheduling # noqa
from xdist.scheduler.dedicated import DedicatedLoadScheduling # noqa
|
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Matti Hamalainen <msh@nmr.mgh.harvard.edu>
# Martin Luessi <mluessi@nmr.mgh.harvard.edu>
#
# License: BSD (3-clause)
from ..externals.six import string_types
from time import time
import warnings
from copy import deepcopy
impor... |
# Generated by Django 3.0.6 on 2020-05-27 15:05
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('tracks', '0002_track_pos... |
#!/usr/bin/env python
"""
==============================================
Regularization path of L1- Logistic Regression
==============================================
Train l1-penalized logistic regression models on a binary classification
problem derived from the Iris dataset.
The models are ordered from strongest ... |
""" This file implements Flask-User access' checkers: is_authenticated and is_confirmed_email.
:copyright: (c) 2013 by Ling Thio
:author: Ling Thio (ling.thio@gmail.com)
:license: Simplified BSD License, see LICENSE.txt for more details."""
from flask import current_app
from flask_login import current_use... |
import discord
from aiohttp import request
from discord.ext import commands
import database as db
from functions import update_db
import io
import json
import contextlib
import textwrap
class Owner(commands.Cog):
"""A private cog which only works for me."""
def __init__(self, bot):
self.bot = bot
... |
from base_agent.memory_nodes import ReferenceObjectNode
class BotNode(ReferenceObjectNode):
""" a memory node represneting a bot"""
TABLE_COLUMNS = [
"uuid",
"eid",
"x",
"y",
"z",
"ref_type",
"type_name",
]
TABLE = "ReferenceObjects" ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: yuri tolkach
"""
# =============================================================================
# 2. JPEG compression
# =============================================================================
#Parameters
#Number of gaussian levels to test
num_g_lev =... |
"""
Django settings for Alot_Todo project.
Generated by 'django-admin startproject' using Django 3.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
... |
default_app_config = 'django-hasura-auth.apps.AuthConfig' |
import spacy
nlp = spacy.load('en')
nlp.vocab.vectors_length
def respond(message):
doc = nlp(message)
for token in doc:
print("{} : {}".format(token, token.vector[:3]))
msg = ""
while msg != "bye":
msg = input("enter a phrase: ")
print(respond(msg))
|
import torch
import torchvision
class Cifar100Dataset:
def __init__(
self,
batch_size: int = 256,
input_size: int = 32,
num_workers=2,
transforms=None,
):
self.trainset = torchvision.datasets.CIFAR100(
root="./data/CIFAR100",
train=True,... |
# -*- coding: utf-8 -*-
#
# Authors: Tomi Jylhä-Ollila, Finland 2010-2018
# Toni Ruottu, Finland 2013
#
# This file is part of Kunquat.
#
# CC0 1.0 Universal, http://creativecommons.org/publicdomain/zero/1.0/
#
# To the extent possible under law, Kunquat Affirmers have waived all
# copyright and related or ne... |
import os
import sys
import distutils.util
from wheel.macosx_libfile import extract_macosx_min_system_version
from wheel.pep425tags import get_platform
def test_read_from_dynlib():
dirname = os.path.dirname(__file__)
dylib_dir = os.path.join(dirname, "testdata",
"macosx_minimal_s... |
import os
import sys
import unittest
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from scripts.generators import ecs_helpers
class TestECSHelpers(unittest.TestCase):
def test_is_intermediate_field(self):
pseudo_field = {'field_details': {}}
self.assertEqual(ecs_helpers.is_inte... |
import pytest, os, shutil, numpy as np
import sys
sys.path.append((os.path.dirname(os.path.dirname(__file__))))
from inference import inference
from mock import patch
from etiltWav import etiltWav
test_folder_location = os.path.dirname(__file__)
path = os.path.join(test_folder_location, r'folder')
path2label_map_json ... |
import unittest
from stringsheet.parser import parse_file
from stringsheet.writer import get_strings_text
from stringsheet.model import Resources
class BaseParseTestCase(unittest.TestCase):
@property
def test_file(self):
raise NotImplementedError
@property
def output_file(self):
retu... |
#!/usr/bin/env python3
# This file is part of the Printrun suite.
#
# Printrun is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pri... |
#!/usr/bin/env python
import argparse
import json
import importlib
from typing import Dict
import os
##### Hide lines below until Lab 4
import wandb
from training.gpu_manager import GPUManager
##### Hide lines above until Lab 4
from training.util import train_model
DEFAULT_TRAIN_ARGS = {
'batch_size': 32,
'... |
"""Test config validators."""
from collections import OrderedDict
from datetime import date, datetime, timedelta
import enum
import os
from socket import _GLOBAL_DEFAULT_TIMEOUT
from unittest.mock import Mock, patch
import uuid
import pytest
import voluptuous as vol
import homeassistant
from homeassistant.helpers imp... |
import numpy as np
import cv2
def draw_polygone(image, plane):
contours = np.array(plane.points).astype(dtype=np.float)
color_tuple = tuple([int(part) for part in plane.color])
cv2.fillPoly(image, pts=np.int32([contours]), color=color_tuple)
return image
def draw_polygones(planes, image_shape):
... |
def add(a, b):
'''
>>> add(1, 2)
3
>>> add(5, 10)
15
'''
return a + b
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=True)
|
import numpy as np
import matplotlib.pyplot as plt
from constants import width, height, terrain_ids, n_px
# in RGB format
#gold = [99.3, 68.8, 1.0]
#silver = [47.8, 47.8, 47.8]
#blue = [8.2, 39.4, 95.6]
#green = [4.6, 43.8, 2.5]
#pink = [85.4, 47.7, 45.9]
#gold = np.array([99.3, 68.8, 1.0])
#silver = np.array([47.8, ... |
from sfepy.discrete.fem import FEDomain
import scipy.sparse as sps
import numpy as nm
from sfepy.base.compat import factorial
from sfepy.base.base import output
from numpy.core import intc
from numpy.linalg import lapack_lite
def elems_q2t(el):
nel, nnd = el.shape
if nnd > 4:
q2t = nm.array([[0, 2, 3,... |
# Copyright 2017 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 applica... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.