content stringlengths 5 1.05M |
|---|
# Copyright (c) 2021 by Don Deel. All rights reserved.
"""
RedfishODataService API Definitions.
Defines REST API behaviors for RedfishODataService.
Allows initial data for instances of this API object to be set.
Based upone Singleton template version 0.9.0
"""
# Standard library module imports
# None
# Third party... |
class FindMin():
def __init__(self,num1,num2,num3):
self.num1=num1
self.num2=num2
self.num3=num3
def find_min(self):
smallest=self.num1
if smallest > self.num2:
smallest=self.num2
if smallest > self.num3:
smallest=self.num3
return smallest
# Main Program
x=FindMin(2,-5,25... |
# This code is all CDS code
# Author: David Wu (dwu@broadinstitute.org)
import collections
import pandas as pd
import pickle
import random
import sys
from scipy.special import comb
from scipy.stats import pearsonr
from sklearn.ensemble import RandomForestRegressor
# Generate 10 random splits of cell lines for a tissu... |
# coding: utf-8
# Author:雪山凌狐
# website:http://www.xueshanlinghu.com
# version: 1.1
# update_date:2020-01-28
# 自己封装的SMTP发送邮件类,一般用于QQ邮箱SMTP发信
import smtplib
import email.utils
from email.message import EmailMessage
import os
try:
# 外部使用本包导入方式
from .xs_sendmail_setting import sender, receiver, username, password
exc... |
from django.urls import path
from django.conf.urls import url
from . import views
urlpatterns = [
#path('signup/', views.SignUp.as_view(), name='signup'),
path('camera/cholesterol_login/', views.cholesterol_login, name='cholesterol_login'),
path('camera/bilirubin_login/', views.bilirubin_login, ... |
# -*- coding: utf-8 -*-
from .util.pyutil import ChemPyDeprecationWarning
import warnings
from .electrolytes import (
A,
B,
limiting_log_gamma,
extended_log_gamma,
davies_log_gamma,
limiting_activity_product,
extended_activity_product,
davies_activity_product,
)
warnings.warn("use .... |
from empire import *
from empire.enums.base_enum import BaseEnum
class PythonTokenTypes(BaseEnum):
ENDMARKER: Final[int] = 0
NAME: Final[int] = 1
NUMBER: Final[int] = 2
STRING: Final[int] = 3
NEWLINE: Final[int] = 4
INDENT: Final[int] = 5
DEDENT: Final[int] = 6
LPAR: Final[... |
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
from services import CCTVService
class CCTV_Api(object):
@staticmethod
def main():
while 1:
service = CCTVService()
menu = input('0-Exit, 1-read_csv 2-read_xls 3-read_json')
if menu == '0'... |
import unittest
import numpy
import pytest
import chainer
from chainer import backend
from chainer.backends import _cpu
from chainer.backends import cuda
from chainer import functions
from chainer import testing
import chainerx
def _to_gpu(x, device_id):
if device_id >= 0:
return cuda.to_gpu(x, device_i... |
# -*- coding: utf-8 -*-
# Copyright 2020 ICON Foundation
#
# 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 o... |
import datetime as dt
import logging
import random
import sqlite3
logger = logging.getLogger(__file__)
with open('data/first_names.txt') as f:
first_names = [n.strip() for n in f]
with open("data/last_names.txt") as f:
last_names = [n.strip() for n in f]
CLASS_NAMES = [
"Mineral Psychology",
"Und... |
ano = int(input("Digite o ano: "))
if ano%100 == 0 and ano%400 == 0:
print('Bissexto!!')
else :
if ano%4 == 0:
print('Bissexto!!')
else:
print('Não é Bissexto!')
|
#!/usr/bin/env python3
#coding=utf-8
import os
import VBREG as REG
import CorpusReader as cr
os.system('clear')
print('Training starts - Tuna-Furniture')
ts,ds,ats = cr.LoadAlignedRegCorpus('Corpora/ETunaF-Aligned2.json')
reg = REG.VBREG(ts,ds,ats)
print('Training completes')
# "targets": [
# "colour=grey;ori... |
import os
from math import cos, sin, pi
def rotate_vector(theta, vector):
#Rotation by anti-clocwise rotation matrix
R = [ [cos(theta), -sin(theta)], [sin(theta), cos(theta)]]
new_vector = list(); new_vector.append(0); new_vector.append(0);
for i in xrange(2):
for j in xrange(2):
new_... |
import os
SAMPLES_DIR = '/home/pi/ArchSound/ArchSound/samples/'
SAMPLES_CONFIG = [
{'zone': '1', 'space': SAMPLES_DIR + '01_molenstraat/space.wav', 'steps': SAMPLES_DIR + '01_molenstraat/steps.wav'},
{'zone': '2', 'space': SAMPLES_DIR + '02_pocket_park/space_steps.wav', 'steps': ''},
{'zone': '3', 'space'... |
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
''' IMPORTS '''
import os
import traceback
import requests
import zipfile
import io
from datetime import datetime as dt
# Disable insecure warnings
requests.packages.urllib3.disable_warnings()
''' GLOBALS/PARAMS '''
... |
import qcore
from qcore.asserts import AssertRaises
class Foo(metaclass=qcore.DisallowInheritance):
pass
def test_disallow_inheritance():
with AssertRaises(TypeError):
class Bar(Foo):
pass
|
#!/usr/bin/env python
from __future__ import print_function
import jinja2
import argparse
import os
import fnmatch
import numpy as np
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('filename')
parser.add_argument('env_dir')
args = parser.parse_args()
env = jinja2... |
from django.urls import path
from . import views
urlpatterns = [
path('textCheck', views.textCheck, name='textCheck'),
path('check', views.check, name='check'),
path('check_result', views.check_result, name='check_result'),
path('globalUpload', views.globalUpload, name='globalUpload'),
path('fileM... |
from math import *
inp = input().split(" ")
n = int(inp[0])
r = int(inp[1])
fives = 1
for i in range(n):
a = int(input())
fives = (fives*a)//gcd(fives,a)
print((fives+r) % (10**9+7)) |
import unittest
from xappt.models.callback import Callback
class CallbackHost:
def __init__(self):
self.call_info = {
'a': [],
'b': [],
'c': [],
}
def callback_method_a(self, *args, **kwargs):
self.call_info['a'].append((args, kwargs))
def cal... |
"""Test the ht.pyfilter.operations.primaryimage module."""
# =============================================================================
# IMPORTS
# =============================================================================
# Standard Library
import argparse
# Third Party
import pytest
# Houdini Toolbox
from h... |
import os
import cv2
import torch
import numpy as np
class SAVE_ATTEN(object):
def __init__(self, save_dir='../save_bins'):
"""
save_dir: the path for saving target
"""
self.save_dir = save_dir
if not os.path.exists(self.save_dir):
os.makedirs(sel... |
from django.apps import AppConfig
class ContactUpdateConfig(AppConfig):
name = 'contact_update'
|
import os
from dotenv import load_dotenv, find_dotenv
class Config(object):
# Environment config
SECRET_KEY = os.environ.get('SECRET_KEY', 'dev')
BASE_PATH = os.environ.get('BASE_PATH', '')
DB_HOST = os.environ.get('DB_HOST', 'localhost')
DB_USER = os.environ.get('DB_USER', 'user')
DB_PASS = ... |
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright 2021- QuOCS 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://ww... |
from .utils.packetCreator import *
"""
Format of an SSL record
Byte 0 = SSL record type
Bytes 1-2 = SSL version (major/minor)
Bytes 3-4 = Length of data in the record (excluding the header itself). The maximum SSL supports is 16384 (16K).
Byte 0 can have following values:
SSL3_RT_CHANGE_CIPHER_SPEC 20... |
from collections import defaultdict
def sock_merchant(sock_colors):
sock_counter = defaultdict(int)
result = 0
for sock_color in sock_colors:
sock_counter[sock_color] += 1
for sock_type_count in sock_counter.values():
result += sock_type_count // 2
return result
n = int(input(... |
import os
from flask import Flask, Response, request
import requests
import requests_ftp
import xml.etree.ElementTree as ET
from pprint import pprint
import json
import datetime
# Set up FTP
requests_ftp.monkeypatch_session()
cache = dict()
def get_cached_result(url: str) -> ET.Element:
cach... |
from setuptools import setup, find_packages
import robosync
setup(
name='robosync',
version=robosync.__version__,
url='https://github.com/rbn920/robosync/',
license='MIT',
author='Robert Nelson',
test_require=['unittest'],
author_email='robertb.nelson@gmail.com',
description='Sync with ... |
# WARPnet Client<->Server Architecture
# WARPnet Parameter Definitions
#
# Author: Siddharth Gupta
import struct, time
from warpnet_framework.warpnet_common_params import *
from warpnet_framework.warpnet_client_definitions import *
from twisted.internet import reactor
import binascii
RETRANSMIT_COUNT = 10 # Max retri... |
##########################################################################
#
# Copyright (c) 2013-2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redi... |
from .linked_list import LinkedList
from .hashmap import HashMap
|
import pytest
import os
@pytest.fixture(autouse=True)
def is_skinny():
if "MLFLOW_SKINNY" not in os.environ:
pytest.skip("This test is only valid for the skinny client")
def test_fails_import_flask():
import mlflow
assert mlflow is not None
with pytest.raises(ImportError):
import f... |
from abc import ABC, abstractmethod
from typing import List
class Collision(ABC):
"""Abstract interface for a game collision."""
@abstractmethod
def snake(self, location: List) -> bool:
pass
@abstractmethod
def apple(self, location: List) -> bool:
pass
class GameCollision(Colli... |
import unittest
import uuid
import mock
def fake_id(prefix):
entropy = ''.join([a for a in str(uuid.uuid4()) if a.isalnum()])
return '{}_{}'.format(prefix, entropy)
class APITestCase(unittest.TestCase):
def setUp(self):
super(APITestCase, self).setUp()
self.requestor_patcher = mock.patc... |
import os
import fcntl
import os.path
import pytest
import simplejson
from .conftest import requires_questionnaire, requires_mongomock
from happi.backends.json_db import JSONBackend
from happi.errors import DuplicateError, SearchError
from happi import Client
from happi.containers import Motor
@pytest.fixture(scope... |
try:
import uwsgi # noqa: F401
except ModuleNotFoundError:
class postfork:
"""Simple non-uwsgi stub that just calls the postfork function"""
def __init__(self, f):
f()
def __call__(self, f):
pass
else:
import uwsgidecorators
postfork = uwsgidecorato... |
from django.contrib import admin
from .models import Board, Post, Topic
# Register your models here.
admin.site.register(Board),
admin.site.register(Post),
admin.site.register(Topic), |
class Triangle:
EQUILATERAL = "equilateral"
ISOSCELES = "isosceles"
SCALENE = "scalene"
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
if self.error():
raise TriangleError
def kind(self):
if self.equilateral():
return ... |
from .visible_object import VisibleObject
from ..aabb import AABB
class Sphere(VisibleObject):
TYPE = 'sphere'
def __init__(self, **kwargs):
self._location = [0, 0, 0]
self._size = 2
attribute_mappings = {
'location': {
'attribute': '_location'
... |
"""
Utilities for Django Models
"""
# Python
from typing import Any
# Django
from django.forms.widgets import ChoiceWidget
from django import forms
# Django filters
import django_filters as filters
def set_placeholder(field: Any, text: str) -> Any:
"""
Pass a Django form field and set a placeholder widget a... |
#Feliz Natal
dia = 25
if(dia == 24):
print('Bora comer panetone')
print('Beber um refri')
print('comer doce')
elif dia == 25:
print('Feliz Natal!!!')
|
import pytest
@pytest.mark.django_db
def test_signed_out_homepage(client):
response = client.get("/")
assert response.status_code == 200
assert b'<a href="/login/auth0">Sign in</a>' in response.content
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: lipeijie
import os
import sys
sys.path.insert(0, os.getcwd() + "/.")
import json
from pathlib import Path
import time
import re
import fire
import psutil
import numpy as np
import torch
from google.protobuf import text_format
import torchplus
from second.builder ... |
def test():
assert (
"from spacy.tokens import Doc" in __solution__
), "Importes-tu correctement la classe Doc ?"
assert (
len(spaces) == 5
), "Il semble que le nombre d'espaces ne correspond pas au nombre de mots."
assert all(isinstance(s, bool) for s in spaces), "Les espaces doiven... |
import yaml
from definitions import CONFIG_PATH, DEFAULT_SETTINGS
config = yaml.safe_load(open(CONFIG_PATH, encoding="utf8"))
for setting, default_value in DEFAULT_SETTINGS.items():
if setting not in config:
config[setting] = default_value
|
from database import database, manage, models
|
from django.apps import AppConfig
class portfolioConfig(AppConfig):
name = 'portfolio'
|
import sublime
import sublime_plugin
from Default.exec import ExecCommand
# Related reading/viewing;
# https://stackoverflow.com/questions/56934013/sublimetext-run-the-exec-with-current-file-as-arg-tab-context-menu
# https://youtu.be/WxiMlhOX_Ng
# This plugin is a combination of an exec variant written for a... |
bl_info = {
"name": "Window Generator",
"description": "Generate Window Arrays",
"author": "Austin Jacob",
"version": (1, 0, 0),
"blender": (2, 79, 0),
"location": "View3D > Add > Mesh",
"warning": "", # used for warning icon and text in addons panel
"wiki_url": "",
"tracker_url": ""... |
#
# Copyright 2016 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... |
import torch
import torch.nn.functional as F
from torch import nn
from .pooler import RoIAlign
from .utils import Matcher, BalancedPositiveNegativeSampler, roi_align
from .box_ops import BoxCoder, box_iou, process_box, nms
def fastrcnn_loss(class_logit, box_regression, label, regression_target):
classifier_loss ... |
import time
import loggedmethods
class BaseInstrument(object):
logged_methods_on = False
capabilities = (
{'name': 'SystemTime', 'type': 'property'},
)
def __init__(self):
pass
def getSystemTime(self):
return time.time()
def getCapabilities(self):
implemented = []
for cap in self.capabilities:
fo... |
# charter.renderers.pdf.title
#
# Renderer for drawing a title onto the chart in PDF format.
from ...constants import *
#############################################################################
def draw(chart, canvas):
text_width = canvas.stringWidth(chart['title'], "Helvetica", 24)
text_height = 24 * 1... |
from typing import Optional, Tuple, Dict
from dataset_tools import QuestionCase
from filenames import SlotFillingFiles
from neural_sparql_machine.fairseq_wrapper import FairseqTranslator
from entity_linking import BaseEntityLinkingSystem
from query_generation import SparqlQueryGenerator, QueryTemplateGenerator, \
... |
class Trie:
class Node:
def __init__(self):
self.endmark = False
self.next = {}
def __init__(self):
self.root = self.Node()
def insert(self, str):
str = str.lower()
curr = self.root
for c in str:
if c not in curr.next:
... |
#!/usr/bin/env python3
"""
Created on 15 Oct 2020
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
DESCRIPTION
The disk_volume utility is used to determine whether a volume is mounted and, if so, the free and used space on
the volume. Space is given in blocks. The volume is identified by its mount point.
... |
from dataclasses import dataclass, field
from typing import Dict, Any
@dataclass
class RecconSpanExtractionArguments:
model_name: str = field(
default="mrm8488/spanbert-finetuned-squadv2",
metadata={"help": "Pretrained model to use for training"},
)
train_data_path: str = field(
de... |
from user_manager.manager.app import app as manager_app
from user_manager.oauth.app import app
app.mount('/api/v1/manager', manager_app)
def print_routes(container, prefix=''):
if hasattr(container, 'routes'):
for route in getattr(container, 'routes'):
print_routes(route, prefix + getattr(con... |
shadowed = False
def property(f):
global shadowed
shadowed = True
return f
class C(object):
@property
def meth(self):
pass
C()
___assertTrue(shadowed)
|
#!/usr/bin/python
# Get the Commonly Used Abbreviation for ML Estimators/Algorithms
classification_estimators = {
"Logistic Regression": "lr",
"K Nearest Neighbour": "knn",
"Naives Bayes": "nb",
"Decision Tree": "dt",
"SVM (Linear)": "svm",
"SVM (RBF)": "rbfsvm",
"Gaussian Process": "gpc",
... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 Miroslav Bauer, CESNET.
#
# oarepo-references is free software; you can redistribute it and/or modify
# it under the terms of the MIT License; see LICENSE file for more details.
"""Pytest configuration.
See https://pytest-invenio.readthedocs.io/ for documentation on whic... |
import json
import requests
import os
import psycopg2
import subprocess
import csv
import datetime
import utilities
import config
def main():
stocks = config.stocks
get_data_csv_name = config.get_data_csv_name
db_csv_name = config.db_csv_name
subprocess.call( ["rm", get_data_csv_name] )
subproces... |
import pytest
from xdl.errors import (
XDLUndeclaredAlwaysWriteError,
XDLUndeclaredDefaultPropError,
XDLUndeclaredPropLimitError,
XDLUndeclaredInternalPropError
)
from xdl.steps import AbstractStep
from xdl.utils.prop_limits import ROTATION_SPEED_PROP_LIMIT
class TestUndeclaredDefaultProp(AbstractStep)... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
UL call demonstrated: TmrDevice.pulse_out_start()
Purpose: Generate an output pulse using the
specified timer
Demonstration: Outputs user defined pulse on the
... |
__author__ = "Swas.py"
__title__ = "vscode"
__license__ = "MIT"
__copyright__ = "Copyright 2021 Swas.py"
__version__ = "1.4.5"
from . import window
from .compiler import build
from .extension import Extension
from .envMethods import env
from . import _types as ext
from ._types import *
|
# Generated by Django 3.2.5 on 2021-07-27 17:15
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('movielist_app', '0002_auto_20210727_1527'),
]
operations = [
migrations.AddField(
model_name='w... |
from flask_restful import Resource, current_app, request
from schematics.exceptions import DataError
from server.models.postgis.task import Task
from server.models.postgis.task_annotation import TaskAnnotation
from server.services.project_service import ProjectService, NotFound
from server.services.task_annotations_ser... |
from enum import Enum
from typing import Literal as _Literal, Sequence
from .lexeme import Lexeme
__all__ = ["Token"]
# backwards / forwards paradox again...
# TODO: improve on this
Type = type
Object = object # TODO: make this precise
def construct(name, bases: Sequence[Type]):
...
def create(name, bases:... |
#!/usr/bin/env python3
"""
Computes embeddings on a set of tasks
"""
import json
import os
import shutil
import time
from pathlib import Path
import click
import tensorflow as tf
import torch
from slugify import slugify
from tqdm import tqdm
import heareval.gpu_max_mem as gpu_max_mem
from heareval.embeddings.task_em... |
"""XPO logistics LTL rate quote response Datatype definition module."""
import attr
from typing import List, Union, Optional
from jstruct import JList, JStruct
@attr.s(auto_attribs=True)
class rateQuote:
confirmationNbr
shipmentInfo
accessorialTariffName
actlDiscountPct
amcAmt
aMCInd
comm... |
"""
usage: $ deephyper-analytics plot csv -p results.csv --xy elapsed_sec objective
"""
import sys
import matplotlib.pyplot as plt
import pandas as pd
def add_subparser(subparsers):
subparser_name = "plot"
function_to_call = main
parser = subparsers.add_parser(
subparser_name, help="Tool to gen... |
"""
Exceptions and warnings
"""
class ArimWarning(UserWarning):
pass
class InvalidDimension(ValueError):
"""
Raised when an array has an invalid dimension.
"""
@classmethod
def message_auto(cls, array_name, expected_dimension, current_dimension=None):
current = (
" (curr... |
import unittest
import sys
import os
sys.path.insert(0,"../src/")
import SVN
import shutil
class TestSVNbackend(unittest.TestCase):
def setUp(self):
self.workerc=4
self.workdir="testdir/workdir"
self.repodir="testdir/repo"
self.text="""
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut metus massa,
... |
# blog/admin.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import xadmin
from xadmin.layout import Fieldset, Row
# from django.contrib import admin
from django.utils.html import format_html
from django.urls import reverse
from .models import Category, Tag, Post
# from typeidea.custom_site import ... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from scrapy.item import Item, Field
class Home(scrapy.Item):
location = Field()
rent_price = Field()
available_at = Field()
allows_pets ... |
import unittest
from solution.linked_list import LinkedList
from solution.linked_list_helpers import LinkedListHelpers
class TestCasesLinkedListHelpers(unittest.TestCase):
def execute_tests_both_linked_lists_none(self: object) -> None:
# Arrange
linked_list_helpers: LinkedListHelpers = LinkedListH... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .utils import get_block, get_norm
from .unet_utils import inconv, down_block, up_block
from .dual_attention_utils import DAHead
class DAUNet(nn.Module):
def __init__(self, in_ch, num_classes, base_ch=32, block='BasicBlock', pool=True):
... |
def multiprocess_state_generator(video_frame_generator, stream_sha256):
"""Returns a packaged dict object for use in frame_process"""
for frame in video_frame_generator:
yield {'mode': 'video', 'main_sequence': True} |
from unittest import TestCase
from anybadge import Badge, parse_args, main
class TestAnybadge(TestCase):
"""Test case class for anybadge package."""
def test_badge_equal_label_value_width(self):
"""Test that label and value widths are equal when text is the same."""
badge = Badge(label='a', v... |
import re
import json
import socket
import asyncio
import logging
from time import time
import websockets
from .util import Queue, get as default_get, current_task
from .error import (
SocketIOError, ConnectionFailed,
ConnectionClosed, PingTimeout
)
from .proxy import ProxyError
class SocketIOResponse:
... |
import os
from dotenv import load_dotenv
if os.path.isfile('./.env'):
load_dotenv()
JWT_SECRET = os.getenv('JWT_SECRET', 'pass')
PORT = os.getenv('PORT', '8000')
DEBUG = os.getenv('MODE', 'production') == 'development'
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-03-29 05:03
from __future__ import unicode_literals
from django.db import migrations
import tagging.fields
class Migration(migrations.Migration):
dependencies = [
('blog', '0006_auto_20180328_2107'),
]
operations = [
migration... |
from __future__ import print_function
from .logger import logger
from .kinto2yaml import introspect_server
async def initialize_server(async_client, config, bucket=None, collection=None,
force=False, delete_missing_records=False):
logger.debug("Converting YAML config into a server batc... |
dict = dict()
lista = list()
dict['nome'] = str(input('Nome do jogador: ')).capitalize()
partidas = int(input(f'Quantas partidas {dict["nome"]} jogou? '))
for c in range(0, partidas):
lista.append(int(input(f' Quantos gols na {c}° partida? ')))
dict['gols'] = lista[:]
dict['total'] = sum(lista)
print('-='*30)
pr... |
#source: https://medium.com/@joel.barmettler/how-to-upload-your-python-package-to-pypi-65edc5fe9c56
#README.md: https://dillinger.io/
from distutils.core import setup
setup(
name = 'ChoateStudentHelp', # How you named your package folder (MyLib)
packages = ['ChoateStudentHelp'], # Chose the same ... |
import unittest
from translator import english_to_french, french_to_english
class Testetof1(unittest.TestCase):
def test1(self):
self.assertEqual(english_to_french("Hello"),"Bonjour")
class Testetof2(unittest.TestCase):
def test1(self):
self.assertEqual(english_to_french(" ")," ")
class Test... |
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2020 FABRIC Testbed
#
# 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 ... |
#!/usr/bin/env python
import curses
import os
from box import Box
from utils import load_yaml
def main(screen):
"""
Draws and redraws the screen.
"""
# Hide the cursor.
curses.curs_set(0)
# Load config from file.
config = load_yaml(os.path.expanduser('~/.suave/config.yml'))
# Creat... |
# -*- coding: utf-8 -*-
"""
filtering exceptions module.
"""
from pyrin.core.exceptions import CoreException, CoreBusinessException
class FilteringException(CoreException):
"""
filtering exception.
"""
pass
class FilteringBusinessException(CoreBusinessException, FilteringException):
"""
fil... |
import timeit
from itertools import product
import pickle
import os
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
from sphere.distribution import fb8, FB8Distribution, fb8_mle, spa
plt.style.use('paper.mplstyle')
def grid(npts):
return ... |
import os, re, sys
import subprocess as sp
import random, string
import numpy as np
from .utils import *
from .pfunc import pfunc
DEBUG=False
# load package locations from yaml file, watch! global dict
package_locs = load_package_locations()
def bpps(sequence, package='vienna', constraint=None, pseudo=False,
... |
"""
Module: 'mlx90640' on M5 FlowUI v1.4.0-beta
"""
# MCU: (sysname='esp32', nodename='esp32', release='1.11.0', version='v1.11-284-g5d8e1c867 on 2019-08-30', machine='ESP32 module with ESP32')
# Stubber: 1.3.1 - updated
from typing import Any
def deinit():
pass
def getCenterTmp():
pass
def getMaxTmp():
... |
# Generated by Django 3.2.12 on 2022-03-21 17:33
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='MLAlgorithm',
fields=[
... |
import os
files = os.listdir('.')
best_files = []
for f in files:
if 'best.' in f and 'py' not in f:
best_files.append(f)
best_data = []
for f in best_files:
with open(f) as ff:
best_data.append(ff.readlines())
best_dict = {}
for b in best_data:
#print(b)
b = b[0]
tab_split =... |
""""
Samuro Bot
Автор: *fennr*
github: https://github.com/fennr/Samuro-HotsBot
Бот для сообществ по игре Heroes of the Storm
"""
import os
import discord
from discord import Embed
from discord.ext import commands
from utils.library import files
from utils.classes.Const import config
from utils import library
guild... |
import torch
import torch.nn as nn
import torch.nn.functional as nnf
class SpatialTransformer(nn.Module):
"""
N-D Spatial Transformer
"""
def __init__(self, size, mode='bilinear'):
super().__init__()
self.mode = mode
# create sampling grid
vectors = [torch.arange(0, ... |
import inspect
from flask.ext.admin.form import BaseForm
def converts(*args):
def _inner(func):
func._converter_for = frozenset(args)
return func
return _inner
class InlineFormAdmin(object):
"""
Settings for inline form administration.
You can use this class to customiz... |
#
# Flask
#
from . import auth_blueprint
from flask import Flask, request, url_for, redirect, Response, make_response
from flask_cors import CORS, cross_origin
#
# Configuration Object
#
from config import CONFIG as conf
#
# Python Standard Library
#
import logging
import os
from pprint import pprint
im... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.