content stringlengths 5 1.05M |
|---|
import math
import torch
import torch.nn as nn
class MultiHeadedPooling(nn.Module):
def __init__(
self,
head_count,
model_dim,
dropout=0.1,
use_bilinear=False,
use_final_linear=True,
model_dim_out=None,
use_layer_norm=False,
):
assert mo... |
import matplotlib.pyplot as plt
import numpy as np
plt.style.use("ggplot")
import pickle
import rlkit.torch.pytorch_util as ptu
import torch
from rlkit.launchers.experiments.ashvin.rfeatures.rfeatures_model import TimestepPredictionModel
model_class = TimestepPredictionModel
representation_size = 128
output_classes =... |
#!/usr/bin/python
#
# weewx driver that reads data from MQTT subscription
#
# 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 3 of the License, or any later version.
#
# This progra... |
# -*- coding: utf-8 -*-
# @program: APIAutoTest
# @description: TODO
# @Time : 2022-01-13 22:30
# @Author : Haruki
# @File : setting_path.py
# @Version:1.0
import os
from common.handle_config import HandleConfigIni
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
read_config = HandleConfigIni()
config = os.pat... |
import pybrid
import os
class MacejkovicReport(pybrid.PybridReport):
AUTHOR = 'martaschimmel'
NAME = 'macejkovicreport'
GROUPS = ['hamill', 'hills']
def write(self, output_dir):
f = file(os.path.join(output_dir, 'index.html'), 'w')
f.write("numquam id tenetur")
f.close()
|
# ----------------------------------------------------------------------
# Liftbridge client tests
# ----------------------------------------------------------------------
# Copyright (C) 2007-2020 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# Thir... |
#!/usr/bin/python3
#coding:utf-8
from googlesearch import search
import time
from datetime import datetime
import argparse
import os
import requests
banner = '''
\033[1;96m dP""b8 \033[1;91m dP"Yb \033[1;93m dP"Yb \033[1;96m dP""b8 \033[1;92m88 \033[1;91m888888\033[00m
\033[1;96mdP ... |
class SingletonMetaclass(type):
def __call__(cls, *args):
try:
return cls._instance
except AttributeError:
cls._instance = type.__call__(cls, *args)
return cls._instance
class SingletonType(metaclass=SingletonMetaclass):
def __eq__(self, other):
re... |
from itertools import combinations as com
from random import random
z = [2,3,5,7,11]
def carp(A):
k=1
if len(A)<0:
return 0
for i in A:
k*=i
return k
def create():
ke=[]
for i in com(z,3):
carp(i)
ke.append(str(carp(i))+"989"+"989".join([str(int(random()*100)) for i in range(3)]))
r... |
"""405. Convert a Number to Hexadecimal"""
class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
##############
d = {10:'a', 11:'b', 12:'c', 13:'d', 14:'e', 15:'f'}
if num == 0:
return '0'
if num < 0:
... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 载入数据
mnist = input_data.read_data_sets("MNIST",one_hot=True)
#每个批次的大小
batch_size = 100
#一共有多少个批次
batch_count = mnist.train.num_examples // batch_size
#定义两个Placeholder
x = tf.placeholder(tf... |
from __future__ import absolute_import
import django
from django.db.models import ForeignKey
try:
from south.modelsinspector import add_introspection_rules
except ImportError:
pass
else:
add_introspection_rules([], [
"^cobra\.models\.fields\.foreignkey\.FlexibleForeignKey",
])
__all__ = ('Fle... |
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
#! /usr/bin/env python3
"""RFC 3548: Base16, Base32, Base64 Data Encodings"""
# Modified 04-Oct-1995 by Jack Jansen to use binascii module
# Modified 30-Dec-2003 by Barry Warsaw to add full RFC 3548 support
# Modified 22-May-2007 by Guido van Rossum to use bytes everywhere
import re
import struct
import binascii
_... |
import json
import boto3
from botocore.exceptions import ClientError
def handle(event, context):
print('handle---', event)
if 'TrainSageMaker' in event and 'TrainingJobName' in event['TrainSageMaker']:
client = boto3.client('sagemaker')
training_job_name = event['TrainSageMaker']['TrainingJo... |
from .managers import MyModelManager
class MyModel(models.Model):
pass |
from django.urls import path
from django.views.generic import TemplateView
from .views import resource, availability, capabilities, authority, web
app_name = 'registry'
urlpatterns = [
path('', TemplateView.as_view(template_name='registry/root.html'), name='root'),
path('resource', resource, name='resource'... |
# 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 a... |
from Port import *
class Function:
def __init__(self, inputs, outputs, handlerFunc, name='UnnamedFunction'):
self.inputs = [Port(self, True, 0, objType) for objType in inputs]
self.outputs = [Port(self, False, 0, objType) for objType in outputs]
self.handler = handlerFunc
self.inputGroups = [[]] * le... |
#!/usr/bin/env python3
import os
import unittest
from unittest import mock
from quibble import cmd
from quibble.cmd import MultipleChoices
import quibble.commands
class MultipleChoicesTest(unittest.TestCase):
def test_init(self):
# It is really just like a list
self.assertEquals([], MultipleCho... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import inspect
import twodlearn as tdl
try:
import tensorflow_probability as tfp
TFP_AVAILABLE = True
except ImportError:
TFP_AVAILABLE = False
_KL_DIVERGENCES = {}
class KLDivergence(tdl.core.Td... |
import math
from typing import List, Optional, Tuple
import numpy as np
def leggauss_2d(order: int) -> Optional[Tuple[np.ndarray, np.ndarray]]:
"""Generate Gauss-Legendre points and weights of the given order on the reference square [-1,1].
"""
if math.floor(math.sqrt(order))**2 != order:
print('... |
import luigi
from luigi.contrib.postgres import CopyToTable
from nyc_ccci_etl.commons.configuration import get_database_connection_parameters
from nyc_ccci_etl.etl.centers_updater import CentersUpdater
from .load_clean_inspections_metadata import LoadCleanInspectionsMetadata
from .feature_engineering_validation_metada... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (c) 2016, René Moser <mail@renemoser.net>
#
# This file is part of Ansible
#
# Ansible 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 Lice... |
from typing import List, Optional
def get_project_name_from_airflow_tags(tags):
# type: (Optional[List[str]]) -> Optional[str]
if not tags:
return None
project_tag_prefix = "project:"
for tag in sorted(tags):
if tag.startswith(project_tag_prefix):
return tag.replace(projec... |
import unittest
from .helpers import StubBoard, StubPiece, C, WHITE, BLACK
class TestPawnGenerate(unittest.TestCase):
def get_pawn(self, board, team, position):
from chess.models import Pawn
return Pawn(board, team, position)
def compare_list(self, expected, results):
compared = []
... |
from datetime import date, datetime
from decimal import Decimal
from unittest import mock
from django.test import TestCase
from freezegun import freeze_time
from dominio.documentos.dao import (
ComunicacaoCSMPDAO,
DadosAssuntoDAO,
DadosPromotorDAO,
InstauracaoICDAO,
ListaROsAusentesDAO,
Minuta... |
# -*- coding: utf-8 -*-
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTI... |
"""
Snake game written in Python3 using curses on linux
By Archisman Dey
"""
import curses as cp
import random
import time
import sys
#should be at least 10 and 30 to be playable
height = 20
length = 56
class Snake(object) :
"""Defines body, direction, alive, expand of a snake"""
def __init__(self):
mid_x = len... |
"""Contains the admin site"""
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin, GroupAdmin
from django.contrib.auth.models import User, Group, Permission
from django.utils.translation import ugettext_lazy, ugettext as _
class StaffAdminSite(admin.sites.AdminSite):
"""The admin site ... |
from web3.middleware import geth_poa_middleware
from utils.contracts.contractsDatas import datas
def getContract(w3, name):
w3.middleware_onion.inject(geth_poa_middleware, layer=0)
addr = w3.toChecksumAddress(datas[name]["address"])
return w3.eth.contract(address=addr, abi=datas[name]["abi"])
|
from django.db import models
# Create your models here.
class User(models.Model):
username = models.CharField(max_length=20)
age = models.IntegerField()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__name__="Antonio"
__version__="0.0.1"
#for tests only
#~ path_db =
from sql2json import SQLConverter
def load_sqldb(path_db=None, id_db=None):
'''From crawtext to Antonio: Load db from path_db and id'''
#full_db_path = os.path.join(path_db, id_db)
db = SQLConverter... |
# Leetcode 208. Implement Trie (Prefix Tree)
#
# Link: https://leetcode.com/problems/implement-trie-prefix-tree/
# Difficulty: Medium
# Solution using a dictionary
# Complexity:
# O(N) time | where N represent the average length of the keys in the trie
# O(N*M) space | where N and M represent the average length of... |
from lib.ml import extract_features_for_one
class TestFeaturesModule:
def test_extract_features_for_one(self):
lexicon = [
'beautiful', # 0
'brown', # 1
'cat', # 2
'dog', # 3
'elephant', # 4
'flew', ... |
import re
pattern = re.compile(r'^([0-9]+)-([0-9]+) ([a-z]): ([a-z]+)$')
def solve(input):
valid = 0
for i in input:
match = pattern.match(i)
min_char = int(match.group(1))
max_char = int(match.group(2))
char = match.group(3)
password = match.group(4)
n = 0
for c in password:
if... |
import argparse
from threading import Event, Thread, Semaphore, Lock
DEBUG = True # 是否输出调试信息
class Bank:
"""表示银行服务的类"""
def __init__(self):
self.time = 0
self.queue = [] # 顾客的等待队列及其锁
self.mutex_queue = Lock()
self.customers = []
self.tellers = []
self.total_s... |
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
# @email : spirit_az@foxmail.com
__author__ = 'ChenLiang.Miao'
# +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ #
import time
import psutil
import pathlib
import sys
from source.gui_import import *
import... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 02 19:29:01 2016
Benchmarking of Forest Type Prediction Dataset on UCI Repository
@author: Rupak Chakraborty
"""
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble... |
#algoritmo de ordenação que utilizada a técnica dividir para consquistar.
#quebra o problema em pequenos problemas.
#escolher um pivo e coloca os menos a esquerda e os maiores a direita
#execute o quicksort recursivamente nos subarrays da esquerda(menores) e direita(maiores)
def quicksort(array):
#caso base
if... |
# code-checked
# server-checked
import torch.nn as nn
from torch.nn import functional as F
import torch
import os
import sys
import numpy as np
from torch.autograd import Variable
import functools
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
from resnet_block import co... |
import argparse
import itertools
import json
import random
from collections import defaultdict
from pathlib import Path
import numpy as np
from multiprocessing import Pool
from natsort import natsorted
from PIL import Image
from script_utils.common import common_setup
from tqdm import tqdm
from tao.utils import fs
fr... |
from troposphere import Ref, Equals, Parameter
def init(t, r):
r['envtype'] = t.add_parameter(Parameter(
"EnvironmentType",
Description='Environment Type',
Type='String',
AllowedValues=['stage', 'prod'],
Default='stage',
ConstraintDescription='Must specify stage or ... |
from flask import (Flask,
render_template,
request,
url_for,
redirect,
flash,
jsonify)
# database
from database_orm import session, desc, exc
from database_setup import Category, Item, User
# login sessio... |
"""
Given a binary matrix A, we want to flip the image horizontally,
then invert it, and return the resulting image.
To flip an image horizontally means that each row of the image is reversed.
For example, flipping [1, 1, 0] horizontally results in [0, 1, 1].
To invert an image means that each 0 is replaced by 1, and... |
# ------------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2014-2021 Digital Sapphire
#
# 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 ... |
import sqlite3
import logging
from datetime import datetime, timedelta, date
logger = logging.getLogger()
db_file = 'db.sqlite'
class ManageTodoDB:
def connect_db(self):
try:
db = sqlite3.connect(db_file)
db.execute("PRAGMA foreign_keys = 1")
logger.info("Connected t... |
from django.shortcuts import get_object_or_404
from django.views.generic import TemplateView
from ..comments.models import Comment
from ..professors.models import Professor
from ..universities.models import University
from .models import Department
class DepartmentView(TemplateView):
template_name = "department.... |
from __future__ import division, unicode_literals
import os
import unittest
import numpy as np
import six
import vtk
from traits_enaml.testing.enaml_test_assistant import EnamlTestAssistant
from tvtk.api import tvtk
from ensemble.volren.volume_axes import VolumeAxes
from ensemble.volren.volume_bounding_box import V... |
# Puzzle Input ----------
with open('Day01-Input.txt', 'r') as file:
puzzle = list(map(int, file.read().split('\n')))
with open('Day01-Test01.txt', 'r') as file:
test01 = list(map(int, file.read().split('\n')))
# Main Code ----------
# Sums three measurements and compare one sum with the next
def average_de... |
import os
import glob
import psycopg2
import pandas as pd
import json
from scripts.templating import choose_template
from table_creation.create_tables import generate_uri
from table_creation.sql_queries import song_select, songplay_table_insert
def get_files(filepath, extension="*.json"):
"""
- read all the fi... |
# noinspection PyUnresolvedReferences
from PyQt5 import QtCore, QtWidgets
class GameOverUi(object):
def __init__(self, game_over_message):
self.__verticalLayout = None
self.__label = None
self.__buttonBox = None
self.__gameOverMessage = game_over_message
def setup_ui(self, ga... |
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional
__NAMESPACE__ = "NISTSchema-SV-IV-list-language-enumeration-3-NS"
class NistschemaSvIvListLanguageEnumeration3Type(Enum):
SK_SL_SM_SN_SO_SQ_SR_SS_ST = (
"SK",
"SL",
"SM",
"SN... |
#! /usr/bin/env python
import os
import wpipe as wp
def register(task):
_temp = task.mask(source='*', name='start', value=task.name)
_temp = task.mask(source='*', name='__init__', value='*')
if __name__ == '__main__':
my_pipe = wp.Pipeline()
my_job = wp.Job()
my_job.logprint("Preparing targets")... |
############################################################################
#
# Program: GDCM (Grassroots DICOM). A DICOM library
#
# Copyright (c) 2006-2011 Mathieu Malaterre
# All rights reserved.
# See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details.
#
# This software is distributed ... |
# -*- coding: utf-8 -*-
###############################################################################
#
# GetList
# Returns a list of legislators that meet a specified search criteria.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License")... |
import math
import sys
import code as nbc
import unittest
def check_imports(source_name):
imports = []
with open('student_code.py',"r") as f:
tokens = f.read().replace("\n", " ").split()
for i in range(len(tokens)-1):
if tokens[i] == 'import':
imports.append(tokens[i+1])
... |
from seviceLayer.Managers.AuthorizationManager import AuthorizationManager
from repository.SaveUserRepository import SaveUserRepository
from Domain.models.SaveUserDomainModel import SaveUserDomainModel
from flask import Request
class SaveUserService:
repository: SaveUserRepository
auth: AuthorizationManager
... |
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="sqlrecorder",
version="1.0",
author="Paul Wilson",
author_email="pauldewilson@gmail.com",
description="Python Wrapper for use in recording the success or failure of any f... |
repeat = int(input())
for x in range(repeat):
x, y = input().split()
x, y = x[::-1], y[::-1]
z = int(x) + int(y)
print(int(str(z)[::-1]))
|
listB = []
listN = []
def calc(B, listA):
listA.sort()
c = 0
for ch in listA:
if ch <= B:
B -= ch
c += 1
return c
T = int(input())
for k in range(T):
B = int(input())
listB.append(B)
N = int(input())
listN.append(N)
listA = []
for i in range(N):... |
import cv2
import random
import numpy as np
import os
from keras.preprocessing.image import img_to_array
from deeplabv3 import Deeplabv3plus
from tqdm import tqdm
image_size = 512
bs=12
def predict():
# load the trained convolutional neural network
print("[INFO] loading network...")
model = Dee... |
import requests
from collections import defaultdict
import time
baseurl = "https://discordapp.com/api/v6"
auth_token = ''
delay = 0.250
def api_request(path):
headers = {
'User-Agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) discord/0.0.306 Chrome/78.0.3904.130 Electro... |
import pydantic
from modelkit.core.model import Model
class SomeSimpleValidatedModelB(Model[str, str]):
"""
This is a summary
that also has plenty more text
"""
CONFIGURATIONS = {"some_model_b": {}}
def _predict(self, item):
return item
class ItemModel(pydantic.BaseModel):
st... |
from models.networks.PyramidTreeNet import PyramidTreeNet
def get_net_by_name(name):
if name == PyramidTreeNet.__name__:
return PyramidTreeNet
else:
raise ValueError('unrecognized type of network: %s' % name)
|
import os
import ruamel_yaml
from ruamel_yaml.comments import CommentedSeq, CommentedMap
from ruamel_yaml.scanner import ScannerError
assert ruamel_yaml.load('''\
A: 1
B:
- Cef
- def
''') == {'A': 1, 'B': ['Cef', 'def']}
print('ruamel_yaml.__version__: %s' % ruamel_yaml.__version__)
assert ruamel_yaml.__version__... |
from .filedialogsubmission import handle_file_dialog_submission
from .filelisting import handle_file_creation
from .fileselect import handle_file_select_action
from .help import handle_generic_help
from .projectdialogsubmission import handle_project_dialog_submission
from .projectlisting import handle_project_creation
... |
# Generated by Django 2.1.3 on 2018-12-01 07:30
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='MLModel',
fields=[
('id', models.AutoField(... |
#Manipulacao de dados
import numpy as np
import pandas as pd
##Validacao
from sklearn.metrics import f1_score
#classificador
from sklearn.naive_bayes import MultinomialNB
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.neural_network import MLPClassifier
from sklearn.met... |
"""Print Utilities.
Module provides methods to display messages with timestamps,
message type tagss, and dividers.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import time
# try:
# import arcpy
# except ImportError:
# arcpy = Non... |
# komle/bindings/v1411/read/_xlink.py
# -*- coding: utf-8 -*-
# PyXB bindings for NM:b43cd366527ddb6a0e58594876e07421e0148f30
# Generated 2020-05-05 12:27:35.394977 by PyXB version 1.2.6 using Python 3.8.2.final.0
# Namespace http://www.w3.org/1999/xlink [xmlns:xlink]
from __future__ import unicode_literals
import io... |
import gym
import numpy as np
import matplotlib.pyplot as plt
from deep_Q_cart import Agent
class CartPoleDigitizer:
def __init__(self, bounds=(2.4, 4, 0.209, 4), n_bins=10):
self.position_space = np.linspace(-1*bounds[0], bounds[0], n_bins)
self.velocity_space = np.linspace(-1*bounds[1], b... |
# Elliot Eriksson
# Teinf 20
# 2022-04-04
# Main for Train Calculator
from time import sleep
from resources import Train, create_line, create_train, get_lines, get_trains, pro_bar
from math import sqrt
from rich.console import Console
from rich.style import Style
console = Console()
count_line = -1
count_train = -1
... |
#Open file
file = open('inputs\input4.txt')
data = file.read().split('\n\n')
file.close()
#Clean input
dataClean = []
for x in data:
dataClean.append(x.split()) #Split with no argument splits on whitespace
#Define functions
import re
def validatePassport(passport,reqFields,rules=None):
passportFields = [i... |
import pyrealtime as prt
class CounterLayer(prt.InputLayer):
def __init__(self, target, *args, **kwargs):
self.target = target
super().__init__(*args, **kwargs)
def generate(self, counter):
if counter == self.target:
# can trigger a shutdown by returning stop signal or cal... |
import re
from django.conf import settings
from nose.tools import eq_
from pyquery import PyQuery as pq
import kitsune.sumo.tests.test_parser
from kitsune.gallery.models import Video
from kitsune.gallery.tests import image, video
from kitsune.sumo.tests import TestCase
from kitsune.wiki.models import Document
from k... |
# stdlib
from typing import Any
from typing import List
from typing import Optional
# third party
from google.protobuf.reflection import GeneratedProtocolMessageType
# syft relative
from ...core.common import UID
from ...core.store.storeable_object import StorableObject
from ...util import aggressive_set_attr
# thi... |
#
# Example file for variables
#
# Basic data types in Python: Numbers, Strings, Booleans, Sequences, Dictionaries
myint = 5
myfloat = 13.2
mystr = "This is a string"
mybool = True
mylist = [0, 1, "two", 3.2, False]
mytuple = (0, 1, 2)
mydict = {"one" : 1, "two" : 2}
print(myint)
print(myfloat)
print(mystr)
print(myb... |
from Transport import Transport
from base64 import b64encode
from json import dumps, loads
from log import *
from sha256 import *
from threading import Thread
from time import sleep, time
from urlparse import urlsplit
from util import *
import httplib
import traceback
class NotAuthorized(Exception): pass... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
import db_sql
import db_ldap
def init_dummies():
try:
users = db_ldap.PosixGroup('users', 100)
sql_admin = db_ldap.PosixGroup('sql_admin', 2000)
sql_writer = db_ldap.PosixGroup('sql_write', 2001)
sql_readonly = db_ldap.PosixGroup('sql_readonly', 2002)
user0 = ... |
# Copyright (C) 2021 ServiceNow, Inc.
""" Compile results from bert keyword evaluation
This script compiles the MULTICLASS and PAIRING evaluation output
files in the input_dir into the two files specified by
OUTPUT_KERAS_RUN_LOG and OUTPUT_KERAS_EVAL_METRICS which are
used by the evaluation notebook... |
class Player:
"""
Player object.
"""
def __init__(self, name: str, id: str):
self.name = name
self.id = id
|
from enum import Enum
class Version(Enum):
V1 = "v1"
DEFAULT = V1
|
class SpeechUnit:
"""Storage of important attributes of speech unit for correct integration into speech synthesis."""
def __init__(self, signal, enrg_start, enrg_stop, f0_start, f0_stop, mfcc_start, mfcc_stop):
self.signal = signal
# Target loss params
self.left_phoneme = None
... |
# -*- coding:utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the ... |
"""Glue for the "yapf" library.
"""
import os
import sys
from elpy.rpc import Fault
YAPF_NOT_SUPPORTED = sys.version_info < (2, 7) or (
sys.version_info >= (3, 0) and sys.version_info <= (3, 3))
try:
if YAPF_NOT_SUPPORTED:
yapf_api = None
else:
from yapf.yapflib import yapf_api
f... |
import frappe
from erpnext.regional.india import states
def execute():
company = frappe.get_all('Company', filters = {'country': 'India'})
if not company:
return
# Update options in gst_state custom field
gst_state = frappe.get_doc('Custom Field', 'Address-gst_state')
gst_state.options = '\n'.join(states)
gs... |
# Copyright 2010 New Relic, 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... |
# (C) Copyright 2010-2020 Enthought, Inc., Austin, TX
# All rights reserved.
import math
import numpy as np
from abc import abstractmethod
from force_bdss.api import (
RangedVectorMCOParameter,
ListedMCOParameter,
KPISpecification
)
class BaseObjective:
""" An objective function for the unit-testi... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import tensorflow.contrib.slim as slim
import tfplot
from ops import conv2d, fc, selu, lrelu
from util import log
import numpy as np
class Model(object):
def __init__(self, conf... |
import exceRNApipeline.tasks.task_extract_fastx as task
from unittest import TestCase
import os
import shutil
import sys
_FILE_PATH = os.path.dirname(__file__)
_DATA_DIR = os.path.join(_FILE_PATH, 'data')
_TEMP_DIR = os.path.join(_FILE_PATH, '_test_temp')
_BASE_ARGS = [
'',
'-i', os.path.join(_DATA_DIR, 'tes... |
PRIV_KEY = ''
RPC_URL = 'wss://mainnet.infura.io/ws/v3/<PROJECT_ID>'
|
import celery
from dateutil.rrule import (
rrule as dateutil_rrule,
YEARLY,
MONTHLY,
WEEKLY,
DAILY,
HOURLY,
MINUTELY,
SECONDLY,
)
from celery.schedules import BaseSchedule as schedule
class rrule(schedule):
RRULE_REPR = (
'<rrule: freq: {0.freq}, dtstart: {0.dtstart}, inter... |
import os
from pymongo import MongoClient
from src.aws_services.aws_secrets_manager import AwsSecretsManager
from .config import Config
# Get MongoURI from AWS credentials
aws_secrets_manager = AwsSecretsManager()
secrets = aws_secrets_manager.get_secret(os.environ['APP_CONFIG'])
config = Config(secrets)
# Connect to... |
# coding=utf-8
# Copyright 2017 Foursquare Labs Inc. All Rights Reserved.
from __future__ import absolute_import, division, print_function, unicode_literals
import os
from pants.base.build_environment import get_buildroot
from pants.base.exceptions import TaskError
from pants.build_graph.address import Address
from ... |
# https://www.codewars.com/kata/5d50e3914861a500121e1958/train/python
'''
Instructions :
Your task is to add up letters to one letter.
The function will be given a variable amount of arguments, each one being a letter to add.
Notes:
Letters will always be lowercase.
Letters can overflow (see second to last example ... |
"""
MMTO F/5 WFS camera interface
"""
import os
import time
import pkg_resources
import asyncio
import tornado
import tornado.web
import tornado.httpserver
import tornado.ioloop
import tornado.websocket
from tornado.log import enable_pretty_logging
from scipy.ndimage import median_filter
from .header import update_hea... |
import numpy as np
import pandas as pd
def calc_trading_value(prices, volumes) -> np.ndarray:
if not isinstance(prices, np.ndarray):
prices = np.array(prices)
if not isinstance(volumes, np.ndarray):
volumes = np.array(volumes)
return prices * volumes
def calc_total_return(prices):
r... |
import csv
import os
import stormberry.plugin
class CSVWriter(stormberry.plugin.IRepositoryPlugin):
def prepare(self, config, data_manager):
self.config = config
def store_reading(self, data):
behaviour = self.config['CSV']['BEHAVIOUR']
filename = self.config['CSV']['FILENAME']
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.