text stringlengths 2 999k |
|---|
# Copyright 2016 gRPC 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 writing... |
# -*- coding: utf-8 -*-
from ccxt.btcbox import btcbox
class jubi (btcbox):
def describe(self):
return self.deep_extend(super(jubi, self).describe(), {
'id': 'jubi',
'name': 'jubi.com',
'countries': 'CN',
'rateLimit': 1500,
'version': 'v1',
... |
'''
This file is part of soundannotatordemo. The soundannotatordemo repository
provides democode and documentation accompanying the libsoundannotator
repository, available from https://github.com/soundappraisal/libsoundannotator.
The library libsoundannotator is designed for processing sound using
time-frequency repr... |
import tweepy
import os
import time
# Store access keys
consumer_key = '1cLeoWmt5u9bJcCIis8xsKJw9'
consumer_key_secret = 'pokzxnCuAyueXdogzKC3mVL7F0U3dxqZf08bfj7r8sR8XE4Vvn'
access_token = '1125477861115043840-3nTv2MjORa8oUBYoP18uOTOwNstuvl'
access_token_secret = 'kdBlhdwJU3TxHAl67cXcyYIaIRXI3GvKYxBfPnEpN7OKP'
# Conn... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2018-03-31 05:57
from __future__ import unicode_literals
import apps.accounts.utils
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
... |
# direct string
print("direct string")
# string variable
my_string = "string variable"
print(my_string)
# string with quotes
single_quote = 'single quote'
print(single_quote)
double_quotes = "double quotes"
print(double_quotes)
multi_quotes = 'this is single quote and "this is double quotes"'
print(multi_quotes)
... |
import sys
from modules.excel_gen import ExcelGenerator
from modules.word_gen import WordGenerator
from modules.ppt_gen import PowerPointGenerator
from modules.msproject_gen import MSProjectGenerator
from modules.vba_gen import VBAGenerator
from modules.vbs_gen import VBSGenerator
from modules.hta_gen import HTAGenera... |
# -*- coding: utf-8 -*-
from phanterweb.fontawesome import (
FontawesomeButtonLeftMenu,
FontawesomeButtonLeftMenuPlus
)
from phanterweb.helpers import (
CONCATENATE
)
html = CONCATENATE(
FontawesomeButtonLeftMenu(
"edit_admin_auth_group",
"Edit Group",
"fab fa-black-tie",
... |
# Configuration file for ipython.
# ------------------------------------------------------------------------------
# InteractiveShellApp(Configurable) configuration
# ------------------------------------------------------------------------------
## A Mixin for applications that start InteractiveShell instances.
#
# ... |
def boyer_moore_galil(t, w, n, m):
BM = suffix.boyer_moore_shift(w, m)
i, memory = 1, 0
while i <= n - m + 1:
j = m
while j > memory and t[i + j - 1] == w[j]:
j = j - 1
if j == memory:
yield i
i, memory = i + BM[0], m - BM[0]
else:
i, memory = i + BM[j], 0 |
# Imports
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import random
import math
from scipy.misc import imsave
###
### Convolutional Neural Network (CNN) for MNIST
###
class CnnData2: ##### OBS: only works if stride size = filter size of pooling layer
def __init__( self, session... |
from keras.preprocessing.image import ImageDataGenerator
def get_data_generator(opt):
if opt.is_train:
return ImageDataGenerator(
featurewise_center=opt.featurewise_center,
samplewise_center=opt.samplewise_center,
featurewise_std_normalization=opt.featurewise_st... |
import re
# Allow underscore in host name
_label_valid = re.compile(b"(?!-)[A-Z\d\-_]{1,63}(?<!-)$", re.IGNORECASE)
def is_valid_host(host: bytes) -> bool:
"""
Checks if a hostname is valid.
"""
try:
host.decode("idna")
except ValueError:
return False
if len(host) > 255:
... |
# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals, print_function
from six.moves import input
import frappe, os, re, git
from frappe.utils import touch_file, cstr
def make_boilerplate(dest, app_name):
if not os.path.exists(de... |
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
import sys
class Pixman(AutotoolsPackage):
"""The Pixman package contains a library that provide... |
"""Setup module for ZHAQuirks."""
from setuptools import find_packages, setup
VERSION = "0.0.64"
def readme():
"""Print long description."""
with open("README.md") as f:
return f.read()
setup(
name="zha-quirks",
version=VERSION,
description="Library implementing Zigpy quirks for ZHA in... |
from tir import Webapp
import unittest
from datetime import datetime
import time
DateSystem = datetime.today().strftime("%d/%m/%Y")
class PMSC200(unittest.TestCase):
@classmethod
def setUpClass(self):
'''
SETUP
Test Case Initial Setup
'''
#Endereco do webapp e o nome... |
import strings
#strings.hello_world()
#strings.loop_string('hello')
#print()
#strings.loop_string_while('hello')
str = 'Four score and seven years ago'
word_list = str.split() # Lecture 3/10/2022
print(word_list)
for word in word_list:
print(word) |
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.10.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
... |
import argparse
import math
import os
import torch
from torch import optim
from torch.nn import functional as F
from torchvision import transforms
from PIL import Image
from utils import tensor2image, save_image
from tqdm import tqdm
import lpips
from model import Generator, Encoder
def noise_regularize(noises):
... |
quine = 'print("quine = " + repr(quine) + "; eval(quine)")'; eval(quine)
def quine_test():
"""
>>> quine_test()
QUINE!
"""
import contextlib, io
f = io.StringIO()
with contextlib.redirect_stdout(f):
exec(quine)
quine_output = f.getvalue()
if quine == quine_output:
p... |
#!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
... |
import numpy as np
from PIL import Image
import h5py
import json
import os
import io
import pickle
from torchmeta.utils.data import Dataset, ClassDataset, CombinationMetaDataset
# QKFIX: See torchmeta.datasets.utils for more informations
from torchmeta.datasets.utils import download_file_from_google_drive
class Tier... |
#!/usr/bin/env python3
from genericpath import exists
from optparse import OptionParser
from utils import get_ast_from_file
from compiler import Compiler
from analyzer import Analyzer
from errors import IOError
from builtIns import new_ctx
__version__ = "0.01@test"
def main():
parser = OptionParser()
parser.s... |
from styx_msgs.msg import TrafficLight
import tensorflow as tf
import numpy as np
import datetime
class TLClassifier(object):
def __init__(self):
TrainedModelPath = r'light_classification/model/faster_rcnn_frozen_inference_graph.pb'
self.graph = tf.Graph()
self.threshold = .5
with ... |
import numpy as np
from petsc4py import PETSc
def main():
# import petsc4py
n = 4
dx = 1.0/(n - 1)
dy = dx
comm= PETSc.COMM_WORLD
da = PETSc.DMDA().create([n, n], dof=1, stencil_width=1, comm=comm)
dar = da.refine()
print(dar.getSizes())
exit()
rank = PETSc.COMM_WORLD.getR... |
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from ..registry import iso_register
from .core import UnitedStates
@iso_register('US-IA')
class Iowa(UnitedStates):
"""Iowa"""
include_thanksgiving_friday = True
include_co... |
import argparse
def parse_args():
"""
Parse Arguments for segmentation with UNet.
Returns:
-------
* `args`: [argparse object]
Parsed arguments.
"""
parser = argparse.ArgumentParser(description='Segmentation parameters.')
parser.add_argument('-d','--datapath', metavar='DIR', d... |
import pytest
import torch
from espnet2.tts.fastspeech2 import FastSpeech2
@pytest.mark.parametrize("postnet_layers", [0, 1])
@pytest.mark.parametrize("reduction_factor", [1, 2, 3])
@pytest.mark.parametrize(
"spk_embed_dim, spk_embed_integration_type",
[(None, "add"), (2, "add"), (2, "concat")],
)
@pytest.ma... |
# Copyright (c) 2020, salesforce.com, inc.
# All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# For full license text, see the LICENSE file in the repo root
# or https://opensource.org/licenses/BSD-3-Clause
from ai_economist.foundation.base.base_env import scenario_registry
from .covid19 import covid19_en... |
#!/usr/bin/env python3
import sys
from PyQt5.QtCore import QBasicTimer, Qt
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QApplication, QLabel
class Marquee(QLabel):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.right_to_left_direction = True
self.initUI()
... |
# pylint: disable=too-many-lines
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# ----------------------------------------------------... |
import logging
import checkslots as c
from time import sleep
import pathlib as pl
from decouple import config
from datetime import datetime as dt
import sys
pl.Path('log').mkdir(parents=False, exist_ok=True)
log = logging.getLogger('cowin')
log.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s | %(me... |
from tkinter import *
from view import * # 菜单栏对应的各个子页面
from view2 import *
class Zhuyemian(object):
# 初始化
def __init__(self, master=None):
self.root = master # 定义内部变量root
self.root.geometry('%dx%d' % (600, 400)) # 设置窗口大小
self.createPage()
def createPage(self):
#连接view里的... |
from flask import session
from flask_socketio import emit, join_room, leave_room
from .. import socketio, connected_players
@socketio.on('joined', namespace='/play')
def joined():
join_room('quizzy')
emit('status', {'msg': session.get('name') + ' has joined the game.'}, room='quizzy')
@socketio.on('/status'... |
from IPython.display import clear_output
import random
def display_board(board):
print(' | |')
print('' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('----------')
print(' | |')
print('' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
... |
import warnings
from typing import Optional
import torch
from quicknlp.utils import assert_dims
from .basic_decoder import EmbeddingRNNDecoder
class RNNAttentionDecoder(EmbeddingRNNDecoder):
def __init__(self, ntoken: int, emb_sz: int, nhid: int, nlayers: int, pad_token: int, eos_token: int,
m... |
import logging
import pathlib
from typing import Iterable, Iterator, List, Optional
import pydantic
import shapely.geometry
import urllib3
from vaccine_feed_ingest import vial
from vaccine_feed_ingest.schema import schema
from ..utils.match import canonicalize_address, get_full_address
from . import outputs
from .com... |
from contextlib import contextmanager
import psycopg2
import psycopg2.extensions
import psycopg2.extras
import psycopg2.pool
import psycopg2.sql
import gws
import gws.types as t
# noinspection PyArgumentList
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
# noinspection PyArgumentList
psycopg2.extens... |
from psion.oauth2.exceptions import InvalidClient
from psion.oauth2.mixins import ClientMixin
from psion.oauth2.models import Request
from psion.webtools import get_basic_authorization
from .base import BaseAuthentication
class ClientSecretBasic(BaseAuthentication):
"""
Implements the Client Authentication v... |
from django.db.models.query import QuerySet
class TestQuerySet(QuerySet):
def field_one_true(self, queryset, user, request):
return queryset.filter(field_one=True)
def field_two_true(self, queryset, user, request):
return queryset.filter(field_two=True)
def field_three_true(self, querys... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016, the cclib development team
#
# This file is part of cclib (http://cclib.github.io) and is distributed under
# the terms of the BSD 3-Clause License.
"""Calculation of overlap population analysis based on cclib data."""
import random
import numpy
from .cal... |
import pandas as pd
import numpy as np
from scipy.stats import spearmanr
from sklearn.metrics import matthews_corrcoef, ConfusionMatrixDisplay
from alaska2.submissions import blend_predictions_ranked, blend_predictions_mean
import matplotlib.pyplot as plt
from sklearn.metrics import plot_confusion_matrix
v25_xl_NR_mor... |
from enum import IntEnum
class LoaddataFromFileScanQuota(IntEnum):
VALUE_0 = 0
VALUE_1 = 1
VALUE_2 = 2
def __str__(self) -> str:
return str(self.value)
|
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# -------------------------------------------------------------------------
from typin... |
DB_FILENAME = 'db/db.sqlite'
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-07-16 19:20
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('quiz', '0013_auto_20170716_1541'),
]
operations = [
migrations.AlterField(
... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
import numpy as np
import rospy
from std_msgs.msg import Bool
from geometry_msgs.msg import Point, Twist, Vector3
# Global variables
blue_center = Point()
blue_flag = False
blue_base = Point()
red_base = Point()
blue_twist = Twist()
game_over = False
accumulated_error = 0.
neutral_zone = False
# Helper functions
def ... |
import csv, re
from os import sys, path
line_re = re.compile("\s+(\d+)\s{2,}(.+?)\s{3,}([\d,]+)\s{2,}([\d\.]+)\n")
# write the file data row to the first line of the output file
for thisfile in ['', '-hispanic', '-black', '-asian']:
filename = 'txts/2015-2016-dma-ranks' + thisfile + '.txt'
print "Readi... |
# coding: utf-8
import pprint
import re
import six
class UpdateBandwidthOption:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the va... |
from zeeguu.core.test.model_test_mixin import ModelTestMixIn
from zeeguu.core.test.rules.user_rule import UserRule
from zeeguu.core.model.bookmark_priority_arts import BookmarkPriorityARTS
from zeeguu.core.word_scheduling import arts
class WordsExerciseStatsTest(ModelTestMixIn):
def setUp(self):
super().... |
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.dos.anjos@gmail.com>
# Mon 4 Feb 14:12:24 2013
"""Builds custom scripts with the right paths for external dependencies
installed on different prefixes.
"""
import os
import sys
import time
import logging
from zc.recipe.egg import Scripts
fro... |
import os
import codecs
import pandas as pd
from pathlib import Path
from glob import glob
from ekorpkit.utils.func import ordinal
class ESGReport:
def __init__(self, name, output_dir, output_file, input_path, txt_info, **kwargs):
self.name = name
self.input_path = input_path
self.txt_inf... |
API_ENDPOINT = 'https://api.uploadgram.me/'
DOWNLOAD_ENDPOINT = 'https://dl.uploadgram.me/'
PASTEGRAM_ENDPOINT = 'https://paste.uploadgram.me/' |
from energy_supplier.group_member import GroupMember
from config import participants
class Group(object):
"""
The addresses and public keys of the group that belong to the same energy
supplier.
"""
def __init__(self, participants):
self.participants = participants
self.group_member... |
# index.py -- File parser/writer for the git index file
# Copyright (C) 2008-2013 Jelmer Vernooij <jelmer@samba.org>
#
# Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
# General Public License as public by the Free Software Foundation; version 2.0
# or (at your option) any later version. You... |
import random
import time
from django.core.exceptions import ObjectDoesNotExist
import pytz
from django.db.models import Q
from django.utils import timezone
from threepio import logger
from core.models import AccountProvider
from core.models.credential import Credential
from core.models import InstanceStatusHistory
fro... |
from datetime import datetime
from pathlib import Path
from threading import Lock
from typing import Any, List, Optional, Union
from sqlalchemy import ( # type: ignore
BigInteger,
Column,
LargeBinary,
MetaData,
String,
Table,
create_engine,
delete,
insert,
select,
update,
)... |
class AuthenticationError(KeyError):
pass
|
import time
from multiprocessing import Process
from proxypool.api import app
from proxypool.getter import Getter
from proxypool.tester import Tester
from proxypool.db import RedisClient
from proxypool.setting import *
class Scheduler():
def schedule_tester(self, cycle=TESTER_CYCLE):
"""
定时测试代理
... |
import _plotly_utils.basevalidators
class BordercolorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self,
plotly_name='bordercolor',
parent_name='scatterternary.marker.colorbar',
**kwargs
):
super(BordercolorValidator, self).__init__(
... |
# -*- coding: utf-8 -*-
# Copyright 2010-2021, Google 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:
#
# * Redistributions of source code must retain the above copyright
# notice, this... |
import sys, os
sys.path.append('./Models/')
sys.path.append('../src/ccscp/')
sys.path.append('../src/utils/')
import astrobee_plot
from cc_ocp import *
from Models.astrobee import Model
from astro_iss_plot import plot
from astrobee_mc import monte_carlo
# Initialize Astrobe model
m = Model()
N = m.N
# Create cha... |
# This has not been tested yet.
import os
def install():
# Move the ITSToolKit.sh to the /bin/ directory
os.system("mv ITSToolKit.py ~bin/")
os.system("mv ITSToolKit ~bin/")
# Install the pip3 requirements
os.system("pip3 install os")
os.system("pip3 install time")
os.system("pip3 i... |
import cv2
from os import listdir
from os.path import isfile, join
import time,sys
import pickle
import imagehash
from PIL import Image
# Perceptual hash algorithm. LSH for frames
def phash(image,hashSize=4):
# Return a truth matrix, a matrix of boolean values
diff = imagehash.phash(Image.fromarray(image),hash... |
import sympy
from converter.qiskit import QuantumCircuit
from converter.qiskit.qasm import _node as node
|
#!/usr/bin/python
#
# Copyright 2011 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... |
from telegram.ext import (Updater, CommandHandler, CallbackQueryHandler, Filters, BaseFilter)
from telegram.error import (TelegramError, Unauthorized, BadRequest, TimedOut, ChatMigrated, NetworkError)
from telegram import (InlineKeyboardButton, InlineKeyboardMarkup)
import logging
from time import (localtime, strftime... |
'''
Graph
======
The :class:`Graph` widget is a widget for displaying plots. It supports
drawing multiple plot with different colors on the Graph. It also supports
axes titles, ticks, labeled ticks, grids and a log or linear representation on
both the x and y axis, independently.
To display a plot. First create a graph... |
#!/usr/bin/python
"""
Needleman-Wunsch Aligner
Bioengineering 131/231, Fall 2018
Command-line script to read in the contents of a multi-FASTA containing two
sequences and a score matrix, perform a global alignment, and print the
resulting alignment matrix and optimal alignment to STDOUT.
"""
import os
import sys
... |
import pandas as pd
import os
import argparse
import re
def is_number(s):
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
def get_... |
__version__ = "0.3.8"
__banner__ = \
"""
# pypyKatz %s
# Author: Tamas Jos @skelsec
# License: MIT
""" % __version__ |
"""Central place for package metadata."""
# NOTE: We use __title__ instead of simply __name__ since the latter would
# interfere with a global variable __name__ denoting object's name.
__title__ = 'crc'
__summary__ = 'Core transcriptional regulatory circuitry analysis'
__url__ = 'https://github.com/linlabcode/CR... |
#!/usr/bin/env python
from napalm_base import get_network_driver
import napalm_yang
import configuration
import json
def pretty_print(data):
print(json.dumps(data, indent=4))
def main():
ios_driver = get_network_driver("ios")
with ios_driver(**configuration.ios) as device:
r = device.yang.ge... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Receive and decode RPN messages.
RPN (registered parameter number) messages are just regular Control Change
messages with a special semantic. To change an RPN value, the sender first
sends the parameter number with CC #100 (LSB) and #101 (MSB) and then the
parameter val... |
import sys,os
sys.path.append(os.getcwd())
# from Process.process import *
from Process.process import *
import torch as th
from torch_scatter import scatter_mean
import torch.nn.functional as F
import numpy as np
from tools.earlystopping import EarlyStopping
from torch_geometric.data import DataLoader
from tqdm import... |
import abc
from bin.contentctl_project.contentctl_core.domain.entities.enums.enums import SecurityContentProduct
from bin.contentctl_project.contentctl_core.domain.entities.security_content_object import SecurityContentObject
from bin.contentctl_project.contentctl_core.domain.entities.enums.enums import SecurityConten... |
# Colormaps for MagellanMapper
# Author: David Young, 2018, 2020
"""Custom colormaps for MagellanMapper.
"""
from enum import Enum, auto
import numpy as np
from matplotlib import cm
from matplotlib import colors
from magmap.settings import config
from magmap.io import libmag
#: Dict[:class:`config.Cmaps`, :obj:`col... |
# -*- 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... |
# 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, software
# distributed unde... |
# conv-kernel.py
# why?: build a resnet with kernel and attention set convolutions
import tensorflow as tf
from .kernel import get_kernel
from tools import concat_1D_coords, log, make_uuid
B, L, K = tf.keras.backend, tf.keras.layers, tf.keras
# todo ... fix one_for_all and all_for_one inside graph_model
SET_OPTIONS... |
from setuptools import setup
setup(name='custom_transforms', version='0.1', scripts=['custom_transforms.py', 'predictor.py']) |
from pathlib import Path
import numpy as np
import open3d as o3d
import torch
from src.data.rgbd import load_rgbd
from src.data.pcd import load_pcd
from .cropping import mask_selection_volume, box_mask_from_rgbd
def preprocess_box_for_cv(img_fpath: Path) -> o3d.geometry.PointCloud:
"""Load and strip walls of bo... |
from collections import OrderedDict
expected = OrderedDict(
[
("type", "figure"),
(
"assets",
[
OrderedDict(
[
("type", "image"),
("doi", u"10.7554/eLife.27041.006"),
... |
import os
import numpy as np
from abc import abstractmethod
from abc import ABCMeta
from typing import Any
from typing import Dict
from typing import Type
from typing import Tuple
from typing import Callable
from typing import Optional
from cftool.misc import Saving
from oneflow.utils.data import Dataset
from oneflow... |
from enginelib import script
import glm
from enginelib.level.reload import reloadable
class CrateSpinner(script.Script):
# allow changes to speed to persist across restarts
savable_attributes = {'speed': 'speed'}
# all scripts are given a reference to the entity they're attached to and the game god obje... |
# Funktion zur Berechnung der Wettpunkte. Die dazu notwendigen Werte
# werden als Integer-Werte an die Funktion übergeben. Das Ergebnis
# wird als Ganzzahlwert zurückgegeben.
def computeBetScore(home, guest, betHome, betGuest):
# bei genauer Voraussage
if home == betHome and guest == betGuest:
# verlass... |
"""A matcher for URLs.
## Basic initialisation
If no arguments are given, a matcher that matches any valid URL will be
initialized:
AnyURL()
There's a good chance you _don't_ want this however, as actual URLs are much
more flexible than you might assume. Basically any string will match.
You can limit what the ... |
import numpy as np
from functions import make_piecewise_linear, PiecewiseFunction, LinearFunction
def link_consumption(T, f, g, M):
L = f(T)
R = g(T)
max_t_idx = np.iinfo(np.dtype('uint32')).max
opt_H = np.full_like(L, float('inf'))
opt_delta_idx = np.full_like(L, max_t_idx, dtype='uint32')
fo... |
#!/bin/python3
import time
'''
Given two string a and b
determine if it's possible to make a equal to b by
1. Capitalize zero or more of a's lowercase letters.
2. Delete all of the remaining lowercase letters in a.
:param a: String 1
:type a: str
:param b: String 2
:type b: str
:return: YES or NO... |
# coding: utf-8
import datetime
import decimal
import json
import re
from .. import config
from .. import engines
from .. import fixtures
from .. import mock
from ..assertions import eq_
from ..assertions import is_
from ..config import requirements
from ..schema import Column
from ..schema import Table
from ... impo... |
import torch.nn as nn
from utils import StochasticDepth
from layers import FeedForward
from CvT import ConvAttention
class CvTBlock(nn.Module):
def __init__(self, embed_dim: int, out_dim: int,
num_heads: int, mlp_ratio: int = 4,
qkv_bias: bool = False, drop: float = 0.,
... |
import pytest
import aiohttp
import aionap
pytestmark = pytest.mark.asyncio
async def test_api_base_url():
api = aionap.API("http://localhost")
assert api._store['base_url'] == "http://localhost"
await api.close()
async def test_api_format():
api = aionap.API("http://localhost")
# default jso... |
from .gradients import *
import logging
__author__ = "Saranraj Nambusubramaniyan"
__version__ = "0.0.3"
logging.basicConfig(level=logging.INFO)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Comunidad',
fields=[
('id', models.AutoField(ve... |
import smbus
from time import sleep
from Adafruit_TCS34725 import TCS34725
import subprocess
import os
import singlepixel_pb2
class SensorReader:
FIRST_MUX_ADDRESS = 0x70 # MUX Address
LAST_MUX_ADDRESS = 0x77
DEVICE_REG_MODE1 = 0x00
DEVICE_REG_LEDOUT0 = 0x1d
COLOR_SENSOR_ADDRESS = 0x29 # Color... |
# Generated by Django 2.2.10 on 2020-04-24 04:57
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0002_tag'),
]
operations = [
migrations.CreateModel(
... |
import logging
from pathlib import Path
from django.core.files.storage import FileSystemStorage
from storages.utils import safe_join, get_available_overwrite_name
log = logging.getLogger(__name__)
class BuildMediaStorageMixin:
"""
A mixin for Storage classes needed to write build artifacts
This adds ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on September 25, 2018
Testing suite for topopy.Flow.get_stream_poi() function
@author: J. Vicente Perez
@email: geolovic@hotmail.com
@date: September 25, 2018
"""
import unittest
import sys
import numpy as np
# Add to the path code folder and data folder
sys.p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.