content stringlengths 5 1.05M |
|---|
"""
Created on 16:58, Apr. 22nd, 2021
Author: fassial
Filename: AlphaSyn.py
"""
import brainpy as bp
__all__ = [
"AlphaSyn",
]
class AlphaSyn(bp.TwoEndConn):
target_backend = "general"
@staticmethod
def derivative(s, x, t, tau):
dxdt = (-2 * tau * x - s) / (tau ** 2)
dsdt = x
... |
import tellcore.constants as const
import json
def __parseDeviceData__(device):
lastCommand = device.last_sent_command(const.TELLSTICK_TURNON | const.TELLSTICK_TURNOFF | const.TELLSTICK_DIM)
return {'id': device.id, 'name': device.name, 'switchedOn': lastCommand == const.TELLSTICK_TURNON}
def __getDevice__(de... |
# Code for custom code recipe acf_amazon_cloud_watch (imported from a Python recipe)
# J.L.G.
# import the classes for accessing DSS objects from the recipe
import dataiku
# Import the helpers for custom recipes
from dataiku.customrecipe import *
# Output dataset, containing the token retrieved from last API call to... |
import responses
import unittest
from tests.support import with_resource, with_fixture, characters
from twitter_ads.account import Account
from twitter_ads.creative import Tweets
from twitter_ads.client import Client
from twitter_ads.cursor import Cursor
from twitter_ads.enum import TWEET_TYPE
from twitter_ads import... |
import os
import urllib2
import time
import multiprocessing.dummy as multiprocessing
import string
from random import choice
import socket
from ctypes import c_int
import tempfile
import dummy
from logger import log
"Smart Downloading Module. Written by Itay Brandes."
shared_bytes_var = multiprocessing.Value(c_int, ... |
def secondhighest(listA):
best = listA[1]
secbest = listA[1]
for i in range(len(listA)):
if listA[i]>secbest:
if listA[i] > best:
secbest = best
best = listA[i]
else:
secbest = listA[i]
return secbest
if __name__ == "__main... |
# Copyright 2020,2021 Sony Corporation.
# Copyright 2021 Sony Group Corporation.
#
# 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 ... |
from setuptools import setup, find_packages
with open('README.rst', encoding='UTF-8') as f:
readme = f.read()
setup(
name='hr',
version='1.0.0',
description='Command line user export utility',
long_description=readme,
author='Your Name',
author_email='your_email@example.com',
packages=fi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 12 08:41:10 2019
@author: yuhanyao
"""
import numpy as np
import pandas as pd
import extinction
from copy import deepcopy
from astropy.io import fits
import astropy.io.ascii as asci
from astropy.table import Table, vstack
from astropy.cosmology impo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
# elevacion de 50mm en 1.5 s
# retorno en 2 s con el esquema de mov cicloidal
# detencion
Ts = [1.5, 2.0, 0.75]
# tiempo total0
SigmaT = 0
for i in range(len(Ts)):
SigmaT += Ts[i]
# tiempo Ti - intervalo
# SigmaT = 4.2... |
# Chap02-03/twitter_get_user_timeline_daterange.py
import sys
import json
from tweepy import Cursor
from twitter_client import get_twitter_client
from argparse import ArgumentParser
from datetime import datetime
from datetime import timezone
def get_parser():
parser = ArgumentParser("Clustering of followers")
... |
"""Parse size notations."""
import re
import spacy
from traiter.const import FLOAT_RE
from traiter.const import INT_RE
from traiter.patterns.matcher_patterns import MatcherPatterns
from traiter.util import to_positive_float
from traiter.util import to_positive_int
from anoplura.pylib.const import COMMON_PATTERNS
from... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: terra/wasm/v1beta1/query.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
fr... |
from django.db import models
# Create your models here.
class Sample_Data(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField(null=True)
|
from PyQt6.QtCore import *
from PyQt6.QtGui import *
class QXPixmap(QPixmap):
"""
extension of QPixmap
contains cached scaled versions
cached grayscaled
cached QIcon
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._cache = {}
def scaled... |
import os
import tarfile
from time import time
import glob
import gdown
folders = {
1999: '1ObZwt6cb97XogQoKu5vQvcnOzeQX4h_5',
2001: '1ishYRAffV0pdos8wufxQwC4y00b89sd4',
2002: '1_yoN_uqIcPv976jTJ3Aqyk1nuOPOaAvP',
2004: '1bnRoWv3jtXTJrd1waVsqiWd-1k24XtyB',
2005: '1... |
import os
import time
import datetime
import numpy as np
import cv2
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
from torch.utils.data import DataLoader
#import network
import segment_network
#import resnet_version
import segment_test_dataset
import segment_utils
import torch.autograd as aut... |
import subprocess
from datetime import datetime
import time
import linecache
while True:
host = []
with open("ip_server.txt") as f:
try:
for line in f:
line = line.rstrip("\n")
line = line.split(",")
host.append(line)
break #para que solo lea la primera l... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2018 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-... |
km = int(input('Qual a distância da viagem(km): '))
'''if km <= 200:
valor = km * 0.50
else:
valor = km * 0.45'''
valor = km * 0.50 if km <= 200 else km * 0.45
print(f'O valor da viagem é R${valor:.2f}') |
from django.conf.urls.defaults import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from test_app.views import Edit
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# u... |
#used as a configuration file
def fan:
pin = 4
dependencies = [“python3”,”gpiozero”]
|
#!/usr/bin/python3
'''
Test harness: this is just a wrapper for qualiatas_test,
adapted for the "other" (or non-Qualitas) suites.
'''
import sys
import os
import qualitas_test as qt
# This is where I put the other suites:
OTHER_ROOT = '/media/passport/bigApps/corpus-python/jese-2018-versions/'
# The name... |
# -*- coding: utf-8 -*-
"""Wrapper for actually running ASCAT"""
from snakemake import shell
__author__ = "Manuel Holtgrewe <manuel.holtgrewe@bihealth.de>"
shell.executable("/bin/bash")
shell(
r"""
set -x
export TMPDIR=$(mktemp -d)
trap "rm -rf $TMPDIR" EXIT
# Also pipe stderr to log file
if [[ -n "{snakemake... |
from collections import defaultdict
dice = defaultdict(int)
for d1 in range(1, 4):
for d2 in range(1, 4):
for d3 in range(1, 4):
dice[d1 + d2 + d3] += 1
player = 0
p1 = 7
p2 = 3
s1 = 0
s2 = 0
universes = defaultdict(int)
universes[(p1, p2, s1, s2)] = 1
q = True
while q:
q = False
nex... |
example = """16,1,2,0,4,2,7,1,2,14"""
import numpy as np
def preprocess (data :str)-> list:
return [int(x) for x in data.split(',')]
def min_fuel(crabs: list) -> int:
crabs = sorted(crabs)
med = crabs[len(crabs)//2]
return sum(abs(x-med) for x in crabs)
crabs = preprocess(example)
min_fuel(crabs=cra... |
import unittest
from checkov.terraform.checks.resource.aws.ECRPolicy import check
from checkov.terraform.models.enums import CheckResult
class TestECRPolicy(unittest.TestCase):
def test_failure(self):
resource_conf = {'repository': ['public_repo'], 'policy': [
'{\n "Version": "2008-10-17"... |
from pyspark import keyword_only
from pyspark.ml.param.shared import HasInputCols
from pyspark.ml.util import DefaultParamsReadable, DefaultParamsWritable
from pyspark.sql import DataFrame
from pyspark.ml import Transformer
from typing import List
class DropColumns(Transformer,
HasInputCols,
... |
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
def convert_from_decimal_larger_bases(number, base):
''' convert any decimal number to a number in a base up to 20'''
strings = "0123456789ABCDEFGHIJ"
result = ""
while number > 0:
digit = number%base
result = strings... |
"""Automatically serve ML model as a REST API"""
__version__ = "0.1.1"
from typing import List, Dict, Union, Callable
import pandas as pd
import sklearn
from flask import Flask
from flask_restful import Api
from scikit_rest.resource import Prediction
from scikit_rest.types import numpy_dict
from scikit_rest.validato... |
"""
The Metric class handles running metrics throughout a simulation.
To define a Metric, it needs only a name and an update function. The update function will access any of:
environment.action_history
meta_vars
environment.state
"""
class Metric(object):
def __init__(self, update_func):
# up... |
# Given a string s and a string array dictionary,
# return the longest string in the dictionary that can be formed by deleting some of the given string characters.
# If there is more than one possible result,
# return the longest word with the smallest lexicographical order.
# If there is no possible result, return t... |
from threading import Lock
from lib.caching.fingerprint import is_similar
from lib.caching.policy import Policy
class TranscriptCache:
def __init__(self, policy: Policy):
self.policy = policy
self.cache = dict()
self.cache_lk = Lock()
def add(self, key: str, value: object) -> None:
... |
from tensorflow.compat.v1 import ConfigProto
from tensorflow.compat.v1 import InteractiveSession
config = ConfigProto(allow_soft_placement=True, log_device_placement=True)
config.gpu_options.allow_growth = True
session = InteractiveSession(config=config)
import tensorflow as tf
import tensorlayer as tl
import time
im... |
# Generated by Django 3.1 on 2021-01-21 11:31
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('pathtests', '0003_auto_20210121_1747'),
('analysis', '0015_auto_20210121_2201'),
('annotation', '0016_one_off_move_ontology'),
]
operations = ... |
from distutils.core import setup
def readme():
with open('README.md') as file:
README = file.read()
return README
setup(
name = 'TOPSIS-Utkarsh-101803613',
packages = ['TOPSIS-Utkarsh-101803613'],
version = '0.1',
license='MIT',
description = 'Topsis Assi... |
"""Add_token_hash_User
Revision ID: b9586e96ee77
Revises: 28fb5b1eaf5d
Create Date: 2018-12-20 16:56:32.260456
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'b9586e96ee77'
down_revision = '28fb5b1eaf5d'
branch_labels = None
depends_on = None
def upgrade():
... |
#!/usr/bin/env python3
import re
import warnings
warnings.simplefilter(action='ignore', category=UserWarning)
import numpy as np
import pandas as pd
import pyranges as pr
from src import logger
from src.query import bam
__all__ = ["Interval", "Regions"]
tag_parser = re.compile(r"(?P<chrom>chr.{1,2}):(?P<start>\d*... |
class OptimizerLog(object):
def __init__(self):
pass
def error(self, errorstring):
pass
def notify(self,what):
pass
|
import os
import random
import ray
from alpha_zero_general import Coach
from alpha_zero_general import DotDict
from alpha_zero_general.coach import ModelTrainer
from alpha_zero_general.coach import ReplayBuffer
from alpha_zero_general.coach import SelfPlay
from alpha_zero_general.coach import SharedStorage
from examp... |
from django.conf import settings
from django.conf.urls import include, url
from django.core import urlresolvers
from django.utils.html import format_html, format_html_join
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailcore import hooks
from wagtail.wagtailadmin.menu import MenuItem
from ... |
#!/usr/bin/env python
from utils.munin.base import MuninGraph
class NBMuninGraph(MuninGraph):
@property
def graph_config(self):
return {
'graph_category' : 'NewsBlur',
'graph_title' : 'NewsBlur Feeds & Subscriptions',
'graph_vlabel' : 'Feeds & Subscribers',
... |
import datetime
import pytest
from jason import props
def test_validates():
assert (
props.Date().load(datetime.date.fromisoformat("1970-01-01")).isoformat()
== "1970-01-01"
)
def test_true_from_string():
assert props.Date().load("1970-01-01").isoformat() == "1970-01-01"
def test_fro... |
from .base_request import BaseRequest
from .token import Token
from .settings import Settings
from . import exceptions
class Auth(object):
"""
This class implements all authentication functions for Resin Python SDK.
"""
def __init__(self):
self.base_request = BaseRequest()
self.setti... |
# This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
from pkg_resources import parse_version
import kaitaistruct
from kaitaistruct import KaitaiStruct, KaitaiStream, BytesIO
if parse_version(kaitaistruct.__version__) < parse_version('0.9'):
raise Exception("Incompati... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(name='ibmBluegroup',
version='1.05',
description="IBM Bluegroup API",
packages=find_packages(),
keywords='Bluegroup',
author='ThomasIBM',
author_email='guojial@cn.ibm.com',
... |
import sys
from base64 import b64encode, b64decode
class base_conv(object):
def __init__(self):
self.chars = 'abcdefghijklmnopqrstuvwxyz'
self.base = len(self.chars)
self.splitter = "!"
self.debug = False
@staticmethod
def base_alpha_encode(chars, base, binary):
enc... |
# -*- coding: utf-8 -*-
from openprocurement.auctions.core.utils import (
opresource,
)
from openprocurement.auctions.insider.views.other.question import (
AuctionQuestionResource,
)
@opresource(name='dgfFinancialAssets:Auction Questions',
collection_path='/auctions/{auction_id}/questions',
... |
import pafy
import tkinter as tk
root = tk.Tk()
root.title("youtube-py-dl")
canvas = tk.Canvas(root, width=400, height=200, relief='raised')
canvas.pack()
label = tk.Label(root, text='Enter YouTube URL')
label.config(font=('verdana', 12))
canvas.create_window(200, 100, window=label)
entry = tk.Entry(root)
canvas.cr... |
import psycopg2
import json
#
from bridgebots import Deal
class HandDao:
def __init__(self):
self.connection = psycopg2.connect("dbname=bridge user=bridgebot host=localhost password=bidslam")
def close(self):
self.connection.close()
def get_processed_files(self):
with self.conne... |
import os
import sys
from glob import glob
sys.path.append(os.path.dirname(os.path.realpath(os.path.dirname(__file__))))
import torch
import torch.backends.cudnn as cudnn
from torch.utils.tensorboard import SummaryWriter
import numpy as np
from arguments import get_args
from dataloader import get_dataloader
from rel... |
from .problem import Problem
from .submission import Submission
from .user import User
|
from django.test.testcases import TestCase
from dbfiles.models import DBFile
class DBFileTests(TestCase):
def test_db_file_save(self):
content = b"Hello World!"
name = "my-files/hello-world.txt"
db_file = DBFile.objects.create(content=content, name=name)
self.assertEqual(db_file... |
# LIBTBX_SET_DISPATCHER_NAME dxtbx.show_mask_info
import argparse
import sys
import dxtbx.util
from dxtbx.model.experiment_list import ExperimentListFactory
def run(args=None):
dxtbx.util.encode_output_as_utf8()
parser = argparse.ArgumentParser()
parser.add_argument("filenames", metavar="IMAGE", nargs="... |
# coding: utf-8
# In[ ]:
#练习一:文本加密解密(先看有关ASCII码的相关知识以及码表,查维基百科或百度百科)
#输入:一个txt文件(假设全是字母的英文词,每个单词之间用单个空格隔开,假设单词最长为10个字母)
#加密:得到每个单词的长度 n ,随机生成一个9位的数字,将 n-1 与这个9位的数字连接,形成一个10位的数字,
#作为密匙 key 。依照 key 中各个数字对单词中每一个对应位置的字母进行向后移位(例:如过 key 中某数字为 2 ,
#对应该位置的字母为 a ,加密则应移位成 c ,如果超过 z ,则回到 A 处继续移位),对长度不到10的单词,移位后,
#将移位后的单词利用随机字母... |
#!/usr/bin/env python
# Copyright 2018 Xiaohui Zhang
# Apache 2.0.
from __future__ import print_function
from collections import defaultdict
import argparse
import sys
import math
def GetArgs():
parser = argparse.ArgumentParser(
description = "Use a greedy framework to select pronunciation candidates"
... |
import sys, time
from django.conf import settings
from django.db import connection, transaction, backend
from django.core import management
from django.dispatch import dispatcher
from django.test import signals
from django.template import Template
# The prefix to put on the default database name when creating
# the te... |
from django.db import models
# Create your models here.
class Question(models.Model):
question_title = models.CharField(max_length=200)
question_text = models.TextField()
active = models.BooleanField(default=True)
def __str__(self):
return self.question_text
class Choice(models.Model):
qu... |
import unittest
from typing import List
from cave_navigator import CaveNavigator
class TestCaveNavigator(unittest.TestCase):
def setUp(self) -> None:
pass
def test_cave_navigator_small_sample(self) -> None:
lines = file_read_helper('day-12/small_sample_input.txt')
cave_navigator = Cav... |
# entry point for the input form to pass values back to this script
def setValues(tH0,tWM,tWV,tz,tmnue,tmnumu,tmnutau,tw,twp,tT0):
H0 = tH0
h = H0/100
WM = tWM
WV = tWV
z = tz
WR = 2.477E-5/(h*h) # does not include neutrinos, T0 = 2.72528
WK = 1-WM-WR-WV
mnue = tmnue
mnumu = tmnumu
mnutau = tmnutau... |
import logging
import re
import sys
from framework.mongo import database
from website.app import init_app
from framework.transactions.context import TokuTransaction
from scripts import utils as script_utils
logger = logging.getLogger(__name__)
def get_targets():
guids = [
x['_id']
for x in datab... |
#=========================================================================
# RegIncr
#=========================================================================
# This is a simple model for a registered incrementer. An eight-bit value
# is read from the input port, registered, incremented by one, and
# finally written t... |
def rasterize_mesh_from_barycentric_coordinate_images(
mesh, bcoords_image, tri_indices_image
):
r"""
Renders an image of a `menpo.shape.TexturedTriMesh` or
`menpo.shape.ColouredTriMesh` from a barycentric coordinate image pair.
Note that the texture is rendered without any lighting model - think o... |
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
__version__ = '0.10.2'
__version_info__ = (0, 10, 2)
|
# -------------------------------------------------------------
# generic_display.py - Implements an interface for all the display classes
# August 2018 - Andrei Diaconu
# -------------------------------------------------------------
__all__ = ("GenericDisplay",)
from typing import NamedTuple
class GenericDisplay:
... |
'''
给定两个大小为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的中位数。
O(log(m+n))算法
'''
|
import os
import torch
from collections import OrderedDict
import argparse
import numpy as np
eps_bn = 1e-5 #default epsilon for bn
mean_rgb = {
"": [0.0, 0.0, 0.0],
"pascal": [103.939, 116.779, 123.68],
"cityscapes": [0.0, 0.0, 0.0],
"railsem19": [0.0, 0.0, 0.0],
"vistas": [80.... |
import json
import os
from datetime import datetime
from datetime import timedelta
import airflow
import urllib3
from airflow import DAG
from airflow.models import Variable
from airflow.operators.dummy import DummyOperator
from airflow.operators.python import BranchPythonOperator
from airflow.operators.python import P... |
n = int(input())
fib = lambda n: 0 if n == 0 else 1 if n == 1 else fib(n-1) + fib(n-2)
print(fib(n)) |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from msccl.language import *
def allreduce_allpairs(size):
# Each rank sends the nth chunk to the nth rank into scratch space
for r1 in range(size):
for r2 in range(size):
if r1 != r2:
index = r2 * siz... |
import pytest
from django.urls import reverse
from core.logic.serialization import b64json
from organizations.models import UserOrganization
from test_fixtures.scenarios.basic import users # noqa
@pytest.mark.django_db
class TestSlicerAPI:
def test_primary_dimension_required(self, flexible_slicer_test_data, ad... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
The Model Zoo.
This file contains a list of all the models in the model zoo, the path to
load them, agents & tasks ... |
import copy
from pgdrive.constants import TerminationState
import logging
import os
import sys
from panda3d.bullet import BulletBodyNode
def import_pygame():
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame
return pygame
def setup_logger(debug=False):
logging.basicConfig(
lev... |
import numpy as np
import sys
sys.path.append('../')
from interpolate import get_gradient, _bin_and_index
three_colors = ['#ffffff', '#000000', '#ff0000']
two_colors = ['#ffffff', '#000000']
equal = np.testing.assert_array_equal
close_enough = np.testing.assert_allclose
def test_bin_lower():
value = 0.3
s... |
# Generated by Django 2.0.4 on 2018-04-03 19:50
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('recipes', '0002_auto_20180403_1907'),
]
operations = [
migrations.AddField(
model_name='recipe',
nam... |
'''
This module contains all functions relating to feature engineering
'''
import datetime as dt
import re
import platform
import pandas as pd
import numpy as np
if platform.system() == "Darwin":
import matplotlib as plt
plt.use('TkAgg')
else:
import matplotlib.pyplot as plt
import seaborn as sns
from .s... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from tapi_server.models.base_model_ import Model
from tapi_server.models.tapi_common_capacity import TapiCommonCapacity # noqa: F401,E501
from tapi_server import util
... |
import unittest
class TestIngest(unittest.TestCase):
return True
if __name__ == '__main__':
unittest.main() |
import logging
from Pegasus.db.admin.admin_loader import DBAdminError
from Pegasus.db.admin.versions.base_version import BaseVersion
DB_VERSION = 13
log = logging.getLogger(__name__)
class Version(BaseVersion):
def __init__(self, connection):
super().__init__(connection)
def update(self, force=Fal... |
""" Tests for asset pull """
import logging
import mock
import os
import sys
if sys.version_info.major < 3:
ConnectionRefusedError = Exception
else:
from urllib.error import HTTPError
import pytest
from refgenconf.const import *
from refgenconf.exceptions import *
from refgenconf.refgenconf import _download_ur... |
from __future__ import absolute_import
from collections import namedtuple
Observations = namedtuple('Observations', 'x y')
|
import unittest
from katas.kyu_7.bouncy_numbers import is_bouncy
class IsBouncyTestCase(unittest.TestCase):
def test_true_1(self):
self.assertTrue(is_bouncy(101))
def test_true_2(self):
self.assertTrue(is_bouncy(120))
def test_true_3(self):
self.assertTrue(is_bouncy(2351))
... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
"""
Run the test cases for the excercise as unittests.
"""
import unittest
from solution import solve
class Test(unittest.TestCase):
def test_case_1(self):
n = 4
k = 1
ar = [3, 10, 2, 9]
b = 12
answer = 5
self.assertEqual(answer, solve(n, k, b, ar))
def test... |
import board
import busio
import adafruit_bd3491fs
i2c = busio.I2C(board.SCL, board.SDA)
bd3491fs = adafruit_bd3491fs.BD3491FS(i2c)
bd3491fs.active_input = adafruit_bd3491fs.Input.A
bd3491fs.input_gain = adafruit_bd3491fs.Level.LEVEL_20DB
bd3491fs.channel_1_attenuation = 0
bd3491fs.channel_2_attenuation = 0... |
from django.urls import path
from .views import chapter_form, ChapterFormView
app_name = 'warhammer'
urlpatterns = [
path('', chapter_form, name='chapter_form'),
]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @FileName :__init__.py.py
# @Author :Lowell
# @Time :2022/3/30 08:59
import importlib
import os
import time
import warnings
from pathlib import Path
from django.conf import global_settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.de... |
#-*- coding: utf-8 -*
#
# Copyright 2011 shuotao.me
# Copyright 2012 msx.com
# by error.d@gmail.com
# 2011-10-9
#
# Sputnik Database Object
# 提供了对*关系*数据库操作的接口,并且对cache的使用进行了封装
# sql语句拼装
# 对象关系映射(ORM),只支持Mysql
#
# ToDoList:
# 支持force index(key) 2012-3-17
# find调用时支持[x:x](limit)
# find的参数直接支持字段,find(id=x,name=x)
# ... |
from ..utils import Object
class UpdateTermsOfService(Object):
"""
New terms of service must be accepted by the user. If the terms of service are declined, then the deleteAccount method should be called with the reason "Decline ToS update"
Attributes:
ID (:obj:`str`): ``UpdateTermsOfService``
... |
import PIL
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
# font = ImageFont.truetype("Arial-Bold.ttf",14)
font = ImageFont.truetype("Arial.ttf",14)
img=Image.new("RGBA", (500,250),(255,255,255))
draw = ImageDraw.Draw(img)
draw.text((0, 0),"This is a test",(0,0,0),font=font)
draw = ImageDraw... |
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# return sorted(t) == sorted(s)
# return Counter(t) == Counter(s)
if len(s) != len(t):
return False
a, b = {}, {}
for i in range(len(s)):
a[s[i]] = a.get(s[i], 0) + 1
b[t[i]] = b.... |
# MIT License
#
# (C) Copyright [2020] Hewlett Packard Enterprise Development LP
#
# 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 righ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import subprocess
import linecache
import click
# Number of problems present in problems.txt
TOTAL_PROBLEMS = 202
def get_filename(problem):
"""Returns filename in the form `001.py`"""
return '{:03d}.py'.format(problem)
def get_solution(p... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 25 21:55:18 2020
@author: admangli
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
dataset = pd.read_csv('Mall_Customers.csv')
print(dataset.head())
X = dataset.iloc[:, 3:].values
#%%
# Convert categorical variables
fro... |
from seperation import seperate
#vriski to pinaka A and C, pairnei to arxeio kai to analyei se grammes
#stelnei tin kathe seira sto seperation kai auto to gyrnaei se pinaka X
#analogos pou vriskomaste p.x. stin grammi 1 oi pinakes C=X
#gia ton pinaka A , stelnoyme kathe grammi sto seperation kai otan gyrnaei pisw kano... |
from abc import ABC, abstractmethod
from typing import Optional
import base64
import hashlib
import re
import requests
from . import exceptions
from .parse.html import find_scripts
class RouterInterface(ABC):
@abstractmethod
def page(self, name: str, params: Optional[dict] = None) -> str:
pass
cla... |
from django.apps import apps
from django.conf import settings
from django.test import TestCase, override_settings
from django.utils import translation
from localized_fields.fields import LocalizedField
from localized_fields.value import LocalizedValue
from .fake_model import get_fake_model
@override_settings(LOCALI... |
from typing import *
import numpy as np
from .common import BIO
class BIOSmoothing:
def __init__(
self,
b_smooth: float = 0.0,
i_smooth: float = 0.0,
o_smooth: float = 0.0,
weight: float = 1.0
):
self.smooth = [b_smooth, i_smooth, o_smooth]
... |
# -*- coding: utf-8 -*-
from api.base.settings.defaults import API_BASE
from api.citations.utils import display_absolute_url
from nose.tools import * # flake8: noqa
from osf_tests.factories import AuthUserFactory, PreprintFactory
from tests.base import ApiTestCase
class PreprintCitationsMixin(object):
def setUp(se... |
#!/usr/bin/env python
import sys
from cvangysel import argparse_utils, \
logging_utils, multiprocessing_utils, pyndri_utils, trec_utils, rank_utils
import sesh
from sesh import domain, scorers, sesh_pb2
import google.protobuf as pb
import argparse
import codecs
import collections
import io
import logging
impor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.