content stringlengths 5 1.05M |
|---|
from flask_api import FlaskAPI
from flask import request
from dbutils import init, getDiseases, destroy
from classifier import classifier
app = FlaskAPI(__name__)
@app.route('/')
def example():
return "API For Health APP"
@app.route('/api/analyse', methods=['POST'])
def analyze():
body = request.data
db... |
from picamera import PiCamera
from time import sleep
camera = PiCamera()
camera.start_preview()
camera.start_recording('/home/pi/Desktop/video.h264')
sleep(5)
camera.stop_recording()
camera.stop_preview()
|
from typing import List
import click
from nsf_ssh_auth_dir.cli.arguments import cli_ssh_group_id_argument
from nsf_ssh_auth_dir.cli.options import (
cli_device_state_always_flag,
cli_device_state_on_option,
cli_device_user_from_any_flag,
cli_device_user_from_option,
cli_device_user_to_all_flag,
... |
"""
direct.py
under pytracer.integrator.surface package
Models direct lighting integrator
Created by Jiayao on Aug 9, 2017
"""
from __future__ import absolute_import
from enum import Enum
from pytracer import *
import pytracer.geometry as geo
from pytracer.integrator.surface import SurfaceIntegrator
__all__ = ['Lig... |
from __future__ import division
from collections import defaultdict, OrderedDict
import re
import numpy as np
# To look up a 2-tuple of (bond energy in kJ/mol / bond order in Angstrom):
# Do BondEnergies[Elem1][Elem2][BO]
BondEnergies = defaultdict(lambda:defaultdict(dict))
## Covalent radii from Cordero et al. 'Cova... |
import unittest
import tensorflow as tf
import numpy as np
from cossmo.dna_encoder import dna_encoder
class TestDnaEncoder(unittest.TestCase):
def setUp(self):
self.seq_ = tf.placeholder(tf.uint8)
self.enc_dna_op = dna_encoder(self.seq_)
self.sess = tf.Session()
self.sess.run(tf.gl... |
import datetime
import logging
from typing import *
import pandas as pd
from .BackendClients.corona_warn_app import CoronaWarnAppBackendClient
from .BackendClients.dp3t import DP3TBackendClient
from .BackendClients.immuni import ImmuniBackendClient
from .BackendClients.smitte_stop import SmitteStopBackendClient
from ... |
__author__ = "Poonam Yadav"
__copyright__ = "Copyright 2017, The Databox Project"
__credits__ = ["Databox team"]
__license__ = "GPL"
__version__ = "0.0.1"
__maintainer__ = "Poonam Yadav"
__email__ = "p.yadav@acm.org"
__status__ = "Development"
import urllib3
import os
import json
import base64
from urllib.parse import... |
# rooms are a truple of (room, x, y)
class Exit:
def __init__(self, from_room, to_room):
self.connections = [from_room, to_room]
|
import logging
from typing import TYPE_CHECKING, Any, Optional, Union
from requests import Response
log = logging.getLogger(__name__)
if TYPE_CHECKING: # pragma: no cover
from globus_sdk.base import BaseClient
class GlobusHTTPResponse:
"""
Response object that wraps an HTTP response from the underlyin... |
# Copyright 2020 nunopenim @github
#
# Licensed under the DBADPL-B (Don't Be A Dick Public License B), v1.0
#
# You may not use this file or any of the content within it, unless in
# compliance with the DBADPL-B (So use it freely, but if you make a
# shitload of cash, buy me a beer or a pizza. Thanks.
from us... |
import csv
import json
import xml.etree.ElementTree as ElementTree
from typing import TextIO, NoReturn
from abc import ABC
class Reader(ABC):
data = []
def get_data(self, file_path):
pass
def _parse_file(self, file):
pass
class CSVReader(Reader):
def get_data(self, file_path: str)... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
import argparse
from mmap import *
from pathlib import Path
from ctypes import *
import re
from .common import *
class Icon(BigEndianStructure):
_pack_ = 1
_fields_ = [("x_0", c_uint8),
("y_0", c_uint8),
("x_8", c_uint32, 2),
("y_8", c_uint32, 2),
... |
from commandPattern.ICommand import ICommand
class Command1(ICommand):
def __init__(self, excuter):
self.excuter = excuter
def excute(self):
self.excuter.do_something1()
|
from unit_test_common import execute_csv2_request, initialize_csv2_request, ut_id, generate_secret, sanity_requests
from sys import argv
def main(gvar):
if not gvar:
gvar = {}
if len(argv) > 1:
initialize_csv2_request(gvar, selections=argv[1])
else:
initialize_csv2_r... |
import os
import pytest
from numpy.testing import (
assert_, run_module_suite, assert_allclose, assert_equal)
import numpy as np
from qutip_qip.device.processor import Processor
from qutip import (basis, sigmaz, sigmax, sigmay, identity, destroy, tensor,
Options, rand_ket, rand_dm, fidelity)
from ... |
from __future__ import absolute_import, unicode_literals
import re
import sys
import pytest
from virtualenv.__main__ import run_with_catch
from virtualenv.util.error import ProcessCallFailed
from virtualenv.util.subprocess import Popen, subprocess
def test_main():
process = Popen([sys.executable, "-m", "virtua... |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 ... |
###############################################################################
# ProteusLib Copyright (c) 2021, The Regents of the University of California,
# through Lawrence Berkeley National Laboratory, Oak Ridge National
# Laboratory, National Renewable Energy Laboratory, and National Energy
# Technology Laborator... |
# SPDX-License-Identifier: MIT
# Copyright (C) 2021 Roland Csaszar
#
# Project: Buildnis
# File: __init__.py
# Date: 13.Feb.2021
###############################################################################
__all__ = [
"PROJECT_FILE_NAME",
"MODULE_FILE_NAME",
"BUILD_FILE_NAME",
"HOST_FILE_NA... |
# Generated by Django 3.2.7 on 2021-09-04 10:51
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='jobInfo',
fields=[
... |
import sys
import os
from unittest import TestCase
from icon_cisco_firepower_management_center.actions.check_if_address_in_group import CheckIfAddressInGroup
from icon_cisco_firepower_management_center.actions.check_if_address_in_group.schema import Input
from unit_test.util import Util
from unittest.mock import patch... |
import uuid
import os
import time
import datetime
import json
# Python 3
class Parallelbug:
dir = None
settings = {
"format": "json",
"meta": True,
"meta_key": "__meta__",
"date_format": "%Y-%m-%d %H:%M:%S",
"append": False,
"data_key": "dump",
"append_group_key": "__append_group__"
}
@staticmethod... |
# -*- coding: utf-8 -*-
'''
Chirp Text - Minimalist Text Processing Library
'''
# This code is a part of chirptext library: https://github.com/letuananh/chirptext
# :copyright: (c) 2012 Le Tuan Anh <tuananh.ke@gmail.com>
# :license: MIT, see LICENSE for more details.
#################################################... |
'''This is a sample configuration file for gentea.py
Each true configuration file is tailored to a specific input map.
'''
database = {
'user' : 'myusername',
'passwd' : 'mypassword',
'host' : 'database_host_ip',
'port' : 'db_port',
'sid' : 'database_sid'
}
input_image = (r'C:\Proj... |
# Copyright (C) 2021 TU Dresden
# Licensed under the ISC license (see LICENSE.txt)
#
# Author: Robert Khasanov
from dataclasses import dataclass
from mocasin.simulate.manager import (
ManagerStatistics,
ManagerStatisticsApplicationEntry,
)
@dataclass
class FiveGManagerStatisticsApplicationEntry(ManagerStati... |
from command_handler import (handle_put, handle_delete)
def test_handle_delete_key_exists():
key, value = 'TEST', 1
handle_put(key, value)
operation_status, msg = handle_delete(key)
assert operation_status is True
assert msg == "Key [TEST] deleted"
def test_handle_delete_key_does_not_exists():
... |
#!/usr/bin/env python3
from typing import Dict, Callable
from wikidata_tree_generator.macros.property_meta import PropertyMeta, ExtractMethod
from wikidata_tree_generator.macros.wikidata import wikidata_entities, Sex
from wikidata_tree_generator.models import Date
from wikidata_tree_generator.models.place import Coord... |
import numpy as np
import cv2
import matplotlib.pyplot as plt
import torch
from skimage import metrics
from contourlet import filters, operations, sampling, transform
if __name__ == '__main__':
device = 'cpu'
img = cv2.imread(r'E:\Project_DL\NCKH_GUI_app\img_test\lol_dataset\eval15\high\1.png')
# img = c... |
from Module import AbstractModule
class Module(AbstractModule):
def __init__(self):
AbstractModule.__init__(self)
def run(
self, network, antecedents, out_attributes, user_options, num_cores,
out_path):
import os
from genomicode import config
from genomicode imp... |
"""Tests for Philips Hue config flow."""
import asyncio
from unittest.mock import patch
import aiohue
import pytest
import voluptuous as vol
from homeassistant.components import hue
from tests.common import MockConfigEntry, mock_coro
async def test_flow_works(hass, aioclient_mock):
"""Test config flow ."""
... |
from collections import defaultdict
import pandas as pd
import matplotlib.pyplot as plt
import random
def word_cloud(dict_word_size):
random.seed(46)
from wordcloud import WordCloud
dict_word_size = {k:5+v for k,v in dict_word_size.items() if v}
wc = WordCloud(stopwords=[], color_func=lambda *_, **a: r... |
# Auto generated by generator.py. Delete this line if you make modification.
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
XPATH = {
'name' : "//h1",
'price' : "//div[@class='product-price-pomotion']/p[@class='price']",
'category' : "//div[@class='product-category-path']/u... |
# This file contains (modified) parts of the codes from the following repository:
# https://github.com/matterport/Mask_RCNN
#
# Mask R-CNN
#
# The MIT License (MIT)
#
# Copyright (c) 2017 Matterport, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated ... |
# -*- encoding: utf-8 -*-
"""
@Author : zYx.Tom
@Contact : 526614962@qq.com
@site : https://zhuyuanxiang.github.io
---------------------------
@Software : PyCharm
@Project : Dive-into-Deep-Learning
@File : sec0202.py
@Version : v0.1
@Time : 2020-12-27 9:25
@License ... |
from rest_framework import generics, permissions
from .models import News, Category
from .serializers import NewsSerializer, CategorySerializer
class NewsList(generics.ListCreateAPIView):
queryset = News.objects.all()
serializer_class = NewsSerializer
class NewsDetail(generics.RetrieveUpdateAPIView):
q... |
#** O python segue uma ordem especifica para percorrer a hierarquia de classes, e essa ordem é chamada de MRO. Com a ordem da esquerda para a direita
#** toda classe tem um atributo _mro_ que podemos acessar atraves do metodo mro() - da classe atual até a classe object.
"""
Metodos especiais
* os metodos especiais ... |
from metaphor.common.cli import cli_main
from .extractor import TableauExtractor, TableauRunConfig
if __name__ == "__main__":
cli_main("Tableau metadata extractor", TableauRunConfig, TableauExtractor)
|
import cv2
from os import listdir
from os.path import isfile, join, splitext
path = "E:\\companies_house_project\\files\\data\\chp_stamps_20200319\\"
def import_files(directory):
"""
Returns list of all files present in given directory, complete with file extensions.
Arguments:
directory: sou... |
import pytest
import logging
import textwrap
from copy import deepcopy
import xml.etree.ElementTree as ET
from pytmc import Symbol, DataType, SubItem
from pytmc.xml_obj import BaseElement, Configuration
from pytmc import TmcFile
from pytmc.xml_collector import ElementCollector, TmcChain, BaseRecordPackage
from pytmc.... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
__all__ = ["transI_fusebn", "transII_addbranch", "transIII_1x1_kxk",
"transIV_depthconcat", "transV_avg", "transVI_multiscale", "DBBORIGIN", "DBB1x1", "DBBAVG", "DBB1x1kxk"]
#######################
# auxiliary operation ... |
from collections import deque, namedtuple
from copy import copy
from math import cos, radians
from itertools import chain, islice
from functools import reduce
from operator import mul
from model.Car import Car
from model.Game import Game
from model.Move import Move
from model.World import World
from model.CarType impor... |
import datetime
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras import backend as K
# a set of auxiliary functions to read dataset
def exel2dict(filename):
xls = pd.ExcelFile(filename)
df = xls.parse(xls.she... |
from launchy import Launchy
from ..app import logger
from ..model.database import Session
from ..model.build import Build
from ..model.chroot import Chroot
from ..molior.queues import enqueue_task
async def CreateBuildEnv(chroot_id, build_id, dist,
name, version, arch, components, repo_url, ... |
import os
import re
import subprocess
import numpy as np
__author__ = 'Guillermo Avendano Franco'
def get_point_group(st, executable='symmol', dcm=0.2, dcme=0.2):
if not cmd_exists(executable):
return 'no symmol'
wf = open('symmol.in', 'w')
wf.write(' %9.5f %9.5f %9.5f %9.5f %9.5f %9.5f\n' % (1... |
from copy import deepcopy
import pytest
from traw.models import Priority
ID = 1234
IS_DEFAULT = True
NAME = '1 - mock priority'
PRIORITY = 1
SHORT_NAME = '1 - mock'
@pytest.fixture()
def priority(client):
content = {"id": ID,
"is_default": IS_DEFAULT,
"name": NAME,
... |
from unittest import TestCase
from pascal_triangle import generate, getRow
class Test(TestCase):
def test_generate(self):
self.assertTrue(generate(1) == [[1]])
self.assertTrue(generate(2) == [[1], [1, 1]])
self.assertTrue(generate(3) == [[1], [1, 1], [1, 2, 1]])
self.assertTrue(gene... |
def hoop_count(n):
if n >= 10: return "Great, now move on to tricks"
if n < 10: return "Keep at it until you get it" |
import matplotlib.pyplot as plt
import numpy as np
from qm import SimulationConfig
from qm.qua import *
from qm.QuantumMachinesManager import QuantumMachinesManager
from configuration import *
all_elements = ["sensor", "sample", "memory"]
N_avg = 100
N_SSR = 10 # Should be increased
hf_splitting = 1.5e6 # ... |
import turtle
akash = turtle.Turtle()
turtle.bgcolor("black")
akash.speed(100)
akash.pencolor('#ffffe6')
akash.pensize(0.2)
area = 0
while area < 430:
akash.forward(2+area)
akash.right(90.899)
area = area + 1
turtle.done() |
from __future__ import print_function
import math
import scipy
import matplotlib.pyplot as plt
# these are the depth and width of the LED module in inches
posDataOutFile = 'pos_data.txt'
edgDataOutFile = 'edg_data.txt'
plot = False
numPanels = 18
numRemove = 6
numPins = 15
panelWidth = 40.0/25.4 + 0.01
panelDepth = ... |
from __future__ import print_function
n = 2**1000
r = 0
while n:
r, n = r + n % 10, n // 10
print(r)
|
"""
The following function will iterate all of the CloudFormation stacks
within a given region. It will then call the detect_stack_drift API
for each stack which will update the status within the CloudFormation
console.
"""
import json
import boto3
import logging
from botocore.exceptions import ClientError
"""Set up ... |
# This files contains your custom actions which can be used to run
# custom Python code.
#
# See this guide on how to implement these action:
# https://rasa.com/docs/rasa/custom-actions
# This is a simple example for a custom action which utters "Hello World!"
from typing import Any, Text, Dict, List
from rasa_sdk ... |
from __future__ import absolute_import, division, print_function
from enum import Enum
MACAlgorithm = Enum('MACAlgorithm', ['null', 'hmac_md5', 'hmac_sha1', 'hmac_sha256', 'hmac_sha384', 'hmac_sha512'],
start=0)
CipherType = Enum('CipherType', ['stream', 'block', 'aead'])
class ProtocolVersion(... |
# Created by lan at 2021/1/2
import os
import re
from enum import Enum
import yaml
from definitions import ROOT_DIR
empty_cell_values = ['', '-', 'n/a', 'null', '.', '..', '...', 'x', 'X', '#', 'NaN', 'NA']
hard_empty_cell_values = ['']
class AggregationOperator(Enum):
SUM = 'Sum'
SUBTRACT = 'Subtract'
... |
# Copyright (c) Jeremías Casteglione <jrmsdev@gmail.com>
# See LICENSE file.
import bottle
from pytest import raises
from unittest.mock import Mock
from _sadm.devops.wapp.auth.error import AuthError
from _sadm.devops.wapp.plugin import auth
from _sadm.devops.wapp.view import view
def test_plugin(devops_wapp):
wapp... |
import numpy as np
import training_config
class RGBConverter(object):
def __init__(self):
pass
def __call__(self, img):
# convert to RGB : stack 3 identical planes
img = np.stack((img,) * 3, axis=1)
# normalize for image-net weights
for i in range(img.shape[0]):
... |
print("hihihiih")
|
# purpose: top level script to evaluate an existing model on the test data and compute accuracy.
import os, sys, math
import random
import torch
import torch.nn as nn
from torch.autograd import Variable
import data
import imp
train = imp.load_source('reasonE.train', 'reasonE.train.py')
modelEval = imp.load_source('... |
#!/usr/bin/env python3
import argparse
import boto3
from datetime import datetime, timedelta
import logging
import reprlib
smart_repr = reprlib.Repr().repr
def main():
p = argparse.ArgumentParser()
p.add_argument('--verbose', '-v', action='store_true')
p.add_argument('--remove', '-r', action='store_tru... |
"""
Copyright (c) 2020 COTOBA DESIGN, Inc.
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, distri... |
from typing import List
from settings import val_maps
from valorant.map import Map
class MapPool:
"""
Represents a VALORANT Map Pool
"""
def __init__(self):
# map list
self.maps: List[Map] = []
# loops through the map from settings
for val_map in val_maps:
... |
import dmri.preprocessing as prep
import yaml,os
from pathlib import Path
logger=prep.logger.write
### utilities
def find_fsl(lookup_dirs=[]):
fsldir=os.environ.get('FSLDIR')
candidates=[]
if fsldir is not None:
fsldir=Path(fsldir)
candidates.append(fsldir)
else:
candidates... |
import unittest
import pysony
class TestBasics(unittest.TestCase):
def test_loadpysony(self):
api = pysony.SonyAPI()
self.assertEqual(api.QX_ADDR, 'http://10.0.0.1:10000')
|
from comment import Comment
class BaseMeta:
def __init__(self, meta):
self.obj = meta
def get_type(self):
return self.obj["@type"]
def get_page(self):
return self.obj["mainEntityofPage"]["@id"]
def get_name(self):
return self.obj["name"]
def get_de... |
VCF_BY_CHROMOSOME = """\
select
id,
chromosome,
position,
reference,
alternative
from
vcfs
where
chromosome = '{chromosome}'
order by
position"""
RELATED_SAM = """\
select
id,
rname,
pos,
length,
end_pos,
cigar,
seq
from
sams
where
rname = '{chromosome}' and
pos < {position} and
e... |
import argparse
import numpy as np
import os
import pickle
# Calculates forgetting statistics per example
#
# diag_stats: dictionary created during training containing
# loss, accuracy, and missclassification margin
# per example presentation
# npresentations: number of training epochs
#
# R... |
#-------------------------------------------------------------------------------
# This script displays five screens :
# 1. First screen displays the logo.
# 2. Second screen has bitcoin price and satoshis per unit of the currency.
# 3. Third screen has Mempool information.
# 4. Fourth screen has the curren... |
import numpy
def select_threshold(yval, pval):
"""
Find the best threshold (epsilon) to use for selecting outliers based
on the results from a validation set and the ground truth.
Parameters
----------
yval : array_like
The validation dataset of shape (m x n) where m is the number
... |
# Copyright 2021 Adobe
# All Rights Reserved.
# NOTICE: Adobe permits you to use, modify, and distribute this file in
# accordance with the terms of the Adobe license agreement accompanying
# it.
'''
>> python -m unittest unit_test.TestSingle_operator
'''
from skimage import io
import time
import beacon_aug as BA
# ... |
import pystache as pystache
from .entfunc import * # NOQA
import pytest
ACK_ACCESS_KEY = os.environ.get('RANCHER_ALIYUN_ACCESS_KEY', "")
ACK_SECRET_KEY = os.environ.get('RANCHER_ALIYUN_SECRET_KEY', "")
ackcredential = pytest.mark.skipif(not (ACK_ACCESS_KEY and ACK_SECRET_KEY),
re... |
########################################
# MIT License
#
# Copyright (c) 2020 Miguel Ramos Pernas
########################################
'''
Definition of classes to evaluate FCNs using PDFs and data sets.
'''
from . import fcns
from ..base import core
from ..base import exceptions
from ..base import parameters
from ... |
import uuid
import datetime
from flask import session
from common.database import Database
from models.blog import Blog
class User(object):
# the main variable in user model
def __init__(self, email, password, _id=None):
self.email = email
self.password = password
self._id = uuid.uuid... |
from __future__ import print_function
import argparse
import os
import time
import torch
import torch.backends.cudnn as cudnn
import numpy as np
import skimage
import torch.cuda as ct
from net_builder import SUPPORT_NETS, build_net
from losses.multiscaleloss import multiscaleloss
import torch.nn.functional as F
import... |
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import path, include
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
# from two_factor.urls import urlpatterns as tf_urls
# from two_factor.gateways.twilio.urls import urlpatterns as tf_twilio_u... |
'''
Test Runbooks.py cache_runbooks()
'''
import mock
import unittest
from runbooks import cache_runbooks
class CacheRunbooksTest(unittest.TestCase):
''' Run unit tests against the cache_runbooks method '''
def setUp(self):
''' Setup mocked data '''
self.config = mock.Mock()
self.lo... |
import keras
import keras.backend as K
from keras.preprocessing import sequence
from keras.layers import LSTM, TimeDistributed, Input, Dense
from keras.models import Model
import os, random
import numpy as np
from argparse import ArgumentParser
import util
INDEX_FROM = 3
CHECK = 5
def generate_seq(
model ... |
# Copyright (c) 2018, Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for details.
import pytest
... |
#!/usr/bin/python
try:
import os
import sys
import json
import time
import pytest
import subprocess
except ImportError as e:
raise ImportError("%s - required module not found" % str(e))
# Test for USB storage support
def test_for_usb_storage():
"""Test Purpose: Verify that if the USB ... |
import pluggy
# hooks for registering plugins
register = pluggy.HookimplMarker("hop")
specification = pluggy.HookspecMarker("hop")
@specification
def get_models():
"""
This plugin spec is used to return message models in the form:
{"type": Model}
where the type refers to a specific message mode... |
import time
import constants as c
from random import random
from threading import Thread
class Event(Thread):
def __init__(self, monitored_area):
Thread.__init__(self)
self.deamon = True
self.monitored_area = monitored_area
def run(self):
while 1:
if random() <... |
from flask_restplus import Namespace, fields, reqparse
class AvgFare24HForDate:
""" Class to store Schema information for Average Speed for 24 hours preceding a given date """
ns = Namespace('avg_speed_24hrs_for_date', 'Average Speed for 24 hours preceding a given date')
model = ns.model('avg_spee... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 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, ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import timedelta
import time
from django.urls import reverse
from django.utils import timezone
from wechatpy import messages
from ..handler import Handler, message_handler
from ..models import MessageHandler, Rule, WeChatUser
from .base im... |
# Generated by Django 2.1 on 2019-03-13 12:05
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Upload',
... |
import pandas
import tqdm
import itertools
import re
from collections import Counter
class tabulation:
def __init__(self, path):
self.path = path
pass
def read(self):
self.table = pandas.read_csv(self.path)
pass
pass
|
# -*- coding: utf-8 -*-
"""setup.py: setuptools control. Always build with Python3"""
import sys
import re
from setuptools import setup, find_packages
from subprocess import call
from setuptools.command.install import install
version = re.search(
'^__version__\s*=\s*"(.*)"',
open('lyrico/lyrico.py').read(... |
"""tests for file_lib"""
import os
import logging
from py4ami.file_lib import AmiPath, PROJ, FILE
FILE_LIB = "file_lib"
PDF_LIB = "pdf_lib"
TEXT_LIB = "text_lib"
_SETUP = "_setup"
_TEARDOWN = "_teardown"
TEST = "test"
class TestFile:
logger = logging.getLogger("test_file")
TEST = "test"
OPTIONS = [
... |
input = """
1 33 1 1 34
1 34 1 1 33
1 35 1 1 36
1 36 1 1 35
1 37 1 0 33
1 38 1 0 35
1 39 2 1 40 37
1 41 2 1 42 38
1 43 2 0 37 39
1 44 2 0 38 41
1 40 2 1 39 37
1 42 2 1 41 38
2 47 2 0 1 34 36
1 48 1 1 47
1 49 1 0 48
2 50 2 0 1 40 42
1 51 1 1 50
1 52 1 0 51
1 53 1 0 49
1 54 1 0 49
1 55 2 0 52 37
1 56 2 0 52 38
1 57 1 0 4... |
import datetime
import unittest
from wordpress import WordPress
class TestWordPress(unittest.TestCase):
def setUp(self):
self.wp = WordPress('http://demo.wp-api.org/')
def test_get_404(self):
with self.assertRaises(Exception):
self.wp._get('404')
def test_post_404(self):
... |
# Copyright 2020 Arthur Coqué, Pôle OFB-INRAE ECLA, UR RECOVER
#
# 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 applic... |
#%%
import numpy as np
import matplotlib.pyplot as plt
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from pathlib import Path
import re
#%%
parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument("--result_dir", type=Path, required=True)
parser.add_argument("--... |
def divisibleSumPairs(numbers, divisor):
count = 0
numbers_length = len(numbers)
for i in range(numbers_length - 1):
for j in range(i + 1, numbers_length):
pair_sum = numbers[i] + numbers[j]
if pair_sum >= divisor and pair_sum % divisor == 0:
count += 1
... |
# -*- coding: utf-8 -*-
"""
chemdataextractor.doc.text
~~~~~~~~~~~~~~~~~~~~~~~~~~
Text-based document elements.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from abc import abstractproperty
import collections
... |
from django.contrib import admin
from bonds import models
admin.site.register(models.Bond) |
import collections
import logging
logger = logging.getLogger(__name__)
VERY_EARLY = -100
EARLY = -50
NORMAL = 0
LATE = 50
VERY_LATE = 100
Handler = collections.namedtuple("Handler", "handler priority")
class ServiceLocator:
def __init__(self):
self.providers = collections.defaultdict(lambda: [])
d... |
from discord.ext import commands
class ErrorMessage(commands.CommandError):
pass
class SuccessMessage(commands.CommandError):
def __init__(self, description, **embedoptions):
super().__init__(message="")
self.description = description
self.embedoptions = embedoptions |
from typing import Optional
import numpy as np
import torch
from torch.distributions import Normal, Categorical
from pbrl.algorithms.ppg.aux_buffer import AuxBuffer
from pbrl.algorithms.ppo import PPO, Policy
class PPG(PPO):
def __init__(
self,
policy: Optional[Policy] = None,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.