content
stringlengths
5
1.05M
#!/usr/bin/python -OOOO # vim: set fileencoding=utf8 shiftwidth=4 tabstop=4 textwidth=80 foldmethod=marker : # Copyright (c) 2010, Kou Man Tong. All rights reserved. # For licensing, see LICENSE file included in the package. """ Base codec functions for bson. """ import struct import cStringIO import calendar from date...
#!/usr/bin/python # ***************************************************************************** # # 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 A...
from django.db import models # Create your models here. class Project(models.Model): '''Simple model for a project''' project_name = models.CharField(max_length=100) description = models.CharField(max_length=100, blank=True, null=True) added_on = models.DateTimeField(auto_now=True, auto_now_add=True...
from unittest import TestCase from views.customer_functions import registerCustomer def test_register_function(): first_name: str = "Ehis" last_name: str = "Edemakhiota" email: str = "edemaehiz@gmail.com" password: str = "EdemaEhi17." user_name: str = "ehizman" registerCustomer(first_name, la...
""" timeseries_qt_demo.py ---- Modification of demo This demo demonstrates how to embed a matplotlib (mpl) plot into a PyQt4 GUI application, including: * Using the navigation toolbar * Adding data to the plot * Dynamically modifying the plot's properties * Processing mpl events * Saving the plot to a file from a ...
def ccw(A,B,C): return (C[1]-A[1]) * (B[0]-A[0]) > (B[1]-A[1]) * (C[0]-A[0]) def is_intersection(A,B,C,D): return ccw(A,C,D) != ccw(B,C,D) and ccw(A,B,C) != ccw(A,B,D) def compare_with_prev_position(prev_detection, detection, line, entry, exit): (xmin_prev, ymin_prev) = (int(prev_detection[0]), int(prev_detectio...
from datetime import datetime import pytest from articat.bq_artifact import BQArtifact def test_versioned_not_supported(): with pytest.raises( NotImplementedError, match="Versioned BigQuery Artifact is not supported" ): BQArtifact.versioned("foo", version="0.1.0") def test_bq_client_is_laz...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `hypothesis_ledger` package.""" import unittest from collections import Counter, OrderedDict from datetime import date from decimal import Decimal from pathlib import Path from hypothesis_ledger.hypothesis_ledger import Ledger, Transaction class TestLedge...
import sys import csv class SimulationSettings: Softening = 10.0 # KM added to every link distance to eliminate needless distinction between very short routes. #TurnBackAllowed = True # feature disabled for now. AgentLogLevel = 0 # set to 1 for basic agent information. CampLogLevel = 0 # set to 1 to obtain av...
__author__ = "Mario Figueiro Zemor" __email__ = "mario.figueiro@ufgrs.br" from classes.Database import * import logging logger = logging.getLogger(__name__); class Estudante(): cursor = Database.getCursor(); def __init__(self,tupla): self.inscricao = tupla[0]; self.idade = tupla[1]; s...
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.detailed_ground_heat_transfer import GroundHeatTransferBasementAutoGrid log = logging.getLogger(__name__) class TestGroundHeatTransferBasementAutoGrid(unittest.TestCase): d...
from model import * import json import ui_helper as ui import os logfilename = 'warnings.log' def read(file_name): with open(file_name,'r') as f: course_dict = json.load(f) return course_from_dict(course_dict) def save(gb, file_name): data = json.dumps(course_to_dict(gb), indent=2, sort_keys=True...
import sys from config import DEBUG_MODE, EASYGIF_VERSION if "-v" in sys.argv or "--version" in sys.argv: print(f"EasyGif {EASYGIF_VERSION}") quit() if "-h" in sys.argv or "--help" in sys.argv: print() print(" EASYGIF SERVER HELP CENTER") print() print(f"EasyGif {EASYGIF_VERSIO...
#!/usr/bin/python # frontend to meowcc # the Scratch linker <3 # llvm-link a.ll b.ll -f | llvm-dis import sys import subprocess import argparse # parse arguments in pretty way parser = argparse.ArgumentParser(description='Frontend to meowcc') parser.add_argument("--output", "-o", help="output file") parser.add_argu...
from django.db import models from django.utils.translation import ugettext_lazy as _ from django.contrib.sites.models import Site class Setting(models.Model): """ Stores values for ``mezzanine.conf`` that can be edited via the admin. """ name = models.CharField(max_length=50) value = models.Char...
def link(cmd, serv, nick, dest, msg): q = msg.replace(" ","+") serv.send("PRIVMSG %s :%s: http://lmgtfy.com/?q=%s\n" % (dest, nick, q)) serv.on_command.connect(link, "link")
from flask import request, jsonify, make_response, current_app from flaskapp.database.models import User from flaskapp.authorization import jwt_redis_blocklist, TOKEN_EXPIRES from flaskapp.responses import * from flask_restful import Resource from flask_jwt_extended import create_access_token, get_jwt, current_user, jw...
from simple_wsgi import API app = API() # Simple routing like in Flask @app.route("/") def index_page(request, response): response.text = "Hello from the INDEX page." # Simple routing like in Django def home_page(request, response): response.text = "Hello from the HOME page." app.add_route("/home", home_p...
""" Project OCELoT: Open, Competitive Evaluation Leaderboard of Translations """ from difflib import SequenceMatcher from django.contrib import messages from django.core.paginator import Paginator from django.http import Http404 from django.shortcuts import HttpResponseRedirect from django.shortcuts import render fro...
import xlrd import numpy from scipy import stats from sklearn import datasets from sklearn import linear_model argc = 2 url = ['D:\\Code\\城房指数新编制\\1 指数编制2018-2020.7excel表\\2018-2020.7excel表\\33 成都标准数据2018.1.xls', 'D:\\Code\\城房指数新编制\\1 指数编制2018-2020.7excel表\\2018-2020.7excel表\\33 成都标准数据2018.2.xls'] def getSB(...
from pathlib import Path from setuptools import setup, find_packages with open('README.md') as f: readme = f.read() with open('LICENSE') as f: license = f.read() setup( name='scbasset', version='0.1', description='model scATAC with sequence-based CNN.', long_description=readme, author='Han Yu...
import os import argparse from glob import glob from functools import partial from dataclasses import dataclass import numpy as np from tqdm import tqdm import matplotlib.pyplot as plt import cv2 from PIL import Image import wandb import jax import jax.numpy as jnp import flax from flax import linen as nn import ...
from .models import Followers def add_first_follower(username, follower): return Followers.add_one(username, follower) def update_followers(username, follower): return Followers.update_one(username, follower)
"""Provides the Predictor related classes.""" from .base import Base import json class Predictors(Base): _base_path_ = 'predictors' _auto_methods_ = ('get', 'post') def create_collection(self, collection_name, dataset_id, runs, event_files, descriptions=None): """ Create...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('arbeitsplan', '0008_auto_20141208_1906'), ] operations = [ migrations.AddField( model_name='mitglied', ...
from .proscript import Word, Proscript, Segment
from .e7_activity import E7Activity from dataclasses import dataclass @dataclass class E11Modification(E7Activity): """ Scope note: This class comprises instances of E7 Activity that create, alter or change instances of E24 Physical Human-Made Thing. This class includes the production of an item from raw materia...
# # Copyright (c) 2022 Airbyte, Inc., all rights reserved. # import pytest from source_linkedin_ads.utils import get_parent_stream_values @pytest.mark.parametrize( "record, key_value_map, output_slice", [ ({"id": 123, "ref": "abc"}, {"acc_id": "id"}, {"acc_id": 123}), ({"id": 123, "ref": "abc...
i = 0 while True: print(i) i = i + 1
import os import numpy from abaqusGui import * import testDB import gui_defaults reload(gui_defaults) from desicos.logger import error from desicos.abaqus.constants import TMP_DIR # Note: The above form of the import statement is used for the prototype # application to allow the module to be reloaded while the appli...
from django.contrib import admin from .models import NeighbourHood,User,Business,Profile @admin.register(NeighbourHood) class NeighbourHood(admin.ModelAdmin): search_fields =['name','location','photo','counts','created_by'] class Meta: model = NeighbourHood # @admin.register(User) # class User(ad...
# Copyright 2019 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 applicable law or ...
import numpy as np import gym from gym import spaces import random class TwoThinning(gym.Env): REJECT = 0 ACCEPT = 1 def get_random_bin(self): return random.randrange(self.n) def evaluate(self): return -np.max(self.load_configuration) def __init__(self, n=8, m=15): super(...
from django.urls import path from apps.job_submissions import views urlpatterns = [ path("job-submission/", views.JobSubmissionListView.as_view()), path("job-submission/<int:pk>/", views.JobSubmissionView.as_view()), ]
import factory from .. import models class PublisherFactory(factory.django.DjangoModelFactory): class Meta: model = models.Publisher
#from stack import Stack from . import * TInt = Type("Int") # # Integer handling # # Constructors def op_int(c: AF_Continuation) -> None: #print("\nop_int c.stack.contents = %s." % c.stack.contents()) i = int(c.stack.pop().value) assert i < 999999999999, "int overflow > 999999999999" assert i > -...
"""Standard text for ROSS Report.""" __all__ = ["ReportTemplateText"] class ReportTemplateText: """Create text instances to ROSS REPORT. Each argument holds a dictionary related to a single Report section. The arguments are collected and set to the HTML file according to the content organization. ...
import gensim from gensim.scripts import glove2word2vec from gensim.models import fasttext import os import shutil from sys import platform import pickle import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) # 计算行数,就是单词数 def getFileLineNums(filename): f = open(...
import configparser import os import sys from .resources import * from .tabquery_path import TabQueryPath tab_cli_exe = '' def configure_tabquery_path(): """Setup the tabquery path from ini settings.""" global tab_cli_exe if os.environ.get('TABQUERY_CLI_PATH'): tab_cli_exe = os.environ.get('TABQ...
# -*- coding: utf-8 -*- """ Created on Sun Feb 13 23:30:09 2022 @author: Daniel Bresnahan """ import os import pandas as pd class CornDataset(): """ Corn with and without NCLB Dataset""" def __init__(self, csv_file, root_dir, transform=None): """ Parameters ---------- c...
import os import unittest import numpy as np import pandas as pd from portformer import BreakpointAPI from portformer.errors import PortformerInvalidAPIKeyError, PortformerMissingAPIKeyError class TestBreakpointAPI(unittest.TestCase): def setUp(self): # Read environment variable = BREAKPOINT_API_KEY ...
import numpy as np # from numpy import fft import pandas as pd # from scipy import signal as sig # from cmath import phase # import math from fft_utils import FFTFeatureExtractor import logging # import matplotlib as mpl import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from argparse imp...
# -*- coding: utf-8 -*- """ Created on Thu Nov 11 14:53:06 2021 @author: angus """ import numpy as np from time import sleep import base64 from io import BytesIO from selenium import webdriver from selenium.webdriver.chrome.options import Options import pandas as pd ### Options that allow chrome to run ...
''' General grab bag of helper functions ''' import numpy as np import os #from .settings import DEFAULT_AWRAL_MASK from .precision import iround, quantize, aquantize, sanitize_cell, sanitize_geo_array def _DEP_load_mask(fn_mask): ''' Identify the AWAP cells required for the continental AWRA-L run. Retur...
""" @file @brief Profiling helpers """ import os from io import StringIO import cProfile import pstats import site def _process_pstats(ps, clean_text): """ Converts class `Stats <https://docs.python.org/3/library/ profile.html#pstats.Stats>`_ into something readable for a dataframe. """ def ad...
import os from git import Repo, Actor from conda_build.conda_interface import (VersionOrder, MatchSpec, get_installed_version, root_dir, get_index, Resolve) from .utils import tmp_directory def update_me(): """ Update the webservice on Heroku by pushing a commit to this repo. """ pkgs = ["conda-buil...
from random import choice, randint N = 10000 K = 233333333 CMAX = 1000 L = [] T = [1] # for i in range(1, N): # v = i + 1 # f = choice(T) # L.append("{} {} {}".format(f, v, randint(1, CMAX))) # T.append(v) for i in range(1, N): L.append("{} {} 100".format(i, i + 1)) with open("data.in", "w") as f...
from pyxmpp.clientstream import ClientStream from pyxmpp.exceptions import ClientStreamError from pyxmpp.exceptions import FatalStreamError from dispatcher import StreamDispatcher import logging class ClientStreamAsyncore(ClientStream): def __init__(self, jid, password=None, server=None, port=None, ...
#Author: Ulya Bayram #email : ulya.bayram@comu.edu.tr # # The original versions of these scripts can be found from the StellarGraph website #------------------------------------------------------------------------------------------------------ # #-------------------------------------------------------------------------...
import discord import datetime as dt from datetime import datetime, timedelta, timezone import time from discord.ext import tasks, commands import random import os client = discord.Client() pretime_dict = {} memberlist = {} inmemberlist = {} JST = timezone(timedelta(hours=+9), 'JST') token = os.environ['DISCORD_BO...
""" Lightgbm algorithm wrapper. """ import lightgbm as lgb def lgb_train_cv(params, df_train, df_val, predictors, target='target', objective='binary', metrics='auc', feval=None, early_stopping_rounds=20, num_boost_round=3000, verbose_eval=10, categorical_features=None ): """Train an lgb model with cross-validati...
/usr/local/lib/python2.7/_abcoll.py
# Mapping of GDAL to Numpy data types. # # Since 0.13 we are not importing numpy here and data types are strings. # Happily strings can be used throughout Numpy and so existing code will # break. # # Within Rasterio, to test data types, we use Numpy's dtype() factory to # do something like this: # # if np.dtype(dest...
import numpy as np class DataPreProcessing: pass
# Copyright (c) 2015 Shotgun Software Inc. # # CONFIDENTIAL AND PROPRIETARY # # This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit # Source Code License included in this distribution package. See LICENSE. # By accessing, using, copying or modifying this work you indicate your # agreement to t...
#!/usr/bin/env python from util import * from regress import * from loaddata import * import openopt from collections import defaultdict import argparse halfdays = ['20111125', '20120703', '20121123', '20121224'] breaks = ['20110705', '20120102', '20120705', '20130103'] parser = argparse.ArgumentParser(descripti...
import unittest import magics #from prog_edu_assistant_tools import magics class TestCutPrompt(unittest.TestCase): def testCutPrompt_intact(self): self.assertEqual(magics.MyMagics.CutPrompt('abc'), 'abc') self.assertEqual(magics.MyMagics.CutPrompt('\nabc\ncde\n'), '\nabc\ncde\n') def testCutPrompt_sol...
import json import time from base64 import b64encode from pprint import pprint from urllib.parse import urljoin import requests import telepot from celery import Celery from peewee import fn from retry import retry from conf import Config from model import DarkNet_DataSale, DarkNet_IMGS, DarkNet_Notice, DarkNet_User ...
# Copyright 2016 - Parsely, Inc. (d/b/a Parse.ly) # # 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 a...
""" public_account ============== Account public key and address. License ------- Copyright 2019 NEM 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 h...
import os import sys from dolfin import MPI, timings, TimingClear, TimingType, File, dump_timings_to_xml from subprocess import check_output, CalledProcessError from distutils.util import strtobool import json import time import mpi4py # Colored printing functions for strings that use universal ANSI escape sequences. ...
# -*- coding: utf-8 -*- # Copyright 2020 ICON Foundation # # 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 o...
from distutils.core import setup setup( name = 'rest_apscheduler', packages = ['rest_apscheduler', 'rest_apscheduler/migrations'], version = '0.1.3', license='MIT', description = 'You can use this package only for django and can schedule jobs using any database and maintain record.', author = 'Ronak Jain', ...
# --- # jupyter: # jupytext: # formats: ipynb,py:light # text_representation: # extension: .py # format_name: light # format_version: '1.4' # jupytext_version: 1.1.6 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + # Import Scripts # %r...
from nipype.interfaces.base import BaseInterface, \ BaseInterfaceInputSpec, traits, File, TraitedSpec from nipype.utils.filemanip import split_filename import nibabel as nb import numpy as np import os class RestAverageInputSpec(BaseInterfaceInputSpec): func = File(exists=True, desc='functional to analyze', ma...
#!_PYTHONLOC # # (C) COPYRIGHT 2005-2021 Al von Ruff, Bill Longley, Uzume, Ahasuerus and Dirk Stoecker # ALL RIGHTS RESERVED # # The copyright notice above does not evidence any actual or # intended publication of such source code. # # Version: $Revision$ # Date: $Date$ from SQLparsing imp...
############################################## #### Author: Hunter Gregal #### ############################################## ##To Do ##add geolocate by zip ...Google Maps API? ##Crack user ID hash scheme import requests import json #Coords of Town lat = "44.4758800" lon = "-73.2120700" raw = requests.get("https...
import os import argparse import numpy as np from scipy.io import savemat, loadmat from PIL import Image from tqdm import tqdm parser = argparse.ArgumentParser() parser.add_argument('--root_path', default='../data/VOCSegmentation2012/VOCdevkit/VOC2012', help='root to the images') parser.add_argument('--sp_folder', def...
from requests_html import HTMLSession import json class InstagramGrabber: def __init__(self, username): self.username = username def getLinks(self): session = HTMLSession() r = session.get('https://instagram.com/' + self.username) l = r.html.find('body > script:nth-child(2)')[...
# This file is part of COFFEE # # COFFEE is Copyright (c) 2014, Imperial College London. # Please see the AUTHORS file in the main source directory for # a full list of copyright holders. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime from contextlib import contextmanager import peewee from flask import abort from peewee import Model import utils from services import peewee_mysql from utils.log import app_logger class MySQLBaseModel(Model): class Meta: database = peewee_my...
from flask import Blueprint tran = Blueprint('tran', __name__) from . import views
# Generated by Django 3.0.14 on 2021-05-19 17:22 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('api', '0102_modelyearreportassessment_modelyearreportassessmentcomment_modelyearreportassessmentdescriptions'), ] operations = [ migrations.RemoveF...
import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import OpaqueFunction from launch_ros.actions import Node def launch_setup(context, *args, **kwargs): bt_example_dir = get_package_share_directory('nav2_bt_example') nav_pa...
from pngdata.core import encode, decode
import pytest from django.core.files.base import ContentFile try: from wagtail.core.models import Page except ImportError: from wagtail.wagtailcore.models import Page from wagtail_svgmap.models import ImageMap from wagtail_svgmap.tests.utils import EXAMPLE2_SVG_DATA, IDS_IN_EXAMPLE2_SVG, IDS_IN_EXAMPLE_SVG ...
from zeus import factories from zeus.constants import Status from zeus.tasks import process_artifact def test_aggregates_upon_completion(mocker, default_job): manager = mocker.Mock() artifact = factories.ArtifactFactory(job=default_job, queued=True) process_artifact(artifact_id=artifact.id, manager=mana...
import logging from django.core.management.base import BaseCommand from handler.event_bot import event_bot from events.settings import PROXY logger = logging.getLogger(__name__) class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('token', type=str) def handle(self, *arg...
""" Unit tests for the Subject factory """ import os from django.test import TestCase from richie.apps.courses.factories import SubjectFactory class SubjectFactoriesTestCase(TestCase): """ Unit test suite to validate the behavior of the Subject factory """ def test_factories_subject_logo(self): ...
import asyncio from scp import user from scp.utils import parser from pyrogram.types import ( Message, ) __PLUGIN__ = 'create' __DOC__ = str( user.md.KanTeXDocument( user.md.Section( 'create', user.md.SubSection( 'create a super group / channel / bot', ...
#!/usr/bin/env python3 """ Generate f32x4 floating-point arithmetic operation cases. """ from simd_f32x4_arith import Simdf32x4ArithmeticCase from simd_float_op import FloatingPointArithOp class F64ArithOp(FloatingPointArithOp): maximum = '0x1.fffffffffffffp+1023' class Simdf64x2ArithmeticCase(Simdf32x4Arithm...
class Metric(object): ''' Interface class for the various metrics. ''' def calculate(self, node): ''' Calculate the metric for the given node. A metric may be a number, a string or any other measurable value about the code. ''' raise NotImplementedError('{}.calc...
""" ccextractor-web | TestUpload.py Author : Saurabh Shrivastava Email : saurabh.shrivastava54+ccextractorweb[at]gmail.com Link : https://github.com/saurabhshri """ import unittest from run import app, createConfig class TestUpload(unittest.TestCase): def setUp(self): createConfig() def t...
import argparse import sys from typing import Sequence from exabel_data_sdk import ExabelClient from exabel_data_sdk.client.api.bulk_insert import BulkInsertFailedError from exabel_data_sdk.client.api.data_classes.entity import Entity from exabel_data_sdk.scripts.csv_script import CsvScript from exabel_data_sdk.util.r...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 3/22/18 4:23 PM # @Author : Yuecheng Jing # @Site : www.nanosparrow.com # @File : ValidNumber.py # @Software: PyCharm class Solution(object): def isNumber(self, s): """ :type s: str :rtype: bool """ status_s...
from output.models.nist_data.list_pkg.duration.schema_instance.nistschema_sv_iv_list_duration_min_length_2_xsd.nistschema_sv_iv_list_duration_min_length_2 import NistschemaSvIvListDurationMinLength2 __all__ = [ "NistschemaSvIvListDurationMinLength2", ]
from __future__ import absolute_import from .gp import GP from .gp_classifier import GPClassifier __all__ = ["GP", "GPClassifier"]
''' Testes do formatador ''' import unittest from service.qry_options_builder import QueryOptionsBuilder class OptionsBuilderTest(unittest.TestCase): ''' Classe que testa a construção de options a partir dos parâmetros do request ''' def test_no_categories(self): ''' Verifica se o parâmetro obrigatório...
import json import datetime import requests import pymysql import pymongo def insert_category(conn): """将商品的种类插入数据库 """ # 商品种类的 id 和对应的名称 categories_dict = { 66: "手机", 327: "腕表配饰", 65: "电脑办公", 67: "相机单反", 217: "平板数码", 179: "运动户外", 255: "家电家居", ...
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. # from asyncio import sleep from pylast import User, WSError from re import sub from urllib import parse from os import ...
class card: def __init__(self,card,account,description,pin,seq,auth,active): self.card = card self.account = account self.description = description self.pin = pin self.seq = seq self.auth = auth self.active = active def setActive(self,v): self.act...
from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django.contrib.sites.shortcuts import get_current_site from django.core.mail import send_mail from django.core.paginator import Paginator from django.shortcuts import render, ...
import pandas as pd import numpy as np import copy from tqdm import tqdm from typing import List, Dict import model as m from db import PostgresDB as db from sql import script_get_customer_data, \ script_get_customer_last_price, \ script_update_customer_stocks class Customer(): # Структура по...
import ds_format as ds import json from ds_format.cmd import UsageError, NumpyEncoder def get(*args, **opts): if len(args) != 2: raise TypeError('Usage: get <path> <input>') path = args[0].split('/') input_ = args[1] d = ds.from_netcdf(input_, []) if len(path) == 2 and path[0] == '' and path[1] == '': j = j...
from copy import deepcopy from eth2spec.test.context import spec_state_test, with_all_phases from eth2spec.test.helpers.state import ( next_epoch, next_slot ) from eth2spec.test.helpers.block import apply_empty_block from eth2spec.test.helpers.attestations import ( add_attestation_to_state, fill_aggreg...
""" Module with models definitions """ import pickle import numpy as np class Model: """ Machine learning model, built from layers """ def __init__(self, layers): """ Constructor :param layers: list of Layers instances """ self.layers = layers outpu...
class SayPlugin: def __init__(self, config): super(SayPlugin, self).__init__() self.config = config # pylint: disable=no-self-use def execute(self, context): entities = context.nlp_analysis.entities result = {} result["query"] = entities["query"] response ...
import hashlib import os from StringIO import StringIO from tarfile import TarFile from tempfile import NamedTemporaryFile from urllib import quote from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.test import Client, TestCase from tardis.tardis_portal.models import ...
from abc import ABC from datetime import datetime, timedelta from unittest.mock import patch from django.contrib.auth.models import Permission from django.core.exceptions import ValidationError from django.test import TestCase from django.utils import timezone from django.utils.dateparse import parse_time from news.m...
import numpy as np from scipy.signal import savgol_filter import matplotlib.pyplot as plt import MadDog x = [] y = [] def generate(): # Generate random data base = np.linspace(0, 5, 11) # base = np.random.randint(0, 10, 5) outliers = np.random.randint(10, 20, 2) data = np.concatenate((base, outli...