text stringlengths 1 927k |
|---|
#!/usr/bin/env python3
#****************************************************************************************************************************************************
#* BSD 3-Clause License
#*
#* Copyright (c) 2015, Mana Battery
#* All rights reserved.
#*
#* Redistribution and use in source and binary forms, wit... |
import os
import librosa
import numpy as np
import torch.utils.data
def random_crop(y, max_length=176400):
"""音声波形を固定長にそろえる
max_lengthより長かったらランダムに切り取る
max_lengthより短かったらランダムにパディングする
"""
if len(y) > max_length:
max_offset = len(y) - max_length
offset = np.random.randint(max_offset)
... |
""":mod:`flask_aiohttp` --- Asynchronous Flask with aiohttp
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides Flask extension for asynchronous I/O.
With this extension, we can use `asyncio.coroutine` as Flask's view function.
So, we can add
asyncio-redis <https://github.com/jonathanslenders/asynci... |
###
# Copyright 2016 Hewlett Packard Enterprise, 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 ... |
"""Reportlab Helpers"""
__docformat__ = "numpy"
from datetime import datetime
from typing import List
from reportlab.lib import colors
from reportlab.pdfgen import canvas
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
from reportlab.platypus import Paragraph, Table, TableStyle
def base_format(... |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... |
# -*- coding: utf-8 -*-
"""
tests.fixers
~~~~~~~~~~~~
Server / Browser fixers.
:copyright: (c) 2014 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import pytest
from werkzeug.contrib import fixers
from werkzeug.datastructures import ResponseCacheControl
from werkzeug.http imp... |
# -*- coding: utf-8 -*-
from ExtractDomainAndFQDNFromUrlAndEmail import extract_fqdn_or_domain
import pytest
@pytest.mark.parametrize('input,fqdn,domain', [ # noqa: E501 disable-secrets-detection
('http://this.is.test.com', 'this.is.test.com', 'test.com'),
('https://ca... |
# Study Drills 19
# 1. Go back through the script and type a comment above each line explaining in English what it does.
# 2. Start at the bottom and read each line backward, saying all the important characters.
# 3. Write at least one more function of your own design, and run it 10 different ways.
# Define a functio... |
import math
class emadiff:
def twe_hund_ema_diff(twema, hundema):
return abs(twema - hundema)
def wrapper_Least_ema_diff(stocks, twemas, hundemas):
Stocks_short_list = []
threshold = 0.25
stock_list_size = len(stocks)
if stock_list_size == len(twemas) and stock_list_siz... |
#!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
Votes according to components stability (crashes vs time)
:author: Thomas Calmant
:license: Apache Software License 2.0
:version: 3.0.0
..
Copyright 2014 isandlaTech
Licensed under the Apache License, Version 2.0 (the "License");
you may not use ... |
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import datetime
import inspect
import unittest
from random import choice
from unittest.mock import patch
import frappe
from frappe.custom.doctype.custom_field.custom_field import create_custom_field
from frappe.database i... |
####
# This script demonstrates how to use the Tableau Server Client
# to query extract refresh tasks and run them as needed.
#
# To run the script, you must have installed Python 3.5 or later.
####
import argparse
import getpass
import logging
import tableauserverclient as TSC
def handle_run(server, args):
tas... |
# *****************************************************************************
# Copyright (c) 2020, Intel Corporation All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of sou... |
"""Cookiecutter loader."""
import json
from collections.abc import Iterator
from typing import Any
from cutty.filesystems.domain.path import Path
from cutty.templates.domain.config import Config
from cutty.templates.domain.variables import Variable
def loadvalue(value: Any) -> Any:
"""Stringize scalars."""
i... |
import heroprotocol, sys, os, os.path, pprint
from heroprotocol.mpyq import mpyq
sys.path.append(os.path.join(os.getcwd(), "heroprotocol"))
from heroprotocol import protocol29406
archive = mpyq.MPQArchive(sys.argv[-1])
contents = archive.header['user_data_header']['content']
header = protocol29406.decode_replay_head... |
"""
Tketris
Tetris using tkinter
Author: Anshul Kharbanda
Created: 10 - 11 - 2018
"""
from .game import GameLogic
from .view.board import Board
from .view.side_menu import SideMenu
from tkinter import *
class Tketris(Frame, GameLogic):
"""
The main application frame. Includes the GameLogic mixin
"""
... |
# Copyright Amazon.com, Inc. and its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT
# Licensed under the MIT License. See the LICENSE accompanying this file
# for the specific language governing permissions and limitations under
# the License.
import json
import boto3
from urllib.parse impo... |
#!/usr/bin/env python3
from copy import deepcopy
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __truediv__(self, other):
answer = deepcopy(self)
answer.x = self.x / other
answer.y = self.y / other
return answer
def __sub__(... |
from gym.envs.registration import register
register(
id='jiminy-cartpole-v0',
entry_point='gym_jiminy.envs:JiminyCartPoleEnv',
reward_threshold=10000.0,
)
register(
id='jiminy-acrobot-v0',
entry_point='gym_jiminy.envs:JiminyAcrobotEnv',
max_episode_steps=12000,
reward_threshold=-3000.0
) |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from google.cloud.container_v1beta1.proto import (
cluster_service_pb2 as google_dot_cloud_dot_container__v1beta1_dot_proto_dot_cluster__service__pb2,
)
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
cl... |
import numpy as np
import os
import time
from sklearn import svm
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import cross_val_predict
from sklearn.pipeline import make_pipeline
from sklearn.metrics import accuracy_score
from grakel import datasets
from grakel import GraphKernel
from... |
# type: ignore[attr-defined]
"""Python package to extend sql functionality"""
try:
from importlib.metadata import PackageNotFoundError, version
except ImportError: # pragma: no cover
from importlib_metadata import PackageNotFoundError, version
try:
__version__ = version(__name__)
except PackageNotFoundE... |
"""
Example service that prints out http context.
"""
import time
import requests
from ray import serve
from ray.serve.utils import pformat_color_json
def echo(flask_request):
return "hello " + flask_request.args.get("name", "serve!")
serve.init()
serve.create_backend("echo:v1", echo)
serve.create_endpoint(... |
from datetime import datetime
from sqlalchemy import Column, Date, DateTime, Float, Integer, String
from sqlalchemy.sql.sqltypes import Boolean
from app.db.base_class import Base
class Sales(Base):
id = Column(Integer, primary_key=True)
saleprice = Column(Integer, nullable=True)
model_id = Column(Intege... |
from GameData import GameData
from RewardSystem import RewardSystem
from TrainingData import TrainingData
from Visualization import Visualization
from Field import Field
from typing import Optional
class Algorithm:
def __init__(self):
self.model = None
self.reward_system: Optional[RewardSystem] = ... |
from io import BytesIO
import PIL.Image
from django.test import TestCase
from django.core.files.images import ImageFile
from wagtail.tests.utils import WagtailTestUtils
from wagtail.images.models import Image
from wagtail_meta_preview.utils import get_focal
# Taken from wagtail.images.test.utils
def get_test_image_... |
"""
@brief test log(time=16s)
"""
import unittest
from logging import getLogger
from pandas import DataFrame
from pyquickhelper.loghelper import fLOG
from pyquickhelper.pycode import ExtTestCase
from pyquickhelper.pandashelper import df2rst
from sklearn.exceptions import ConvergenceWarning
try:
from sklearn.ut... |
if __name__ == '__main__':
string = str(input())
methods = [".isalnum()", ".isalpha()", ".isdigit()",
".islower()", ".isupper()"]
for i, method in enumerate(methods):
print(eval("any(alpha{0} for alpha in string)".format(method))) |
class Classifier(object):
"""
Base class for classifiers
"""
pass |
#!/usr/bin/env python
# Copyright 2019 Google LLC
#
# 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... |
from __future__ import print_function, division
import pytest
import attr
from scantree.test_utils import assert_dir_entry_equal
from scantree import DirEntryReplacement
class MockStat(object):
def __init__(self, st_ino=None):
self.st_ino = st_ino
class TestAssertDirEntryEqual(object):
def get_... |
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root
# for full license information.
# ==============================================================================
from .. import cntk_py
from ..device import use_default_device
from cntk.internal im... |
"""
Enumerated type for education level.
"""
from .FuzzyMatchingEnum import FuzzyMatchingEnum
class EducationLevel(FuzzyMatchingEnum):
"""
EducationLevel enumerated type with fuzzy matching.
"""
pre_primary = "Pre-Primary"
pre_básica = "Pre-Primary"
primary = "Primary"
básica = "Primary"
... |
from __future__ import unicode_literals
import frappe, os
from frappe import _
def execute():
frappe.reload_doc("email", "doctype", "email_template")
if not frappe.db.exists("Email Template", _('Leave Approval Notification')):
base_path = frappe.get_app_path("erpnext", "hr", "doctype")
response = frappe.read_fi... |
class Solution:
def XXX(self, x: int) -> int:
if x == 1:
return 1
left = 0
right = x
while right - left > 1:
mid = (left + right) // 2
a = mid ** 2
if a == x:
return mid
if a > x:
right = mid
... |
# 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... |
# Copyright (c) 2019-present, HuggingFace Inc.
# All rights reserved. This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import json
import logging
import os
import socket
import tarfile
import tempfile
from datetime import datetime
from multi... |
"""Provide a model for Z-Wave firmware."""
from enum import IntEnum
from typing import TYPE_CHECKING, Optional, TypedDict
if TYPE_CHECKING:
from .node import Node
class FirmwareUpdateStatus(IntEnum):
"""Enum with all Firmware update status values.
https://zwave-js.github.io/node-zwave-js/#/api/node?id=s... |
# Generated by Django 3.2.8 on 2021-11-02 18:01
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
"""
This file offers the methods to automatically retrieve the graph Streptomyces catenulae.
The graph is automatically retrieved from the STRING repository.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
title={STRING v11: protein--protein... |
from __future__ import print_function
import logging
import numpy
import pywt
import SimpleITK as sitk
import six
from six.moves import range
logger = logging.getLogger(__name__)
def getMask(mask, **kwargs):
"""
Function to get the correct mask. Includes enforcing a correct pixel data type (UInt32).
Also su... |
# !/usr/bin/env python3
# -*-coding:utf-8-*-
# @file: test_tf_funcs.py
# @brief:
# @author: Changjiang Cai, ccai1@stevens.edu, caicj5351@gmail.com
# @version: 0.0.1
# @creation date: 13-08-2019
# @last modified: Tue 13 Aug 2019 05:38:05 PM EDT
import tensorflow as tf
import numpy as np
if __name__ == "__main__":
... |
from multiprocessing import Pool
import os
from typing import Sequence
from typing import Tuple
import numpy as np
import pytest
import optuna
_STUDY_NAME = "_test_multiprocess"
def f(x: float, y: float) -> float:
return (x - 3) ** 2 + y
def objective(trial: optuna.Trial) -> float:
x = trial.suggest_flo... |
"""
LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them.
A subsequence is a sequence that appears in the same relative order, but not necessarily continious.
Example:"abc", "abg" are subsequences of "abcdefgh".
"""
def LCS(s1, s2):
m = len(s1)
n = len(s2)
... |
import os
import numpy as np
from paddlehub.common.logger import logger
from lda_webpage.util import rand, rand_k
class VoseAlias(object):
"""Vose's Alias Method.
"""
def __init__(self):
self.__alias = None
self.__prob = None # np.array
def initialize(self, distribution):
... |
# "Lorenz-95" (or 96) model. For a deeper introduction, see
# "DAPPER/tutorials/T4 - Dynamical systems, chaos, Lorenz.ipynb"
#
# Note: implementation is ndim-agnostic.
import numpy as np
from tools.math import rk4, integrate_TLM, is1d
Force = 8.0
# Note: the model is unstable (blows up) if there are large peaks
# (a... |
from import_reqs import *
from app import app
@app.route('/enterprise/product=<id>', methods=['GET'])
def get_advanced_analytics(id):
"""
get_advanced_analytics(id): this will be for company dashboard, they will see the advanced analytics of a product.
"""
try:
id_token = request.headers['... |
"""
WSGI config for Ahriknow project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETT... |
from datetime import time
import numpy as np
import pytest
import pytz
from pandas._libs.tslibs import timezones
from pandas import (
DataFrame,
date_range,
)
import pandas._testing as tm
class TestAtTime:
@pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"])
def test_localized_a... |
# -*- coding: utf-8 -*-
import functools
import logging
import sys
import time
import grpc
from grpc._channel import _Rendezvous
NUMBER_OF_RETRIES = 5
# Initial delay in seconds before an attempt to retry
INITIAL_DELAY = 0.3
def retry_wrapper(function, *args):
delay = INITIAL_DELAY
for i in range(NUMBER_OF_... |
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
import datetime
from decimal import Decimal
import pytest
from typepy import DateTime, RealNumber, String, Typecode
from dataproperty import (
Align,
DataPropertyExtractor,
Format,
LineBreakHandling,
MatrixFormatting,
Pre... |
# x_9_9
#
# 「prefecture.csv」を利用して都道府県番号を答える機能をチャットボットに追加してください
import csv
chatbot = {
'おはよう': 'おはようございます',
'おやすみ': 'おやすみなさい',
'今日は何日ですか': '2021年11月14日です',
'今日の天気は': '雨です',
'何か歌って': 'もーもたろさんももたろさん',
}
message = input('何か話しかけてください:')
if message == '都道府県番号を教えて':
prefecture = input('何県の都道府県番号ですか... |
"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W... |
# -*- coding: utf-8 -*-
"""
Contains the definition of the SuddenDecay class.
"""
from __future__ import unicode_literals
from __future__ import print_function
import logging
import numpy as np
from . import SampleBasedDecay
logger = logging.getLogger('decay.half_sudden')
class HalfSuddenDecay(SampleBasedDecay):
... |
from Util import Util
import numpy
import matplotlib.pyplot as pyplot
inputArray = numpy.ones(100)
theta = [ 2.705, -2.448, 0.7408, 0.0523, -0.0855, 0.035 ]
orderOutput = 3
orderInput = 3
sampleRate = 0.1
y = Util.computeOutput(inputArray, theta, orderOutput, orderInput)
t = numpy.arange(0, len(y)*sampleRate, sample... |
"""
Driver for robot Robik from cortexpilot.com
"""
import ctypes
import struct
import math
from datetime import timedelta
from osgar.node import Node
from osgar.bus import BusShutdownException
from osgar.lib import quaternion
# CPR = 9958 (ticks per revolution)
# wheel diameter D = 395 mm
# 1 Rev = 1241 mm
ENC_S... |
# A dictionary comprehension is like a list comprehension, but it constructs
# a dict instead of a list. They are convenient to quickly operate on each
# (key, value) pair of a dict. And often in one line of code, maybe two after
# checking PEP8 😉
#
# We think they are elegant, that's why we want you to know about the... |
def solution():
first = True
for tc in range(1, 1 + int( input() ) ):
if not first:
print('')
else:
input()
first = False
print('Case #%d:' %(tc))
while True:
try:
v = list( input().strip().split() )
if l... |
"""
For JSON lists.
"""
# I need to use yaml for all of this
# excuse me
from string import ascii_uppercase
import discord
STAT_NAMES = {
"speed": "SPEED",
"attack": "ATTACK",
"sp_atk": "SPECIAL ATTACK",
"sp_def": "SPECIAL DEFENSE",
"defense": "DEFENSE",
"hp": "HP",
"total": "TOTAL"
}
... |
#!/usr/bin/env python
"""
Does naive decoding of Hadamard time-encoded data
Assumes that the Hadamard blocks are in adjacent volumes in the data
and simply decodes each block, outputting the same order
"""
import sys
import argparse
from fsl.data.image import Image
import numpy as np
import scipy.linalg
class Argum... |
#!/usr/bin/env python
from __future__ import print_function, unicode_literals
import jinja2
template_vars = {"vlan_id": 400, "vlan_name": "red400"}
vlan_template = """
vlan {{ vlan_id }}
name {{ vlan_name }}
"""
template = jinja2.Template(vlan_template)
print(template.render(template_vars)) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2021 Alibaba Group Holding 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 at
#
# http://www.apache.org/licenses/LICENSE-... |
import logging
import threading
import time
import random
LOG_FORMAT = '%(asctime)s %(threadName)-17s %(levelname)-8s %(message)s'
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)
items = []
event = threading.Event()
class Pasien(threading.Thread):
def __init__(self, *args, **kwargs):
super().... |
DB_CONN_STR = 'sqlite:///event_repository.sqlite' |
from decimal import ROUND_DOWN, Decimal
from django.db import models
from lorikeet.exceptions import PaymentError
from lorikeet.models import (
Adjustment,
DeliveryAddress,
LineItem,
Payment,
PaymentMethod,
)
AUSTRALIAN_STATES = (
("NSW", "New South Wales"),
("VIC", "Victoria"),
("QLD"... |
# Q.1 Run your program for M = 1, 5, 10, 20, 50, 100, 200, 400
# to get the initial option prices and tabulate them
# Pandas : pip install pandas
# Matplotlib: pip install matplotlib
# Numpy: pip install numpy
# Ipython: pip install ipython
import math
import pandas as pd
from IPython.display import display
# F... |
import pytest
from google_auth.users.models import User
pytestmark = pytest.mark.django_db
def test_user_get_absolute_url(user: User):
assert user.get_absolute_url() == f"/users/{user.username}/" |
import csv
import os
import sqlite3
import pytest
BLOGDB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "blogdb")
USERS_DATA_PATH = os.path.join(BLOGDB_PATH, "data", "users_data.csv")
BLOGS_DATA_PATH = os.path.join(BLOGDB_PATH, "data", "blogs_data.csv")
def populate_sqlite3_db(db_path):
conn =... |
# -*- coding: utf-8 -*-
"""
logger module
============
This module contains the WamLogger class for the pygame Whack a Mole game
Attributes:
na
Todo:
* sort docstrings (e.g. class)
Related projects:
Adapted from initial toy project https://github.com/sonlexqt/whack-a-mole
which is under MIT license
... |
import os
import random
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
bot = commands.Bot(command_prefix='.')
@bot.command(name='99', help='Responds with a random quote from Brooklyn 99')
async def nine_nine(ctx):
brooklyn_99_quotes = [
'... |
# Copyright 2013 Openstack Foundation
# 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 requ... |
###***********************************###
'''
CUNYFirstAPI
File: helper.py
Core Maintainers: Ehud Adler, Akiva Sherman,
Yehuda Moskovits
Copyright: Copyright 2019, Ehud Adler
License: MIT
'''
###***********************************###
import datetime
def get_semester():
now = datetime.datetime.now()
today = (n... |
import json
from django.test import TestCase, Client
from django.contrib.auth.models import User
from binder.json import jsonloads
from .testapp.models import Animal, Zoo, ZooEmployee, ContactPerson
from .compare import assert_json, MAYBE, ANY
class MultiPutTest(TestCase):
def setUp(self):
super().setUp()
u ... |
"""
Stain normalization inspired by method of:
A. Vahadane et al., ‘Structure-Preserving Color Normalization and Sparse Stain Separation for Histological Images’, IEEE Transactions on Medical Imaging, vol. 35, no. 8, pp. 1962–1971, Aug. 2016.
Uses the spams package:
http://spams-devel.gforge.inria.fr/index.html
Use... |
# 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 appl... |
import sys
sys.path.insert(0, '../common/')
import utils
def same():
for n in range(10,100):
for d in range(n+1, 100):
nd = str(n)
dd = str(d)
if nd[0] == dd[1] and int(nd[1]) * d == n * int(dd[0]):
yield n,d
if nd[1] == dd[0] and int(nd[0]) * d == n * int(dd[1]):
yield n,d
(n,d)=reduce(lambda... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 12 19:28:12 2020
@author: zdadadaz
"""
import json
import pandas as pd
import numpy as np
import matplotlib.pylab as plt
# dir_json = './../fb_whole/metadata_21.json'
# train_list =[]
# with open(dir_json) as json_file:
# data = json.load(json... |
from scipy.spatial import Voronoi, voronoi_plot_2d
import h5py
import numpy as np
import matplotlib.pyplot as plt
import os
import sys
from shapely.geometry import Polygon, MultiLineString, Point
from shapely.ops import polygonize
from descartes import PolygonPatch
from voronoi_finite_polygons_2d import voronoi_finite... |
import numpy as np
from scipy.integrate import simps
from beluga.numeric.compilation import jit_lambdify, jit_compile_func
from beluga.symbolic.data_classes.components_structures import CostStruct
def compile_control(control_options, args, ham_func, lambdify_func=jit_lambdify):
num_options = len(control_options... |
import logging
import random
from collections import deque
from typing import List, Tuple, Iterable, cast, Dict, Deque
from overrides import overrides
from allennlp.common.checks import ConfigurationError
from allennlp.common.util import lazy_groups_of, add_noise_to_dict_values
from allennlp.data.dataset import Batch... |
"""
opennms-provisioner test source module
This module is the provides test sources for opennms-provisioner.
:license: MIT, see LICENSE for more details
:copyright: (c) 2018 by Michael Batz, see AUTHORS for more details
"""
import provisioner.source
import provisioner.opennms
class DummySource(provisioner.source.Sou... |
"""
node
"""
import socket
import random
import pickle
import time
import ast
import concurrent.futures
from ecdsa import SigningKey, VerifyingKey, SECP112r2
#recieve from nodes
def receive(local_ip):
"""
message is split into array the first value the type of message the second value is the message
"""
... |
"""List of classes in lexical and NPZ order."""
# ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
# ! PLEASE DO NOT MODIFY THIS LIST OF CLASSES !
# ! LIST MODIFICATION CAUSES GREAT F**K UP !
# ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
CLASSES = [
"A", # 0
"Ar", # 1
"B", # 2
"Ba", # 3
"C",... |
######################################################
### ULTIMA MODIFICACIÓN: 2019-06-27
######################################################
import visa, paramiko, numpy
from time import sleep
######################################################
class RASPBERRY_PI2_SSH:
hostname = None
port = None
... |
from rest_framework import permissions
class UpdateOwnProfile(permissions.BasePermission):
"""Allow user to edit their own profile"""
def has_object_permission(self, request, view, obj):
"""Check user is trying to edit their own profile"""
if request.method in permissions.SAFE_METHODS:
... |
""" Test functions for linalg.decomp module
"""
from __future__ import division, print_function, absolute_import
__usage__ = """
Build linalg:
python setup_linalg.py build
Run tests if scipy is installed:
python -c 'import scipy;scipy.linalg.test()'
Run tests if linalg is not installed:
python tests/test_decomp... |
# -*- coding: utf-8
from __future__ import unicode_literals, absolute_import
from django import forms
from jsonsuit.widgets import JSONSuit, ReadonlyJSONSuit
class TestForm(forms.Form):
stats = forms.CharField(widget=JSONSuit)
class ReadonlyTestForm(forms.Form):
stats = forms.CharField(widget=ReadonlyJSON... |
from flexflow.core import *
from flexflow.keras.datasets import cifar10
from accuracy import ModelAccuracy
from PIL import Image
def InceptionA(ffmodel, input, pool_features):
t1 = ffmodel.conv2d(input, 64, 1, 1, 1, 1, 0, 0)
t2 = ffmodel.conv2d(input, 48, 1, 1, 1, 1, 0, 0)
t2 = ffmodel.conv2d(t2, 64, 5, 5, 1, 1... |
"""
Utility for model
"""
import pathlib
import os
import json
def save_list_to_file(path, thelist):
with open(path, 'w') as f:
for item in thelist:
f.write("%s\n" % item)
def mkdir_p(full_dir):
"""Simulate mkdir -p"""
if not os.path.exists(full_dir):
pathlib.Path(full_dir).mk... |
# -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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... |
from __future__ import print_function
import numpy as np
from openmdao.api import ExplicitComponent, Group, IndepVarComp
from wisdem.commonse.utilities import hstack, vstack
from wisdem.commonse.csystem import DirectionVector
from wisdem.commonse import gravity
# This is an extremely simple RNA mass calculator that s... |
from setuptools import setup
from clogd import __VERSION__
setup(
name='clog',
version=__VERSION__,
packages=['clogd'],
package_data={
'': ['static/*.*', 'views/*.*'],
},
install_requires=[
'zpgdb==0.4.2',
'Bottle==0.12.13',
'waitress==1.1.0',
'PyYAML==3.... |
# 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! ***
from ... import _utilities
import typing
# Export this package's modules as members:
from ._enums import *
from .get_namespace import *
from .get_notif... |
# coding=utf-8
# Copyright 2020 The Google Research 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 applicab... |
# -*- coding: utf-8 -*-
"""
JSON API definition.
"""
import math
from urllib import parse
class Page(object):
'''
Page object for display pages.
'''
def __init__(self, item_count, page_index=1,page_size=10):
'''
Init Pagination by item count, page_index and page_size
>>> p1 =... |
# ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# --------------------------------------------... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import os.path as osp
import numpy as np
import pprint
import pdb
from . import evaluate_pr
import scipy.io as sio
'''
intervals : Define thresholds to evaluate pck score
kpnames : Keypoint names
be... |
import gzip
import natsort
from Bio import SeqIO
def get_target(infile: str, outfile) -> None:
contig_hsh = {}
SEX_CHROMOSOME = ("W", "X", "Y", "Z")
sequences = SeqIO.parse(infile, "fasta") if infile.endswith(".fasta") else SeqIO.parse(gzip.open(infile, "rt"), "fasta")
for i in sequences:
cont... |
# Copyright 2020 Huawei Technologies Co., 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 at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.