content stringlengths 5 1.05M |
|---|
from unittest import TestCase
from unittest.mock import MagicMock
from sciit import IssueSnapshot
from tests.external_resources import safe_create_repo_dir, remove_existing_repo
class TestIssueSnapshot(TestCase):
def setUp(self):
self.data = {
'issue_id': '1',
'title': 'new iss... |
# Advent of Code 2015 - Day 4 Part 1
# 17 Nov 2021 Brian Green
#
# Problem:
# find Santa the lowest positive number (no leading zeroes: 1, 2, 3, ...) that produces such a hash.
#
import hashlib
prefix = '11111'
base = -1
while prefix != '00000':
base += 1
xhash = hashlib.md5()
xhash.update(b'iwrupvqb')
... |
import os
import sys
from datetime import datetime
import csv
# Layer code, like parsing_lib, is added to the path by AWS.
# To test locally (e.g. via pytest), we have to modify sys.path.
# pylint: disable=import-error
try:
import parsing_lib
except ImportError:
sys.path.append(
os.path.join(
... |
import os
def parent_directory():
# Create a relative path to the parent
# of the current working directory
os.chdir('..')
# Return the absolute path of the parent directory
return os.getcwd()
print(parent_directory())
|
from .workers import celery
from datetime import datetime
from celery.schedules import crontab
from flask_sse import sse
from flask import url_for
from main import app as app
from .database import db
from .models import User,Deck
import os
import time
import requests
@celery.on_after_finalize.connect
def setup_periodi... |
import sys
from utils.utils import load_config
from utils.log import log
from base.trainer import Trainer
from models.wgan_gp import WGAN_GP
from models.wgan import WGAN
from models.dcgan import DCGAN
from app import app
def start_train_session(Model, cfg_path):
log.info("Setting up Trainer...")
trainer = ... |
from datetime import datetime
from itsdangerous import (TimedJSONWebSignatureSerializer
as Serializer, BadSignature, SignatureExpired)
from sqlalchemy import UniqueConstraint
from sqlalchemy.dialects.postgresql import JSON
from passlib.apps import custom_app_context as pwd_context
from mongo... |
import sys
from flask import Flask
from httpobs.conf import DEVELOPMENT_MODE, API_PORT, API_PROPAGATE_EXCEPTIONS
from httpobs.website import add_response_headers
from httpobs.website.api import api
from httpobs.website.monitoring import monitoring_api
def __exit_with(msg: str) -> None:
print(msg)
sys.exit(1... |
from malaya_speech.model.frame import Frame
from malaya_speech.utils.padding import (
sequence_1d,
)
from malaya_speech.utils.astype import float_to_int
from malaya_speech.utils.featurization import universal_mel
from malaya_speech.model.abstract import Abstract
from malaya_speech.utils.constant import MEL_MEAN, ME... |
from django.apps import AppConfig
class PrimerValConfig(AppConfig):
name = 'primer'
|
#!/usr/bin/python
#-*-coding:utf-8-*-
import os
from scrapy import log
from scrapy.http import Request
from scrapy.contrib.pipeline.images import ImagesPipeline
from woaidu_crawler.utils.select_result import list_first_item
class WoaiduCoverImage(ImagesPipeline):
"""
this is for download the book covor im... |
#!/usr/bin/env python3
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="animepirate-pantuts",
version="0.1.4",
author="Nick Bien",
author_email="[email protected]",
description="Dumb anime videos downloader.",
long_description=long_... |
import urllib.request
import json
from geopy.geocoders import Nominatim
from timezonefinder import TimezoneFinder
import datetime as dt
from time import sleep as wait
import pytz
with urllib.request.urlopen("https://geolocation-db.com/json") as url:
data = json.loads(url.read().decode())
geolocator = Nominatim(us... |
from girder.api import access
from girder.api.rest import Resource, filtermodel, RestException
from girder.api.describe import Description, autoDescribeRoute
from girder.constants import SortDir, AccessType
from ..models.user_module import UserModule as UserModuleModel
from girder import logprint
class UserModule(R... |
#!/usr/bin/env python3
import glob
import os
import numpy as np
import argparse
import pickle
import logging
from sklearn import model_selection
import model
from util import io_util, logging_util
from data_class import opunit_data
from info import data_info
from training_util import data_transforming_util, result_w... |
# write some code using unittest to test our
# add_state_names_columns assignment
import unittest
from pandas import DataFrame
from lambdata.assignment import add_state_names_columns
class TestAssignment(unittest.TestCase):
def test_add_state_names(self):
df = DataFrame({'abbrev': ['CA', 'CO', 'CT', 'D... |
import os
import platform
import shutil
import subprocess
import sys
from setuptools import setup, Distribution
import setuptools.command.build_ext as _build_ext
from setuptools.command.install import install
class Install(install):
def run(self):
install.run(self)
python_executable = sys.executab... |
import argparse
class DevOpsOptions:
def __init__(self):
parser = argparse.ArgumentParser(description='')
parser.add_argument('--env', action="store", dest='env', default='local')
parser.add_argument('--command', action="store", dest='command', default='start')
parser.add_argument(... |
from urllib.request import urlopen
from jwcrypto.jwk import JWKSet
jwkeys = JWKSet()
jwk_sets = [
'https://www.googleapis.com/oauth2/v3/certs'
]
def load_keys():
for keyurl in jwk_sets:
with urlopen(keyurl) as key:
jwkeys.import_keyset(key.read().decode())
|
import unittest
from car_pooling import Solution
class Test(unittest.TestCase):
def test_1(self):
solution = Solution()
self.assertEqual(solution.carPooling([[2, 1, 5], [3, 3, 7]], 4), False)
def test_2(self):
solution = Solution()
self.assertEqual(solution.carPooling([[2, 1,... |
# Copyright (c) 2010 gocept gmbh & co. kg
# See also LICENSE.txt
import gocept.zestreleaser.customupload.upload
import mock
import tempfile
import unittest
class UploadTest(unittest.TestCase):
context = {
'tagdir': '/tmp/tha.example-0.1dev',
'tag_already_exists': False,
'version': '0.1de... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/12/30 下午5:11
# @Title : 1. 两数之和
# @Link : https://leetcode-cn.com/problems/two-sum/
QUESTION = """
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nu... |
from inception.image.matte.bordermatte import *
if __name__ == '__main__':
from inception.image.image import Image
#image = Image.from_filepath("../../../../test/images/buff_small.png")#traditional-buffets-and-sideboards.jpg")
image = Image.from_filepath("../../../../test/images/traditional-buffets-and-sid... |
"""Unit test package for kraken."""
|
import time
from typing import Dict, Union
import requests
def listening_expression(
misty_ip: str,
colour: Dict = {"red": "0", "green": "125", "blue": "255"},
sound: Dict = {"FileName": "s_SystemWakeWord.wav"},
duration: Union[float, int] = 1.5,
) -> None:
requests.post("http://%s/api/led" % mis... |
from .model_field import Field
from ..settings import project_db
from ..utils import bson_parse
class Institution:
def __init__(self, _id):
self.name = ""
self._id = _id
self.fields = []
def add_field(self, name):
field_item = project_db["fields"].insert_one({"name": name})
field_id = field_item.inserte... |
from django.db import models
from django.core.exceptions import ValidationError
from django.db.models.fields.related import ForeignObject
from google_address.models import Address
try:
from django.db.models.fields.related_descriptors import ForwardManyToOneDescriptor
except ImportError:
from django.db.models.f... |
N = int(input())
A = list(map(int, input().split()))
m = 1000000007
A.sort()
if N % 2 == 0:
B = list(range(1, N, 2)) * 2
else:
B = [0] + list(range(2, N, 2)) * 2
B.sort()
if A != B:
print(0)
else:
result = 1
for i in range(N // 2):
result *= 2
result %= m
print(result)
|
"""
Автор: Орел Максим
Группа: КБ-161
Вариант: 11
Дата создания: 2/05/2018
Python Version: 3.6
"""
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
from scipy.interpolate import interp1d
# useful to understand http://mathprofi.ru/metod_naimenshih_kvadratov.html
x = [4.08, 4.42... |
"""
a model of T cell homeostasis for two competing clonotypes
This model definition is based on S. Macnamara and K. Burrage's formulation of
Stirk et al's model:
E. R. Stirk, C. Molina-Par and H. A. van den Berg.
Stochastic niche structure and diversity maintenance in the T cell
repertoire. Journal of T... |
# Generated by Django 2.0.6 on 2018-07-24 19:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('forms', '0005_form_fields'),
]
operations = [
migrations.AddField(
model_name='form',
name='image',
fiel... |
"""
파일 이름 : 2443.py
제작자 : 정지운
제작 날짜 : 2017년 7월 28일
프로그램 용도 : 별을 출력한다.
"""
# 입력
num = int(input())
# 출력
for i in range(num):
print(' ' * i, end = '')
print('*' * (2 * (num - i) - 1)) |
""" Analysis Module for Pyneal Real-time Scan
These tools will set up and apply the specified analysis steps to incoming
volume data during a real-time scan
"""
import os
import sys
import logging
import importlib
import numpy as np
import nibabel as nib
class Analyzer:
""" Analysis Class
This is the mai... |
from setuptools import setup, find_packages
with open('requirements.txt') as f:
requirements = [l for l in f.read().splitlines() if l]
setup(
name="senet",
author="Kan HUANG",
# install_requires=requirements,
python_requires=">=3.6",
version="0.0.1",
packages=find_packages()
)
|
from random import sample
from exercises import *
from time import sleep
from datetime import date
today = str(date.today())
log = open("/home/billy/Desktop/Workout " + today + ".txt", "w")
#Create the generator class which will actually create the routines according
#to the desired number of days per week.
class Gen... |
import FWCore.ParameterSet.Config as cms
electronHcalTowerIsolationScone = cms.EDProducer("EgammaTowerIsolationProducer",
absolut = cms.bool(True),
intRadius = cms.double(0.15), # to be orthogonal with the H/E ID cut
extRadius = cms.double(0.3),
towerProducer = cms.InputTag("towerMaker"),
etMin = c... |
import logging
import os
import sys
from db.setup import SessionWrapper
from logger import logging_config
from orm.personality_tables import *
from save_liwc_scores.orm.scores_tables import *
from twit_personality.training.datasetUtils import parseFastText
from twit_personality.training.embeddings import transformTex... |
"""
Created on Mon Apr 14 15:48:29 2014
@author: Vasanthi Vuppuluri
Original code inspired by: Tanmay Thakur
"""
# PURPOSE:
#---------
# This is designed for the new Azure Marketplace Bing Search API (released Aug 2012)
#
# Inspired by https://github.com/mlagace/Python-SimpleBing and
# http://social.msdn.microsoft.c... |
"""
Command-line argument parsing with structured printing.
See the argparse python module for details to extend argument parsing.
\LegalBegin
Copyright 2019-2020 Aether Instinct LLC. All Rights Reserved
Licensed under the MIT License (the "License").
You may not use this file except in compliance with the Licen... |
import unittest
from conans.test.utils.tools import TestClient
from conans.paths import CONANFILE
from conans.test.utils.conanfile import TestConanFile
class VersionRangesErrorTest(unittest.TestCase):
def verbose_version_test(self):
client = TestClient()
conanfile = TestConanFile("MyPkg", "0.1", r... |
class _RabbitConfig:
"""Parameters for connecting to the RabbitMQ server.
Properties:
* host [str] - The RabbitMQ server's host name (e.g. "localhost")"""
def __init__(self, host=None):
self.host = host
|
# Generated by Django 3.0.7 on 2020-09-04 12:25
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("ig_guidance", "0001_initial"),
]
operations = [
migrations.AlterModelOptions(
name="igtemplate", options={"verbose_name": "Template"},
... |
# 计算根号x的值
x = 2
# 在不引入虚数的前提下小于0的数没有平方根
if x < 0:
print('ERROR')
else:
# 设置精度要求
wuqiongxiao = 0.001
a = x / 2
if a<wuqiongxiao:
a = wuqiongxiao
# 最多迭代40000次,防止陷入死循环
for i in range(40000):
b = x / a
delta = a - b
a = (a + b) /2
if delta < 0:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
from urllib.parse import urljoin
from typing import List
from base_parser import BaseParser
class GamespotCom_Parser(BaseParser):
def _parse(self) -> List[str]:
url = f'https://www.gamespot.com/search/?i=site&q={self.game_name}'
... |
import sys
from crdt.ops import OpAddRightLocal
from crdt_app import CRDTApp
def run_p2p(my_addr, known_peers, encrypt=False, priv_key=None, my_cookie=None, other_cookies=None):
auth_cookies = None
if other_cookies is not None:
auth_cookies = dict(zip(known_peers, other_cookies))
app = CRDTApp(my... |
from channels.generic.websocket import JsonWebsocketConsumer
class UpdatesConsumer(JsonWebsocketConsumer):
def connect(self):
self.accept()
def receive_json(self, content):
if 'type' in content and content['type'] == 'keep-alive':
self.send_json({'type': 'keep-alive'})
def d... |
import argparse
import colorsys
import math
import os
import random
import time
import cv2
import matplotlib.pyplot as plt
import numpy as np
import pyglet
import trimesh
from PIL import Image, ImageEnhance
from tqdm import tqdm
from OpenGL.GL import GL_LINEAR_MIPMAP_LINEAR
import pyrender
from archiver import Archi... |
#!/usr/bin/python
# -*- encoding: utf-8 -*-
'''
@Time : 2021/03/16 10:35:28
@Author : Camille
@Version : 0.7beta
'''
from concurrent import futures
import socket
from sys import argv
import time
import threading
import struct
import uuid
import json
import os, subprocess
from concurrent.futures import threa... |
import click
from sigopt.validate import validate_top_level_dict
from .load_yaml import load_yaml_callback
cluster_filename_option = click.option(
'-f',
'--filename',
type=click.Path(exists=True),
callback=load_yaml_callback(validate_top_level_dict),
help='cluster config yaml file',
default='cluster.yml... |
#!/usr/bin/env python
# coding: utf-8
import os
from pathlib import Path
import io
import geoviews as gv
import panel as pn
import param
from panel.widgets import Checkbox
from mednum.widgets import TreeViewCheckBox
from holoviews.element.tiles import StamenTerrain
from mednum.loaders import *
from pygal.style import S... |
from django.contrib.auth.models import User, Group
from rest_framework import serializers
from app.models import Category, Beverage
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url', 'username', 'email', 'groups']
class GroupSerializer(seriali... |
from django.urls import path
from . import views
urlpatterns = [
path('register/', views.registerPage, name="register"),
path('login/', views.loginPage, name="login"),
path('logout/', views.logoutUser, name="logout"),
path('whoweare/', views.whoweare, name="whoweare"),
path('info/', views.info, name="in... |
# -*- coding: utf-8 -*-
"""Top-level package for webexteamsbot."""
# from .Spark import SparkBot # noqa
from .webexteamsbot import TeamsBot # noqa
__author__ = """Hank Preston"""
__email__ = "[email protected]"
__version__ = "0.1.0"
|
__version__ = (0, 0, 1)
from .parser import read, parse_reply
__all__ = ('read', 'parse_reply')
|
import logging
from flask import Blueprint
from burgeon.api.auth.registration_api import RegistrationAPI
from burgeon.api.auth.login_api import LoginAPI
from burgeon.api.auth.logout_api import LogoutAPI
from burgeon.api.auth.user_api import UserAPI
log = logging.getLogger('burgeon.api.auth')
# Loader for flask-login... |
# encoding: utf-8
# pylint: disable=no-self-use
"""
Docker provider setup.
"""
from datetime import datetime, timedelta
import functools
import logging
import docker
import types
from flask_login import current_user
from flask_restplus_patched import Resource
from flask_restplus_patched._http import HTTPStatus
from a... |
import os
from abc import abstractmethod
from pathlib import Path
import yaml
from surround.config import Config
__author__ = 'Akshat Bajaj'
__date__ = '2019/02/18'
class BaseRemote():
def __init__(self):
self.message = ""
self.messages = []
def write_config(self, what_to_write, file_, name,... |
from distutils.core import setup
setup(
name = "rewemo",
version = "0.1.0",
description = "Renewable energy time series from numerical weather model data",
author = "Harald G Svendsen",
author_email = "[email protected]",
license = "MIT License (http://opensource.org/licenses/MIT)",
classifiers = [
"Pr... |
"""Generated wrapper for Timelock6h Solidity contract."""
# pylint: disable=too-many-arguments
import json
import time
from typing import ( # pylint: disable=unused-import
Optional,
Tuple,
Union,
)
from eth_utils import to_checksum_address
from hexbytes import HexBytes
from web3.contract import Contract... |
# merge Sort
#
# Time Complexity: O(n*log(n))
# Space Complexity: O(n)
class Solution:
def mergeSorted(self, l1, l2):
ret = []
i, j = 0, 0
while i < len(l1) and j < len(l2):
if l1[i] < l2[j]:
ret.append(l1[i])
i += 1
else:
... |
from typing import Union
import us
def build_acs_url(year: Union[int, str] = '2017',
survey: Union[str, int] = '1-Year',
person_or_household: str = 'person',
state: str = 'California',
):
"""
Builds CENSUS FTP-server URL where you can downl... |
# -*- coding: utf-8 -*-
"""
Plot the eigenworms file.
For more information see
https://github.com/openworm/open-worm-analysis-toolbox/issues/79
"""
import sys
import os
import h5py
import numpy as np
import matplotlib.pyplot as plt
#import mpld3
# We must add .. to the path so that we can perform the
# import of op... |
# pylint: disable=no-self-use,invalid-name
from unittest import TestCase
from allennlp.models.archival import load_archive
from allennlp.service.predictors import Predictor
from propara.propara.service.predictors.prostruct_prediction import ProStructPredictor
from propara.propara.models.prostruct_model import ProStruc... |
"""
This module contains classes for datasets compatible with Pytorch
"""
from torch.utils.data.dataset import Dataset
from torchvision import transforms
from sklearn.preprocessing import LabelEncoder
from PIL import Image
import numpy as np
class ImageDataset(Dataset):
def __init__(self, files: list, label_encod... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext as _
from cms.models import CMSPlugin
from cms.extensions import PageExtension
from cms.extensions.extension_pool im... |
import torch
import torch.nn as nn
def uniform_weights_initialization(model):
for module in model.modules():
if type(module) == nn.Conv2d:
torch.nn.init.xavier_uniform(module.weight)
module.bias.data.fill_(0.01)
|
# MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from __future__ import unicode_literals
import swapper
from accelerator_abstract.models import BaseApplicationAnswer
class ApplicationAnswer(BaseApplicationAnswer):
class Meta(BaseApplicationAnswer.Meta):
swappable = swapper.swappable_setting(
... |
import itertools
import numpy as np
import tensorflow as tf
import video_prediction as vp
from video_prediction import ops
from video_prediction.models import VideoPredictionModel, SAVPVideoPredictionModel
from video_prediction.models import pix2pix_model, mocogan_model, spectral_norm_model
from video_prediction.mode... |
from state.machine import BaseState
from helper import *
import state
class HuntPlayerState(BaseState):
def action(self, game_state):
#if game_state_helper.get_current_hp_count(game_state) <= 5:
# return state.GoHomeState(), None
my_pos = game_state_helper.get_my_position(game_state)
... |
# Import Python packages
import os
import glob
import csv
import black
def process_files():
# Join a set of event data stored in indiual csv file into one output file
# for parsing
# checking your current working directory
print(os.getcwd())
# Get your current folder and subfolder event data
... |
import matplotlib
import matplotlib.pyplot as plt
import json as json
import dateutil.parser
import sys
import os
import numpy
if len(sys.argv) < 3:
print("Usage: python3 process_metrics.py <FILE_NAME> <BIN_SIZE_IN_SECONDS>")
sys.exit()
print("Opening file %s" % sys.argv[1], file = sys.stderr)
TOTAL_LINES = i... |
#!/usr/bin/env python3
# https://www.hackerrank.com/challenges/python-division
# #python
import io
import sys
import unittest
def divide(first, second):
int_val = first // second
float_val = first / second
return int_val, float_val
def main():
first_in = int(input().strip())
second_in = int(inp... |
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='yoi',
version='0.0.1',
packages=find_packages('.'),
package_dir={'': '.'},
install_requires=[
# FIXME - read requirements.txt!
],
)
|
import importlib
import logging
import math
import sys
import click
import numpy as np
import tensorflow as tf
from flask import Flask
from flask import json
from flask import request
from nltk import word_tokenize
from experiment.config import load_config
from experiment.qa.data.models import Sentence
from experimen... |
import sys
import time
import schedule
from service import Request
sys.path.insert(0, '')
schedule.every(1).minutes.do(Request.getBalances)
while 1:
schedule.run_pending()
time.sleep(1)
|
# -*- coding:utf-8 -*-
import time
import pandas as pd
import numpy as np
from py4jhdfs import Py4jHdfs
from pyspark.sql import HiveContext, SQLContext
from pyspark.sql.types import *
def run_time_count(func):
"""
计算函数运行时间
装饰器:@run_time_count
"""
def run(*args, **kwargs):
start = time.tim... |
'''
This contains some useful routines I need for finding and analysing
frequencies in pulsating star lightcurves
'''
import multiprocessing
import numpy as np
import f90periodogram
from scipy.interpolate import interpolate
try:
import pyopencl as cl
OPENCL = True
except ImportError:
print("opencl not a... |
from __future__ import print_function
from constants import __THISDIR__, __ABRESTBANDNAME__, __VEGARESTBANDNAME__
from constants import __MJDPKNW__, __MJDPKSE__, __Z__
from constants import __MJDPREPK0NW__, __MJDPOSTPK0NW__
from constants import __MJDPREPK0SE__, __MJDPOSTPK0SE__
from . import lightcurve
from .kcorrect... |
import logging
import pandas as pd
from tqdm import tqdm
from .compare_kmer_content import compare_all_seqs
from .ensembl import get_sequence, get_rna_sequence_from_protein_id
# Create a logger
logging.basicConfig(format="%(name)s - %(asctime)s %(levelname)s: %(message)s")
logger = logging.getLogger(__file__)
logger... |
#!/usr/bin/env python
# coding: utf-8
import tensorflow as tf
print(tf.__version__)
# 2.0.0-alpha0
from tensorflow.keras.applications import VGG16
conv_base = VGG16(weights='imagenet',
include_top=False,
input_shape=(150, 150, 3))
conv_base.summary()
#____________________________... |
from pyrosim.neuron import NEURON
from pyrosim.synapse import SYNAPSE
class NEURAL_NETWORK:
def __init__(self, nndfFileName):
self.neurons = {}
self.synapses = {}
f = open(nndfFileName, "r")
for line in f.readlines():
self.Digest(line)
f.close()
def ... |
# Automatically generated by pb2py
# fmt: off
import protobuf as p
from .StellarAssetType import StellarAssetType
class StellarPaymentOp(p.MessageType):
MESSAGE_WIRE_TYPE = 211
def __init__(
self,
source_account: str = None,
destination_account: str = None,
asset: StellarAsse... |
from faker import Faker
# from arbeitsstunden.models import *
import random
from member.models import profile
'''
Erstellt die gewünschte Anzahl an fakeNews.
fakeNews sind dabei News müssen nicht zwangsläufig einen Sinn haben.
@return Array, bestehend aus Objekten mit Text, Titel
'''
def fakeNews(Anzahl: int) -> []:
... |
import speech_recognition
import pyttsx
speech_engine-pyttsx.init('sapi5')
speech_engine.setProperty('rate',150)
def speak(text):
speech_engine.say(text)
speech_engine.runAndWait()
recongnizer=speech_engine.Recognizer()
def listen():
with speech_engine.Microphone() as source:
recongnizer.adjust_for_ambient_noise(s... |
import os
import sys
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
import csv
import locale
import re
locale.setlocale(locale.LC_ALL, '')
total_nodes = 0
DEFAULT_VALUE="3"
NODE_NUM = ["3", "5", "10", "26"]
def get_completion_time(startTime, endTime):
startTime = datetime.strpti... |
import sys
import pytest
import unittest
from django_message_broker.server.utils import IntegerSequence, WeakPeriodicCallback, PeriodicCallback, MethodRegistry
class IntegerSequenceTests(unittest.TestCase):
def test_next(self):
integer_sequence = IntegerSequence().new_iterator()
self.assertEqual(... |
#!/usr/bin/python
#
# Copyright 2022 DeepMind Technologies Limited
#
# 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 a... |
"""
This is the definition for a spot light
A spot light emits light to one directions with some angle around it.
"""
from .light import Light
from ..math import Vec3
from ..math import Ray
from ..renderer.rgbimage import *
class SpotLight(Light):
"""Class describing a spot light source"""
def __init__(s... |
"""
Copyright ©2017. The Regents of the University of California (Regents). All Rights Reserved.
Permission to use, copy, modify, and distribute this software and its documentation for educational,
research, and not-for-profit purposes, without fee and without a signed licensing agreement, is
hereby granted, provided t... |
from distutils.core import setup
setup(
name='mgprint',
packages=['mgprint'],
version='0.1',
license='MIT',
description='Magic printer for Python CLI',
author='Fernando Olivera',
author_email='[email protected]',
url='https://github.com/fergeek/mgprint',
download_url='https://github.... |
import writer_main.writer_pkg as pkg
def init():
pkg.init()
|
import Algorithmia
import spacy
"""
This package set comes preinstalled with every available small language package provided by spacy.
Pick your language from the following list: 'en', 'es', 'pt', 'fr', 'it', 'de, and 'nl'
You may change the language at runtime, but bear in mind that you'll get hit with some performan... |
import numpy as np
import pandas as pd
from bokeh.models import Band, HoverTool
from tqdm import tqdm
import timeit
import warnings
from copy import deepcopy
from scipy.stats import norm
import time
import multiprocessing
from joblib import Parallel, delayed
from copy import deepcopy, copy
from bokeh.plotting import Co... |
# encoding: utf-8
"""Utilities for cr.cube tests."""
import os
def load_expectation(expectation_file_name, strip=True): # pragma: no cover
"""Return (unicode) str containing text in *expectation_file_name*.
Expectation file path is rooted at tests/expectations.
"""
thisdir = os.path.dirname(__file... |
# Generated by Django 2.2.7 on 2020-09-27 05:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0014_auto_20200926_2116'),
]
operations = [
migrations.CreateModel(
name='Tabs',
fields=[
('... |
# Author: Matthew Mills
# Copyright 2016
# The purpose of this class is to provide the pricing oracle required to feed market data
# We write this in a similar fashion to how it would operate in Ethereum
# Hence the constructor initiates the oracle, which then refreshes when told
# ---
# This is the oracle to interf... |
#
# Software distrubuted under MIT License (MIT)
#
# Copyright (c) 2020 Flexpool
#
# 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
# ... |
from dotenv import load_dotenv
load_dotenv()
from .impl import Bot
__all__ = ("Bot",)
|
"""A simple config manager."""
# TODO: add real config handling
config = {'tag_db_path': 'taglist.xml'}
|
import sys
import numpy as np
from scipy import special
from pymoo.util.misc import find_duplicates, cdist
# =========================================================================================================
# Model
# ===========================================================================================... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.