text stringlengths 2 999k |
|---|
import torch
import time
import numpy as np
from all.core import State
from .writer import ExperimentWriter, CometWriter
from .experiment import Experiment
from all.environments import VectorEnvironment
from all.agents import ParallelAgent
import gym
class ParallelEnvExperiment(Experiment):
'''An Experiment obje... |
import json
from os.path import join, dirname, realpath
with open(join(dirname(realpath(__file__)), "input.txt")) as f:
obj = json.load(f)
def sum_rec(o):
if isinstance(o, int):
return o
if isinstance(o, list):
return sum(map(sum_rec, o))
if isinstance(o, dict):
if "red" in o.... |
import pickle
import sys
import time
from datetime import date, datetime, timedelta
import dateutil
import pytest
import pytz
import simplejson as json
from dateutil import tz
from dateutil.relativedelta import FR, MO, SA, SU, TH, TU, WE
from arrow import arrow, locales
from .utils import assert_datetime_equality
... |
import pytest
def test_choice(serializer):
from abstract_open_traffic_generator.flow import Flow, TxRx, PortTxRx
try:
flow = Flow(name='test', tx_rx=TxRx())
assert('Expected a TypeError when assigning physical')
except TypeError as e:
print(e)
pass
def test_string(serializ... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -------------------------------------------------------------------... |
from mitmproxy.proxy import context
from mitmproxy.test import tflow, taddons
def test_context():
with taddons.context() as tctx:
c = context.Context(
tflow.tclient_conn(),
tctx.options
)
assert repr(c)
c.layers.append(1)
assert repr(c)
c2 = ... |
"""
Hand class tests.
"""
#==================================================================================================#
# Bibliotecas utilizadas:
from ctypes import sizeof
import unittest
from PokerHand import PokerHand
CARDS: str = "KS 2H 5C JD TD"
hand2: str = "9C 9H 5C 5H AC"
class TestPokerHandCompare... |
# -*- coding: utf-8 -*-
#
# Pyserini: Python interface to the Anserini IR toolkit built on Lucene
#
# 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.... |
#!/usr/bin/env python
import json
import yaml
import urllib
import os
import sys
from jsonref import JsonRef
import click
KINDS_WITH_JSONSCHEMA = [
"jsonschemaprops",
"jsonschemapropsorarray",
"customresourcevalidation",
"customresourcedefinition",
"customresourcedefinitionspec",
"customreso... |
import numpy as np
import pydicom
from pydicom.data import get_testdata_files
from tensorflow.keras.utils import Sequence
from tensorflow.keras.utils import to_categorical
from skimage.transform import resize
import config
# Will need to encode categories before calling the Data Generator
# Also before implement spli... |
import vcf_data_loader
def compute_ld(data):
n = data.size()[0]
# Standardize
data = (data - data.mean(dim=0)) / data.std(dim=0)
return (data.transpose(0, 1) @ data / n) ** 2
if __name__ == "__main__":
import matplotlib.pyplot as plt
vcf = vcf_data_loader.FixedSizeVCFChunks(
"all_1k... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2017 John Dewey
#
# 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
# t... |
# Copyright (c) 2012-2021, Camptocamp SA
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions an... |
default_app_config = 'prosopography.apps.ProsopographyConfig'
|
from predictionserver.futureconventions.performanceconventions import (
PerformanceConventions
)
class PerformanceHabits(PerformanceConventions):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._PERFORMANCE_BACKWARD_COMPATIBLE = True
|
# <<BEGIN-copyright>>
# Copyright 2019, Lawrence Livermore National Security, LLC.
# See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: MIT
# <<END-copyright>>
from __future__ import print_function
import os
from numericalFunctions import pointwiseXY_C
if( 'CHECKOPTIONS' in os.environ ) :
... |
import sys
import sinedon
from sinedon import dbconfig
from sinedon import directq
from leginon import projectdata
from leginon import leginondata
import time
# set direct_query values
# exclude preset lable
excludelist = ()
def checkSinedon():
try:
destination_dbinfo = dbconfig.getConfig('importdata')
except Key... |
# SPDX-License-Identifier: Apache-2.0
import copy
import numbers
from collections import deque, Counter
import ctypes
import json
import numpy as np
from ...common._apply_operation import (
apply_div, apply_reshape, apply_sub, apply_cast, apply_identity, apply_clip)
from ...common._registration import register_con... |
# Copyright 2015 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 agreed to in writing, s... |
from __future__ import absolute_import, division, print_function
import ast
from itertools import repeat
from toolz import merge
from . import arithmetic
from . import math
from .expressions import Expr, Symbol
__all__ = ['exprify']
def generate_methods(node_names, funcs, builder):
def wrapped(cls):
f... |
#!/usr/bin/env python3
# coding: utf-8
__author__ = 'cleardusk'
import numpy as np
from math import sqrt
import scipy.io as sio
import matplotlib.pyplot as plt
from .ddfa import reconstruct_vertex
def get_suffix(filename):
"""a.jpg -> jpg"""
pos = filename.rfind('.')
if pos == -1:
return ''
r... |
import kanp
from kwmo.lib.kwmo_kcd_client import KcdClient
from pylons import config
from kwmo.lib.config import get_cached_kcd_external_conf_object
from kwmo.model.kcd.kcd_user import KcdUser
#KANP_EMAIL_NOTIF_FLAG = 1
#KANP_EMAIL_SUMMARY_FLAG = 2
from kflags import Flags
class UserWorkspaceSettings:
def __i... |
from flask import render_template
from flask import Flask,request
import logging
app = Flask(__name__)
@app.route('/')
def index():
logging.info('>>>>>>>>>>>>>')
ip = request.remote_addr
print(ip)
logging.info(ip)
logging.info('<<<<<<<<<<<<<')
return render_template("./index.html")
if __nam... |
# coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from abc import abst... |
# -*- coding: utf-8 -*-
# Open Source Initiative OSI - The MIT License (MIT):Licensing
#
# The MIT License (MIT)
# Copyright (c) 2012 DotCloud Inc (opensource@dotcloud.com)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Softwa... |
from sys import argv
from bs4 import BeautifulSoup
import requests
import datetime
url = 'http://www.njtransit.com/sf/sf_servlet.srv?hdnPageAction=TrainSchedulesFrom'
pu_code = "124_PRIN"
ny_code = "105_BNTN"
prs = "Princeton"
nyp = "New York Penn Station"
# get date
today = datetime.date.today()
str_date = today.__f... |
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2013 NTT MCL Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the... |
from wallpaper_downloader import site_parser
def test_page_with_wallpapers_urls(
get_page_html_from_file,
get_wallpapers_urls_from_file,
get_wallpapers_names_from_file,
):
"""
Test '_find_wallpapers_urls' function of site_parser module.
Function is tested with the HTML where URLs of wallpaper... |
from django.db import models
# Create your models here.
class Faq(models.Model):
question = models.CharField(max_length=1000)
answer = models.TextField(default='')
def __str__(self):
return self.question
class Qs(models.Model):
qs = models.CharField(max_length=1000)
def __str__(self):
... |
#!/usr/bin/env python
# -*- test-case-name: twisted.names.test.test_examples -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Print the IP address for a given hostname. eg
python gethostbyname.py www.google.com
This script does a host lookup using the default Twisted Names
resolver, ... |
# -*- coding: utf-8 -*-
# Copyright 2020 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... |
import pytest
@pytest.mark.parametrize("idx", range(5))
def test_initial_approval_is_zero(gauge_v3_1, accounts, idx):
assert gauge_v3_1.allowance(accounts[0], accounts[idx]) == 0
def test_approve(gauge_v3_1, accounts):
gauge_v3_1.approve(accounts[1], 10 ** 19, {"from": accounts[0]})
assert gauge_v3_1.a... |
"""Discover and run std-library "unittest" style tests."""
import sys
import traceback
import types
from typing import Any
from typing import Callable
from typing import Generator
from typing import Iterable
from typing import List
from typing import Optional
from typing import Tuple
from typing import Type
from typing... |
# -*- coding: utf-8 -*-
from gen_stats import Checkin, load_checkins
import bisect
from PIL import Image
import urllib
import cStringIO
WIDTH = 5616
HEIGHT = 3744
SIZES = {
'photo_img_sm': 100,
'photo_img_md': 320,
'photo_img_lg': 640
}
def get_rowcol(img_size):
cols = WIDTH / float(img_size)
... |
import os
import logging
import uuid
from datetime import datetime, timedelta
from typing import List, Tuple, Optional
import pytz
from fastapi import Depends, APIRouter, status
from okdata.resource_auth import ResourceAuthorizer
from models import (
CreateWebhookTokenBody,
WebhookTokenAuthResponse,
Webho... |
import cgi
import json
import urllib.parse, socket, http.client
import os
import pickle
import ssl
from act.common import aCTConfig
class aCTPanda:
def __init__(self,logger, proxyfile):
self.conf = aCTConfig.aCTConfigAPP()
server = self.conf.get(['panda','server'])
u = urllib.parse.urlpar... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import unittest
import pbtest
import json
class SuperCookieTest(pbtest.PBSeleniumTest):
"""Make sure we detect potential supercookies. """
def has_supercookies(self, origin):
"""Check if the given origin has supercookies in PB's localStorage."""
... |
from .rc522 import RC522
from py522.exceptions import NoReplyException, InvalidBCCException, ReaderException
import serial
import time
class RC522Uart(RC522):
BAUD_REG_VALUE = {
7200: 0xFA,
9600: 0xEB,
14400: 0xDA,
19200: 0xCB,
38400: 0xAB,
57600: 0x9A,
115200: 0x7A,
128000: 0x74,
230400: 0x5A,
4... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.utils.weight_norm as wn
from torch.nn.modules.batchnorm import _BatchNorm
import numpy as np
import pdb
import os
# ------------------------------------------------------------------------------
# Utility Methods
# --------------------... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
intensity_normalization.normalize.gmm
fit three gaussians to the histogram of
skull-stripped image and normalize the WM mean
to some standard value
Author: Blake Dewey (blake.dewey@jhu.edu),
Jacob Reinhold (jacob.reinhold@jhu.edu)
Created on: Apr 24, 2018
"""... |
import sgqlc.types
ebucore_schema = sgqlc.types.Schema()
########################################################################
# Scalars and Enumerations
########################################################################
Boolean = sgqlc.types.Boolean
String = sgqlc.types.String
########################... |
import numpy as np
import scipy.sparse as sp
from scipy import linalg, optimize, sparse
from sklearn.datasets import load_iris, make_classification
from sklearn.metrics import log_loss
from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import LabelEncoder
from sklearn.utils import compute_cl... |
# As a test suite for the os module, this is woefully inadequate, but this
# does add tests for a few functions which have been determined to be more
# portable than they had been thought to be.
import asynchat
import asyncore
import codecs
import contextlib
import decimal
import errno
import fnmatch
import fractions
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def create_superadmin_group(apps, schema_editor):
"""
Migrates the groups to create an admin group with all permissions
granted. Replaces the delegate group to get pk=2.
- Create new delegate group. Move... |
"""Handle the loading and initialization of game sessions."""
from __future__ import annotations
import copy
import lzma
import pickle
import traceback
from typing import Optional
import tcod
import color
from engine import Engine
import entity_factories
from game_map import GameWorld
import input_handlers
from proc... |
# coding=utf-8
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# 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/lice... |
from __future__ import division, print_function
import numpy as np
from openaerostruct.geometry.utils import generate_mesh
from openaerostruct.integration.aerostruct_groups import AerostructGeometry, AerostructPoint
import openmdao.api as om
from openaerostruct.utils.constants import grav_constant
# Create a dictio... |
# -*- coding: utf-8 -*-
from itertools import chain
from atores import ATIVO
VITORIA = 'VITORIA'
DERROTA = 'DERROTA'
EM_ANDAMENTO = 'EM_ANDAMENTO'
class Ponto():
def __init__(self, x, y, caracter):
self.caracter = caracter
self.x = round(x)
self.y = round(y)
def __eq__(self, other):... |
from django.conf.urls import url
from .controllers import generate, rearrange, home
urlpatterns = [
url(r'^generate$', generate),
url(r'^rearrange', rearrange),
url(r'^$', home),
]
|
#Copyright [2020] [Indian Institute of Science, Bangalore & Tata Institute of Fundamental Research, Mumbai]
#SPDX-License-Identifier: Apache-2.0
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.optimize import least_squares
def find_slope(data):
n = len(data... |
import json
import pytest
from monty.io import zopen
from emmet.core.vasp.calc_types import RunType, TaskType, run_type, task_type
from emmet.core.vasp.task import TaskDocument
from emmet.core.vasp.validation import ValidationDoc
def test_task_type():
# TODO: Switch this to actual inputs?
input_types = [
... |
import datetime
import json
import locale
import os
import shutil
from types import ModuleType
from typing import Union
import numpy as np
import pandas as pd
import pytest
from freezegun import freeze_time
import great_expectations as ge
from great_expectations.core import (
ExpectationConfiguration,
Expecta... |
def fibonacci(n):
series = []
a, b = 0, 1
if n == 0:
return a
elif n == 1:
return b
else:
series.append(a)
series.append(b)
for i in range(2,n):
series.append(series[i-1] + series[i-2])
return series
print(fibonacci(10)) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import rospy
import math
import os
import cv2
from geometry_msgs.msg import Pose, Point, Quaternion
from std_msgs.msg import Float32MultiArray
from prometheus_msgs.msg import DetectionInfo, MultiDetectionInfo
rospy.init_node('oriented_object_segs_client', an... |
from django.apps import AppConfig
class MyserConfig(AppConfig):
name = 'myser'
|
#!/usr/bin/env python3
import numpy as np
import re
import random
# ---- Hamming code classes --- #
# This code assumes that words and codewords are encoded as row vectors.
# Thus, word w is encoded into codeword c with w.G and c is decoded with c.H.
# ---- Hamming encoder class --- #
class HammingEncoder(object):... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 28 17:08:30 2020
@author: Christopher Cheng
"""
import time
print("Loading...")
for i in range(10):
print("[",i*"*",(10-i)*" ","]",i*10,"% Complete")
time.sleep(0.5) |
import os
from functools import reduce
from core.TemplateEngine import render
mydir = os.path.dirname(__file__)
def tab(n):
if n <= 0:
return ""
else:
# return "\t" * n
return " " * n
def indent(lines):
return [tab(1) + line for line in lines]
def convert_to_cpptype_string(... |
import pandas as pd
import numpy as np
def build_and_clean_df(original_df, sub_features):
df = original_df[sub_features].copy()
df = df.replace({np.nan: None})
df = df.astype(
{
"commune": "category",
"enqu": "category",
"wilaya": "category",
"ident"... |
"""
Base settings to build other settings files upon.
"""
import environ
#import django
ROOT_DIR = environ.Path(__file__) - 3 # (nobody_will_see_this/config/settings/base.py - 3 = nobody_will_see_this/)
APPS_DIR = ROOT_DIR.path('nobody_will_see_this')
env = environ.Env()
READ_DOT_ENV_FILE = env.bool('DJANGO_READ_D... |
"""
HTML Widget classes
"""
import copy
import datetime
import time
from itertools import chain
from urlparse import urljoin
from util import flatatt
from django.conf import settings
from django.utils.datastructures import MultiValueDict, MergeDict
from django.utils.html import escape, conditional_escape
from django.... |
#!/usr/bin/env python
# -*- coding: utf-8 *-*
import json
import glob
import re
import csv
import sys
def check_that_dict_has_equal_length(resultDict):
i = 0
for key, value in resultDict.iteritems():
if i == 0:
length = len(value)
if not length == len(value):
print("Ke... |
import copy
from collections import OrderedDict
from dataclasses import dataclass
from typing import Optional
import torch
import warnings
from torch import nn
import torch.nn.functional as F
try:
from pytorch_quantization import nn as quant_nn
except ImportError as e:
warnings.warn(
"pytorch_quantizat... |
# Copyright 2015 PerfKitBenchmarker 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... |
# 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 ... |
#!/usr/bin/env python
# encoding: utf-8
"""Separate a path into its directory and base components.
"""
import os.path
for path in ['/one/two/three',
'/one/two/three/',
'/',
'.',
'']:
print '"%s" : "%s"' % (path, os.path.split(path))
|
import unittest
from BST.BasicBst import BasicBst
class TestBasicBst(unittest.TestCase):
def test_should_add_first_node_as_root(self):
bst = BasicBst()
bst[55] = 'this is cool'
bst[10] = 'test'
self.assertEqual(bst.root.value, 'this is cool')
def test_should_have_size_of_three... |
import json
import re
from vkbottle.rule import FromMe
from vkbottle.user import Blueprint, Message
from idm_lp.database import Alias
from idm_lp.idm_api import IDMAPI, IDMException
from idm_lp.logger import logger_decorator
user = Blueprint(
name='aliases_blueprint'
)
async def send_signal(
message: M... |
def display_strings(str_list, ch):
# Modify the code below
longest_length = 0
new_string_list = []
number_padding = len(str_list) - 1
# find longest string length
for string in str_list:
if len(string) > longest_length:
longest_length = len(string)
# move string to another list
... |
import json
from pprint import pformat
import requests
from simplejson import JSONDecodeError
from pytezos.logging import logger
def urljoin(*args):
return "/".join(map(lambda x: str(x).strip('/'), args))
def gen_error_variants(error_id) -> list:
chunks = error_id.split('.')
variants = [error_id]
... |
import sys
class AppTestCodecs:
spaceconfig = {
"usemodules": ['unicodedata', 'struct', 'binascii'],
}
def test_register_noncallable(self):
import _codecs
raises(TypeError, _codecs.register, 1)
def test_bigU_codecs(self):
u = u'\U00010001\U00020002\U00030003\U00040004\... |
"""
Attribute token definition file for Bentham Instruments Spectroradiometer
Control DLL.
"""
# -----------------------------------------------------------------------------
# Monochromator attributes
# -----------------------------------------------------------------------------
MonochromatorScanDirection = 10
Mono... |
"""
#
# 26/08/2018
# Oladotun Rominiyi - Copyright © 2018. all rights reserved.
"""
__author__ = 'dotun rominiyi'
# IMPORTS
import ujson
import ssl
import websockets
from base64 import b64decode
from zlib import decompress, MAX_WBITS
from signalr_aio.transports import Transport as SignalRTransport
from signalr_aio i... |
# coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
from unittest import TestCase
from tests.misc.helper import get_slave_xmss
from xrd.core.misc import logger
from xrd.core.BlockMetadata import BlockMetadata
from xrd.c... |
from . import opentdb as api
from random import shuffle
import json
import psycopg2
from collections import Counter
class PostgreHelp:
def __init__(self):
#self.redisClient = redis.Redis(host="127.0.0.1", port=6379)
self.user = 'user'
self.connection = psycopg2.connect(user="postgres",
... |
#!/usr/bin/env python3
import codecs
import json
import os
from urllib.request import urlopen
import yaml
def load_config(directory):
_repo_config = {}
for _basedir, _, _filenames in os.walk(directory):
for _filename in _filenames:
if not _filename.endswith('.yaml'):
cont... |
from .base import CPObject, TextField, ObjectField
from .address_details import AddressDetails
class Sender(CPObject):
_name = 'sender'
_fields = {
"name": TextField("name"),
"company": TextField("company"),
"contact_phone": TextField("contact-phone"),
"address_details": Objec... |
# Copyright 2019 Nick Guletskii
#
# 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 ... |
"""Plug-in for Widgetastic browser with 3scale specific environment settings"""
from contextlib import contextmanager
from time import sleep
from urllib import parse
from widgetastic.browser import Browser, DefaultPlugin
# pylint: disable=abstract-method
class ThreescaleBrowserPlugin(DefaultPlugin):
"""
Plug... |
import matplotlib.pyplot as plt
import numpy as np
data = np.loadtxt('scoring.txt')
print(data)
blocks_remaining = data[:, 0]
score = data[:, 1]
plt.plot(score, blocks_remaining)
poly = np.poly1d(np.polyfit(blocks_remaining, score, 1))
print(poly(0))
print(np.diff(score))
plt.show()
# 12562 is too low |
from django.db import models
from ckeditor.fields import RichTextField
class Artist(models.Model):
name = models.CharField(max_length=100)
biography = RichTextField(blank=True, null=False)
def __str__(self):
return self.name
class Location(models.Model):
name = models.CharField(max_length=1... |
# coding=utf8
# Copyright (C) 2004-2017 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
#
# Authors: Aric Hagberg (aric.hagberg@gmail.com)
# Pieter Swart (swart@lanl.gov)
# Sasha Gutfraind (... |
import enum
import rlp
from eth_utils import address, keccak
from rlp.sedes import big_endian_int, CountableList, Binary
from plasma_core.constants import NULL_SIGNATURE, NULL_ADDRESS, EMPTY_METADATA
from plasma_core.utils.eip712_struct_hash import hash_struct
from plasma_core.utils.transactions import encode_utxo_id... |
# -*- coding: utf-8 -*-
# Copyright (c) 2019, VHRS and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
# import frappe
from frappe.model.document import Document
class PumpingTest(Document):
pass
|
# Copyright 2018 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 agreed to in writing, ... |
from xd.build.core.data.namespace import *
from xd.build.core.data.expr import Expression
from xd.build.core.data.string import String
from xd.build.core.data.list import List
from xd.build.core.data.dict import Dict
from xd.build.core.data.func import Function
from xd.build.core.data.num import *
import unittest
cla... |
from django.db.backends.base.features import BaseDatabaseFeatures
class DatabaseFeatures(BaseDatabaseFeatures):
allow_sliced_subqueries_with_in = False
can_introspect_autofield = True
can_introspect_small_integer_field = True
can_return_id_from_insert = True
can_use_chunked_reads = False
for_u... |
import os
import argparse
# Argument Parser
parser = argparse.ArgumentParser()
# Device Information
parser.add_argument('--device', type=str, default='cuda:0', help='device cuda or cpu')
# Data information
parser.add_argument('--midi_path', type=str, default='/fast-1/mathieu/datasets/', help='path to midi folder')
pars... |
from sanic import Sanic
from sanic import Blueprint
from sanic.response import json
app = Sanic(__name__)
blueprint = Blueprint('name', url_prefix='/my_blueprint')
blueprint2 = Blueprint('name2', url_prefix='/my_blueprint2')
blueprint3 = Blueprint('name3', url_prefix='/my_blueprint3')
@blueprint.route('/foo')
async... |
import addict
__all__ = ['Meter']
class _AverageMeter(object):
def __init__(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val):
self.val = val
self.sum += val
self.count += 1
self.avg = self.sum / self.coun... |
from __future__ import division
import numpy as np
import scipy.integrate
from numpy import exp, pi
class ComplexPath(object):
"""A base class for paths in the complex plane."""
def __init__(self):
self._integralCache = {}
self._trapValuesCache = {}
def __call__(self, t):
r"""
... |
# Copyright 2020 The Magenta 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 law or agreed to in ... |
from .base import *
DEBUG = True
def get_secret(setting, secrets):
"""Get the secret variable or return explicit exception."""
try:
return secrets[setting]
except KeyError:
error_msg = "Set the {0} environment variable".format(setting)
raise ImproperlyConfigured(error_msg)
# JSO... |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
mod=10**9+9
dp1,dp2=[[0]*10 for i in range(2)],[[0]*26 for i in range(2)]
rdp1,rdp2=[0]*5,[0]*5
for i in range(10): dp1[1][i]=1
for i in range(26): dp2[1][i]=1
rdp1[1],rdp2[1]=10,26
for i in range(2,5):
for j in range(10):
dp1[i&1][j]=(rdp1[i-1]-dp1[(i-1)&1][j])%mod
rdp1[i]=(rdp1[i]+dp1[i&1][j])%mod... |
import sqlite3
from sqlite3 import Connection
from unittest import TestCase
from unittest.mock import Mock
from uuid import uuid4
from eventsourcing.persistence import (
DatabaseError,
DataError,
InfrastructureFactory,
IntegrityError,
InterfaceError,
InternalError,
NotSupportedError,
Op... |
# set a random image from unsplash as a wallpaper
import ctypes
import datetime
import requests
def getTimeStamp():
dateToday = datetime.datetime.today()
today = str(datetime.date.today())
hour = str(dateToday.hour)
sec = str(dateToday.second)
return f'{today} {hour} - {sec}'
def getWa... |
token = '250324006:AAFDAxe4nVlgI3nFkUhVBWHf1xTo1bRwwpc ' # Add Your Token
is_sudo = '242361127' # add Your ID
|
from collections import OrderedDict
import numpy as np
import sympy
import itertools as it
import scipy.linalg as la
from copy import deepcopy
import tinyarray as ta
from .linalg import matrix_basis, nullspace, sparse_basis, family_to_vectors, rref, allclose
from .model import Model, BlochModel, BlochCoeff, _commutati... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.