text stringlengths 2 999k |
|---|
from __future__ import absolute_import
import logging
import os
from pip9.exceptions import CommandError
from pip9.index import FormatControl
from pip9.req import RequirementSet
from pip9.basecommand import RequirementCommand
from pip9 import cmdoptions
from pip9.utils import ensure_dir, normalize_path
from pip9.util... |
import datetime
import pytest
from sepaxml import SepaDD
from sepaxml.validation import ValidationError
def test_name_too_long():
sdd = SepaDD({
"name": "TestCreditor",
"BIC": "BANKNL2A",
"IBAN": "NL50BANK1234567890",
"batch": True,
"creditor_id": "000000",
"curre... |
#!python3
""" Main Meshtastic
"""
import argparse
import platform
import logging
import sys
import time
import yaml
from pubsub import pub
import pyqrcode
import pkg_resources
import meshtastic.util
import meshtastic.test
from . import remote_hardware
from . import portnums_pb2, channel_pb2, radioconfig_pb2
from .glob... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import finance.models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='VatCode',
fields=[
('id',... |
from datetime import datetime, timedelta
from ebedke.utils.date import days_lower, on_workdays
from ebedke.utils import facebook
from ebedke.utils.text import pattern_slice
from ebedke.pluginmanager import EbedkePlugin
FB_PAGE = "https://www.facebook.com/HomeFieldPub/"
FB_ID = "190139087785846"
@on_workdays
def getM... |
import torch.utils.data as data
import torch
import albumentations
import cv2
import numpy as np
import random
import math
from settings import train_png_dir
def generate_transforms(image_size):
IMAGENET_SIZE = image_size
train_transform = albumentations.Compose([
albumentations.Resize(IMAGENET_SIZE, ... |
from narrative2vec.logging_instance.logging_instance import LoggingInstance, _get_first_rdf_query_result
from narrative2vec.logging_instance.reasoning_task import ReasoningTask
from narrative2vec.ontology.neemNarrativeDefinitions import QUATERNION
from narrative2vec.ontology.ontologyHandler import get_knowrob_uri
cla... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 25 14:11:02 2020
@author: avanetten
"""
from shapely.ops import cascaded_union
import matplotlib.pyplot as plt
import geopandas as gpd
import multiprocessing
import pandas as pd
import numpy as np
import skimage.io
import tqdm
import glob
import ma... |
# -*- coding: utf-8 -*-
'''
Module to interact with Junos devices.
'''
from __future__ import absolute_import
# Import python libraries
import logging
import json
import os
try:
from lxml import etree
except ImportError:
from salt._compat import ElementTree as etree
# Juniper interface libraries
# https://gi... |
# pylint: disable=redefined-outer-name
import pytest
from unittest.mock import Mock
from bentoml.adapters import DefaultOutput
from bentoml.service import InferenceAPI
@pytest.fixture(params=(True, False))
def batch_mode(request):
return request.param
@pytest.fixture()
def make_api(batch_mode):
service_m... |
# 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 applica... |
import numpy as np
import dataloaders.transforms as transforms
from dataloaders.dataloader import MyDataloader
iheight, iwidth = 480, 640 # raw image size
#class NYUDataset(MyDataloader):
class NYUDataset(customNYUv2):
#def __init__(self, root, type, sparsifier=None, modality='rgb'):
def __init__(self, root, ... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#############################################################
# File: LossUtili.py
# Created Date: Thursday October 10th 2019
# Author: Chen Xuanhong
# Email: chenxuanhongzju@outlook.com
# Last Modified: Monday, 14th October 2019 5:19:31 pm
# Modified By: Chen Xuanhong
# C... |
spisok = [int(i) for i in input().split()]
sspisok = sorted(spisok, reverse=True)
print(sspisok[0:3]) |
"""
ASGI config for shop_back project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefaul... |
# Copyright (c) 2014-2018, F5 Networks, 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 ... |
from setuptools import setup, find_packages
with open('README.md', encoding='utf-8') as f:
readme = f.read()
setup(
name="mkdocs-video",
version="1.1.0",
author="Mikalai Lisitsa",
author_email="mikalai.lisitsa@gmail.com",
url="https://github.com/soulless-viewer/mkdocs-video",
description="... |
"""
Introduction to Computer Programming in Python: A Hands-on Approach
Part 2: Game Loop, Change Turn and Win Condition
"""
class TicTacToe(object):
def __init__(self):
self.board = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
self.p... |
# Copyright (C) 2015 Atsushi Togo
# All rights reserved.
#
# This file is part of phonopy.
#
# 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
# notic... |
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
"""
This is the main module in vnc_cfg_api_server package. It manages interaction
between http/rest, address management, authentication and database interfaces.
"""
from __future__ import absolute_import
from future import standard_library
standard_l... |
# stdlib
import sys
from typing import Any
from typing import Optional
# third party
from google.protobuf.reflection import GeneratedProtocolMessageType
# syft relative
from ... import deserialize
from ... import serialize
from ...core.common import UID
from ...core.common.serde.serializable import bind_protobuf
from... |
#!/usr/bin/env python3
# Copyright (c) 2014-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the rawtransaction RPCs.
Test the following RPCs:
- createrawtransaction
- signrawtransacti... |
"""
@FileName: GenerateData.py
@Description: Implement GenerateData
@Author: Ryuk
@CreateDate: 2020/05/13
@LastEditTime: 2020/05/13
@LastEditors: Please set LastEditors
@Version: v0.1
"""
import glob
from tqdm import tqdm
fn = "./data_list.txt"
wav_path = "./data/wav/*.wav"
vad_path = "./data/vad/*.txt"
wav_files =... |
import pydicom
from pydicom.data import get_testdata_files
import matplotlib.pyplot as plt
# get some test data
# filename = get_testdata_files("CT_small.dcm")[0]
filename = "my_dicom.dic"
ds = pydicom.dcmread(filename)
pixel_bytes = ds.pixel_array
print(ds.PatientName)
print(ds[0x10,0x10].value)
ds.PatientID = "XXXX... |
import json
def loadConfig():
with open('./config.json', 'r') as f:
content = json.load(f)
return content
def filtFileName(rawName, kind='JSON'):
'''
A util function just used for make objname.json to objname. Default file type is json
'''
l = len(kind) + 1
return rawNa... |
#!/usr/bin/python
from participantCollection import ParticipantCollection
import re
import datetime
import pyperclip
# Edit Me!
# This script gets run on the first day of the following month, and that month's URL is
# what goes here. E.g. If this directory is the directory for February, this script gets
# run on Marc... |
from . import app
def main(argv=None):
app.main(argv)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('user_management', '0003_auto_20150508_1210'),
]
operations = [
migrations.RemoveField(
model_name='userprofile',... |
#!/usr/bin/env python
"""L2XC Multi-instance Test Case HLD:
**NOTES:**
- higher number (more than 15) of pg-l2 interfaces causes problems => only
14 pg-l2 interfaces and 10 cross-connects are tested
- jumbo packets in configuration with 14 l2-pg interfaces leads to
problems too
**config 1**
- ... |
# Generated by Django 3.2 on 2021-04-08 07:46
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("core", "0021_upload_analyzed_file"),
]
operations = [
migrations.AddField(
model_name="datas... |
# Copyright 2020 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... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import numpy as np
import copy
from local.pso.pso_atoms import PsoAtoms
from local.pso.Pre_Relax import PreRelax
from scipy.optimize import linear_sum_assignment
class Pso(object):
"""Pso object.
The Pso object contains the main process of PSO.
It m... |
from scene.track.track import Track
from scene.track.rail_point import RailPoint
from scene.track.rail import Rail
|
# -*- test-case-name: twisted.test.test_stdio.StandardInputOutputTests.test_lastWriteReceived -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Main program for the child process run by
L{twisted.test.test_stdio.StandardInputOutputTests.test_lastWriteReceived}
to test that L{os.write} can... |
"""
test_indexing tests the following Index methods:
__getitem__
get_loc
get_value
__contains__
take
where
get_indexer
get_indexer_for
slice_locs
asof_locs
The corresponding tests.indexes.[index_type].test_indexing files
contain tests for the corresponding methods specific to th... |
import datasetWriter as dW
train_percent = 60
val_percent = 35
tag_non_erase = 60
print("\nDataset Creation Started\n")
print("\n-- Writing TF records...\n")
dW.run(train_percent, val_percent, tag_non_erase)
print("\nDataset Creation Finished\n") |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class endUser(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
# make sure this is unique
username = models.CharField(max_len... |
# Generated by Django 3.2.3 on 2021-05-26 07:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('orders', '0002_auto_20210526_0703'),
]
operations = [
migrations.AddField(
model_name='order',
name='country',
... |
import os
from typing import Optional
# QCoDeS imports
from qcodes.instrument_drivers.Minicircuits.Base_SPDT import (
SPDT_Base, SwitchChannelBase)
try:
import clr
except ImportError:
raise ImportError("""Module clr not found. Please obtain it by
running 'pip install pythonnet'
... |
"""
jsonspec.validators.pointer_util
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
from __future__ import absolute_import
def pointer_join(pre, *parts):
resp = str(pre or '#')
if resp == '#/':
resp == '#'
for part in parts:
if not resp.endswith('/'):
resp += '/'
resp +... |
import tensorflow as tf
from tensorflow.python import debug as tf_debug
from collections import namedtuple
from .estimator import get_estimator
from .input import gen_input_fn
from .args import *
# Make TF be quiet
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"]="2"
import logging
logger = logging.getLogger(__name__)
... |
norm_cfg = dict(type='SyncBN', requires_grad=True)
model = dict(
type='EncoderDecoder',
pretrained=None,
backbone=dict(
type='ResNetV1d',
depth=101,
num_stages=4,
out_indices=(0, 1, 2, 3),
dilations=(1, 1, 2, 4),
strides=(1, 2, 1, 1),
norm_cfg=dict(typ... |
import webbrowser
import random
from typing import TextIO, Tuple, Optional
import os
browser = "https://google.com/"
def user_input(url: str):
"""Takes input and performs search."""
print("Launching...\n")
print("Find something sustainable today!\nEnter a search term, as you normally would on Google. We'... |
"""
Token-based auth for S3 buckets, handing out presigned urls.
ENV Args:
S3_ADDRESS = S3 endpoint address
ACCESS_KEY = S3 access key
SECRET_KEY = S3 secret key
EXPIRE_DEFAULT = default url expiration in seconds (default: 1 hour)
EXPIRE_LIMIT = limit for url expiration in seconds (default: 1 day)
... |
"""
Create a new Module.
"""
import support
from org.python.core import PyModule, PyInstance
test = PyModule("test", {})
exec "a = 2" in test.__dict__
support.compare(len(test.__dict__), "3")
#test = PyInstance.__tojava__(test, PyModule)
exec "b = 3" in test.__dict__
support.compare(len(test.__dict__), "4")
|
# 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 Lcio(CMakePackage):
"""HEP Library for Linear Collider Input/Output"""
homepage = "h... |
"""
cfg.py
Example of saving different network components to file
cfg is an object containing a set of simulation configurations using a standardized structure
"""
from netpyne import specs
cfg = specs.SimConfig() # object of class SimConfig to store the simulation configuration
# ------------------------------... |
"""
Contabo API
The version of the OpenAPI document: 1.0.0
Contact: support@contabo.com
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from pfruck_contabo.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal,
... |
from datetime import datetime
import numpy as np
import pandas.util.testing as tm
from pandas import Series, date_range, NaT
class SeriesConstructor(object):
params = [None, 'dict']
param_names = ['data']
def setup(self, data):
self.idx = date_range(start=datetime(2015, 10, 26),
... |
"""Suppoort for Ariston binary sensors."""
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_CONNECTIVITY,
DEVICE_CLASS_HEAT,
BinarySensorEntity,
)
from homeassistant.const import CONF_BINARY_SENSORS, CONF_NAME
import logging
from datetime import timedelta
from .const import (... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2019-07-24 18:29:48
# @Author : Zhi Liu (zhiliu.mind@gmail.com)
# @Link : http://iridescent.ink
# @Version : $1.0$
import torch as th
import torchlib as tl
class ContrastReciprocalLoss(th.nn.Module):
r"""ContrastReciprocalLoss
way1 is defined as... |
"""
This module defines the user model and associated functions
"""
from werkzeug.security import generate_password_hash
from .base_models import BaseModels
class UserModel(BaseModels):
"""
This class encapsulates the functions of the user model
"""
def __init__(self):
"""Initializes databas... |
import json
import config
from sdk import services
campaigns, jobs, tasks, results = services.get(config)
print("")
print("Campaigns:")
for campaign in campaigns.get_all():
print(" %s %s %s" % (campaign["id"], campaign["name"], campaign["title"]))
print("")
print(" Results:")
result_list = campa... |
# coding=utf-8
# Copyright 2018 The Tensor2Tensor Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... |
# Copyright 2019 The Bazel 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 la... |
from sqlalchemy.engine import URL
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import declarative_base, sessionmaker
SQLALCHEMY_DATABASE_URL = URL.create(
"cockroachdb+asyncpg",
username="root",
host="localhost",
port=26257,
database="defaultdb",
quer... |
#
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021 Jared Crapo
#
# 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, mod... |
# coding: utf-8
"""
pollination-server
Pollination Server OpenAPI Definition # noqa: E501
The version of the OpenAPI document: 0.16.0
Contact: info@pollination.cloud
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import datetime
import... |
from django import forms
from django.contrib.auth.hashers import check_password
from django.contrib.auth.password_validation import (
password_validators_help_texts, validate_password,
)
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from pytz import common_timezones
from pr... |
"""
Defines the building blocks for Individuals.
Individuals represent machine learning pipelines in a back-end agnostic way.
An Individual can be converted to its back-end specific representation
(e.g. a scikit-learn Pipeline) by calling its `pipeline` property
as long as a function has been provided to convert the in... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import pytest
from libvcs.shortcuts import create_repo_from_pip_url
from libvcs.util import run
@pytest.fixture
def tmpdir_repoparent(tmpdir_factory, scope='function'):
"""Return temporary directory for repository c... |
# 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... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as AuthUserAdmin
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from tastypie.admin import ApiKeyInline
from... |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is ... |
from api.bucket import app
if __name__ == '__main__':
app.run(debug=True) |
from helpers.Database import db
import sys
arg = sys.argv
DB = db('mysql', 'pymysql', arg[1], arg[2], arg[3])
name = 'KeyGenes_PL'
DB.add_db(name)
with open(arg[4], "w") as out:
out.write(name) |
from discord.ext import commands
import discord
import random
from . import LTPcogs
from . import LTPlib as ltp
from . import Twenty_doors
# はじめに呼び出されるコグ
class General(commands.Cog):
# コンストラクタ
def __init__(self, bot):
self.bot = bot
# ゲーム中か否かの判断変数。鍵の名前はそのままコグの名前にする
self.has_started =... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** 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 _utilities
fro... |
# all plugins are imported from bothub,x-tra-telegram by @heyworld
# Don't edit or you gay
# credits: spechide,ravana69,mkaraniya & me
import asyncio
from collections import deque
from telethon import events
from telethon.errors.rpcerrorlist import MessageIdInvalidError
from userbot import ALIVE_NAME, CMD_HELP, bot
f... |
# ***************************************************************************************
# ***************************************************************************************
#
# Name : showdictionary.py
# Author : Paul Robson (paul@robsons.org.uk)
# Date : 7th December 2018
# Purpose : List Dictionary con... |
import string
from itertools import product
from time import time
from numpy import loadtxt
def product_loop(password, generator):
for p in generator:
if ''.join(p) == password:
print('\nPassword:', ''.join(p))
return ''.join(p)
return False
def bruteforce(passw... |
"""
Training helpers for supervised meta-learning.
"""
import os
import time
import tensorflow as tf
from .reptile import Reptile
from .variables import weight_decay
# pylint: disable=R0913,R0914
def train(sess,
model,
train_set,
test_set,
save_dir,
num_classes=5,
... |
import sys, struct, binascii, os.path, json, uuid, base64, StringIO
class YbPrefix:
def __init__(self):
self.data = []
def __len__(self):
return sum((4 + len(val) for key, val in self.data))
def clear(self):
del self.data[:]
def load(self, stream):
data = []
w... |
# coding: utf-8
"""
Module for converting DWI of ADNI
"""
__author__ = "Jorge Samper-Gonzalez and Sabrina Fontanella"
__copyright__ = "Copyright 2016-2019 The Aramis Lab Team"
__license__ = "See LICENSE.txt file"
__version__ = "0.1.0"
__maintainer__ = "Jorge Samper-Gonzalez"
__email__ = "jorge.samper-gonzalez@inria.... |
# Copyright 2017,2018,2019,2020,2021 Sony 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... |
# Copyright 2020 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... |
from . import clean, compare, sorting, conversion, parallaxhandling
from .clean import *
from .compare import *
from .sorting import *
from .conversion import *
from .parallaxhandling import *
__all__ = []
__all__.extend(sorting.__all__)
__all__.extend(clean.__all__)
__all__.extend(compare.__all__)
__all__.extend(conv... |
"""Support for local control of entities by emulating a Philips Hue bridge."""
import asyncio
import logging
from .config import Config
from .hass import HomeAssistant
from .hue_api import HueApi
from .upnp import UPNPResponderThread
_LOGGER = logging.getLogger(__name__)
class HueEmulator:
"""Support for local ... |
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "LICENSE.txt" file acc... |
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-generic-plus',
version="2.4.0",
install_requires=[
'python-monkey-business>=1.0.0',
],
description="Django model field that combines the functionality of "
"GenericForeignKey and FileField... |
# Copyright 2013 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.
import logging
import os
import re
import signal
import subprocess
import sys
import tempfile
from devil.android import device_errors # pylint: disable=imp... |
# Copyright (c) 2018 http://reportportal.io
#
# 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 nose
import sys
import os
import warnings
import tempfile
from contextlib import contextmanager
import datetime
import numpy as np
import pandas
from pandas import (Series, DataFrame, Panel, MultiIndex, bdate_range,
date_range, Index, DatetimeIndex, isnull)
from pandas.io.pytables import (H... |
# connectors/pyodbc.py
# Copyright (C) 2005-2022 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
import re
from urllib.parse import unquote_plus
from . import Connector
from ... |
import numpy as np
from shapely.geometry import Polygon
# Pad and unpack the transformation matrix to be 3x1 or 3x3,
# necessary for it to handle both rotation and translation
pad = lambda x: np.hstack([x, np.ones((x.shape[0], 1))])
unpad = lambda x: x[:, :-1]
def norm(pri):
pri = pri.copy()
pri[:, 0] = pri[:... |
from django import forms
from .models import Comment
import mistune
class CommentForm(forms.ModelForm):
nickname = forms.CharField(max_length=50, label='昵称', widget=forms.widgets.Input(
attrs={
'class': 'form-control',
'style': 'width: 60%;'
}
))
email = forms.CharF... |
from traceback import format_exception
from typing import Sequence
class BrokenResourceError(Exception):
"""
Raised when trying to use a resource that has been rendered unusuable due to external causes
(e.g. a send stream whose peer has disconnected).
"""
class BrokenWorkerProcess(Exception):
""... |
from typing import NamedTuple
class Token(NamedTuple):
"""
A simple token representation, keeping track of the token's text, offset in the passage it was
taken from, POS tag, dependency relation, and similar information. These fields match spacy's
exactly, so we can just use a spacy token for this.
... |
from credentials import Cred
import pyperclip
import unittest # Importing the unittest module
from user import User # Importing the user class
class TestUser(unittest.TestCase):
'''
Test class that defines test cases for the user class behaviours.
Args:
unittest.TestCase: TestCase class that help... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/region/shared_battlefield_marker.iff"
result.attribute_template_id ... |
"""cci_nepal."""
import logging
import logging.config
from pathlib import Path
from typing import Optional
import yaml
from dotenv import load_dotenv
def get_yaml_config(file_path: Path) -> Optional[dict]:
"""Fetch yaml config and return as dict if it exists."""
if file_path.exists():
with open(file_... |
# -*- coding: utf-8 -*-
class BadSongFile(Exception):
def __init__(self, path): self.path = path
def __str__(self): return "Can't read %s" % self.path
class NoConfigFile(Exception):
def __init__(self, path): self.path = path
def __str__(self):
return "Path '%s' for config file does not exit" % ... |
# -*- coding: utf-8 -*-
#
# Setuptools documentation build configuration file, created by
# sphinx-quickstart on Fri Jul 17 14:22:37 2009.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pick... |
from pydsa.searching.linear_search import linear_search
def test_linear_search():
List = [4, 17, 9, 12, 5, 16]
item = 12
assert linear_search(List, item) == 3
|
""" Represents a collection of trip stays and home stays. """
import csv, datetime
from datetime import date, timedelta
from svg_chart import SVGChart
class StaysCollection:
MERGE_RANGE_DAYS = 1 # Max days between trips to merge them
PRINT_DATE_FORMAT = '%a %d %b %Y'
def __init__(self, data_csv_pat... |
from vispy import scene
from vispy.visuals.transforms import STTransform, ChainTransform
from glue_vispy_viewers.compat.axis import Axis
import numpy as np
class AxesVisual3D(object):
def __init__(self, view=None, transform=None, **kwargs):
self.view = view
# Add a 3D cube to show us the unit... |
import os
class BaseConfig:
"""Base configuration"""
TESTING = False
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = "my_precious"
DEBUG_TB_ENABLED = False
DEBUG_TB_INTERCEPT_REDIRECTS = False
class DevelopmentConfig(BaseConfig):
"""Development configuration"""
SQLALCHEMY_DATAB... |
#!env python
# -*- coding: utf-8 -*-
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
... |
colors = {
'sidebar': {
'font': 'gray10',
'bg': 'gray90',
'activebg': 'gray70'
},
'main': {
'font': 'gray10',
'bg': 'snow',
'activebg': 'turquoise2'
}
} |
import torch as th
from torch.distributions import Categorical
from .epsilon_schedules import DecayThenFlatSchedule
REGISTRY = {}
class MultinomialActionSelector():
def __init__(self, args):
self.args = args
self.schedule = DecayThenFlatSchedule(args.epsilon_start, args.epsilon_finish, args.eps... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.