content stringlengths 5 1.05M |
|---|
import pytest
from django.http import HttpResponse
from apirouter import APIRouter
from apirouter.exceptions import APIException
pytestmark = [pytest.mark.urls(__name__)]
def exception_handler(request, exc):
return HttpResponse(str(exc), status=400)
router = APIRouter(exception_handler=exception_handler)
@r... |
from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "HAA"
addresses_name = "2021-03-25T12:55:41.884654/Democracy_Club__06May2021.tsv"
stations_name = "2021-03-25T12:55:41.884654/Democracy_Club__06May2021.tsv"
... |
from intent_parser.protocols.lab_protocol_accessor import LabProtocolAccessor
from intent_parser.protocols.labs.aquarium_opil_accessor import AquariumOpilAccessor
from intent_parser.protocols.labs.strateos_accessor import StrateosAccessor
from intent_parser.protocols.templates.experimental_request_template import Exper... |
import matplotlib as mpl
mpl.use("Agg") # Must come after importing mpl, but before importing plt
import matplotlib.pyplot as plt |
from typing import Callable
from rx3.core import Observable
def _skip_last(count: int) -> Callable[[Observable], Observable]:
def skip_last(source: Observable) -> Observable:
"""Bypasses a specified number of elements at the end of an
observable sequence.
This operator accumulates a queue... |
import os
import timeit
import numpy as np
from collections import defaultdict
#from scikits.talkbox.features import mfcc
from python_speech_features import mfcc
from sklearn.metrics import precision_recall_curve, roc_curve
from sklearn.metrics import auc
from sklearn.cross_validation import ShuffleSplit
from sklearn... |
#!/usr/bin/env python2
from __future__ import division, print_function, absolute_import
# Import ROS libraries
import roslib
import rospy
import rosbag
import numpy as np
import time
# Import class that computes the desired positions
from tf.transformations import euler_from_quaternion
from geometry_msgs.msg import ... |
import numpy as np
from unittest import mock
from unittest.mock import MagicMock, Mock, create_autospec
from napari_allencell_segmenter.view.workflow_steps_view import (
WorkflowStepsView,
IWorkflowStepsController,
SegmenterModel,
)
from aicssegmentation.workflow import WorkflowEngine
class TestWorkflowS... |
import uuid
import pytest
from citrine.informatics.workflows import PredictorEvaluationWorkflow
from citrine.resources.predictor_evaluation_workflow import PredictorEvaluationWorkflowCollection
from tests.utils.session import FakeSession, FakeCall
@pytest.fixture
def session() -> FakeSession:
return FakeSession... |
"""
.. warning:: `logging` package has been renamed to `loggers` since v0.7.0 and will be removed in v0.9.0
"""
from pytorch_lightning.loggers.comet import CometLogger # noqa: F403
|
import json
import logging
from django.core.management import BaseCommand
from runner.config import KAFKA_TRANS_TOPIC, METRICS_WHITELIST, KAFKA_PREP_TOPIC
from runner.constants import VTRANSCODER_3D, VTRANSCODER_3D_SPECTATORS
from runner.utils.kafka import KafkaExporter, init_consumer_and_subscribe
logger = logging.... |
import cv2
import numpy as np
import random
import matplotlib.pyplot as plt
import os
from ReadCameraModel import ReadCameraModel
from UndistortImage import UndistortImage
import copy
from numpy.linalg import matrix_rank
import pandas as pd
l = []
frames = []
pathimage="/home/arjun/Desktop/VOM/Oxford_dataset/stereo/ce... |
from unittest import TestCase
from parameterized import parameterized
import case_conversion
ACRONYMS = ["HTTP"]
ACRONYMS_UNICODE = ["HÉÉP"]
CASES = [
"camel",
"pascal",
"snake",
"dash",
"dash",
"const",
"const",
"dot",
]
CASES_PRESERVE = [
"separate_words",
"slash",
"ba... |
__author__ = 'Robert Meyer'
import time
import sys
import pickle
try:
from collections import Set, Sequence, Mapping
except ImportError:
from collections.abc import Set, Sequence, Mapping
import pandas as pd
import numpy as np
import random
import copy as cp
from pypet.tests.testutils.ioutils import run_suit... |
"""This module defines the asynchronous reliable workflow."""
import asyncio
import functools
from typing import Tuple, Optional, List, Dict
from xml.etree import ElementTree as ET
import utilities.integration_adaptors_logger as log
from comms import queue_adaptor
from isodate import isoerror
from tornado import httpc... |
# -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod
class Scanner(metaclass=ABCMeta):
EOF = None
def __init__(self, source):
self.source = source
self.cur_token = None
def current_token(self):
return self.cur_token
def next_token(self):
self.cur_token = ... |
from django.core.management.base import BaseCommand
from django.core.files import File
import os
import exifread
from data.models import SkyPicture, MeasuringDevice
import datetime
from fractions import Fraction
from data.tasks import gator, computeProjection
class Command(BaseCommand):
help = 'Import sky images ... |
import numpy as np
from qflow.wavefunctions import SimpleGaussian
from qflow.hamiltonians import HarmonicOscillator
from qflow.samplers import ImportanceSampler
from qflow.statistics import compute_statistics_for_series, statistics_to_tex
from qflow.mpi import mpiprint
N, D = 100, 3
system = np.empty((N, D))
H = Harm... |
# -*- coding: utf-8 -*-
# Copyright 2020 Kevin Schlosser
import datetime
import threading
from ..utils import (
get_bit as _get_bit,
set_bit as _set_bit
)
from ..packet import (
GetConfigurationRequest,
GetStatusRequest
)
from ..commands import (
FanKeySelection,
HeatDemand,
AuxHeatDemand... |
# Generated by Django 2.0.3 on 2018-08-07 10:47
import json
from django.contrib.postgres import fields
from django.db import migrations
from saleor.page.models import Page
from saleor.product.models import Category, Collection
def get_linked_object_kwargs(object):
return {"pk": object.pk, "slug": object.slug}
... |
import os
from os import listdir
from os.path import isdir, isfile, join
import cv2
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.vgg16 import preprocess_input
import numpy as np
class bilddatensatz:
#
# Geht alle Unterverzeichniss des angegebenen
# Wurzelverze... |
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
import numpy as np
import os
import snnn
model = load_model('./model.h5')
predictDir = './predict'
files = os.listdir(predictDir)
classDict = {v: k for k, v in snnn.getClassesDict().items()}
info = '\n\nGradua... |
from flask import render_template,request,redirect,url_for,abort,request
from ..models import User,Pitch,Comment,Upvote,Downvote
from . import main
from flask_login import login_required,current_user
from .forms import UpdateProfile,PitchForm,CommentForm
from .. import db,photos
# Views
@main.route('/')
def index():
... |
# -*- coding: utf-8 -*-
"""
Name:
gist
Usage:
gist list
gist edit <id>
gist description <id> <desc>
gist info <id>
gist fork <id>
gist files <id>
gist delete <ids> ...
gist archive <id>
gist content <id> [<filename>] [--decrypt]
gist create <desc> [--public] [--encrypt] [FIL... |
#part1
# Merge the ridership and cal tables
ridership_cal = ridership.merge(cal, on=['year','month','day'])
#part2
# Merge the ridership, cal, and stations tables
ridership_cal_stations = ridership.merge(cal, on=['year','month','day']) \
.merge(stations,on=['station_id'])
#part3
# Merg... |
#testing.py
#login = 'westcoastautos'
#password = '1qazxsw2'
from opensourcebotsfuckyeah import *
def input_master(inputFileName):
if '.txt' not in inputFileName:
inputFileName += '.txt'
return inputFileName
inputFileName = input("Enter the name of the .txt file containing hashtags to sear... |
from django.conf.urls import patterns
from rboard_bugzilla.extension import BugzillaExtension
from rboard_bugzilla.forms import BugzillaSiteForm
urlpatterns = patterns('',
(r'^$', 'reviewboard.extensions.views.configure_extension',
{'ext_class': BugzillaExtension,
... |
# Generated by Django 2.1 on 2018-08-24 16:49
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('api', '0003_auto_20180822_... |
# Lists More Advanced
# Loops and lists
inMyBag = ['pen' , 'book' , 'sandwich' , 'rope']
for i in range(len(inMyBag)):
print('Index no. ' + str(i) + ' holds a ' + inMyBag[i]) # Everything in my bag
# The in/not in operators
print('There is a pen in my bag: ' + str('pen' in inMyBag)) # True
print('T... |
from abc import ABCMeta, abstractmethod
from pyppeteer import launch
import requests
from pypp_cookie import get_cookies
class CookiesGetter(metaclass=ABCMeta):
def __init__(self,uid:str,password:str,page=None) -> None:
self.page = page
self.username = uid
self.password = password
@... |
import os
import time
from .constraint import DenialConstraint
class Parser:
"""
This class creates interface for parsing denial constraints
"""
def __init__(self, env, dataset):
"""
Constructing parser interface object
:param session: session object
"""
self.en... |
def raiseExceptionDoNotCatch():
try:
print("In raiseExceptionDoNotCatch")
raise Exception
finally:
print("Finally executed in raiseExceptionDoNotCatch")
print("Will never reach this point")
print("\nCalling raiseExceptionDoNotCatch")
try:
raiseExceptionDoNotCatch()
except Exception:
... |
from strategy.rebalance import get_relative_to_expiry_rebalance_dates, \
get_fixed_frequency_rebalance_dates, \
get_relative_to_expiry_instrument_weights
from strategy.calendar import get_mtm_dates
import pandas as pd
import pytest
from pandas.util.testing import assert_index_equal, assert_frame_equal
def ass... |
#!/usr/bin/env python3.8
import json
import string
import sys
import urllib.request
url_base = "http://challenges2.france-cybersecurity-challenge.fr:6005/check"
COMPILE_SUCCESS = '{"result":0}'
COMPILE_FAILURE = '{"result":1}'
def get_size() -> int:
size = 0
while 1:
data = {"content":"let my_string :... |
#!/home/sonic/anaconda3/envs/astroconda/bin/python
# -*- coding: utf-8 -*-
#============================================================
# IMSNG MONITORING NEW TRANSIENT WITH TNS QUERY CODE
# 2017.09.14 CREATED BY Nikola Knezevic
# 2019.08.06 MODIFIED BY Gregory S.H. Paek
# 2019.08.07 MODIFIED BY Gregory S.H. Paek
# 20... |
emptyForm = """
{"form": [
{
"type": "message",
"name": "note",
"description": "Connect to graphql"
},
{
"name": "url",
"description": "Graphql URL",
"type": "string",
"required": true
}
]}
"""
|
"""Input params handlers."""
from datetime import datetime
import re
from typing import List, Optional
from InquirerPy import inquirer # type: ignore
from redbrick.cli.cli_base import CLIInputParams
class CLIInputProfile(CLIInputParams):
"""Input profile handler."""
def __init__(
self,
ent... |
from __future__ import annotations
import datetime
import itertools
from tkinter import messagebox
from typing import List
import arkhesPlaylists
from spotifyWrapper import spotify_wrapper
class ArkhesResource:
def __init__(self, data_dict: dict) -> None:
self._data_dict = data_dict
self._line = ''
... |
# bit count library
# bitcount(val) returns number of set bits in val
# import the function bitcount()
__bctable__={}
__bctable__[0]=0
__bitmaskCacheBits__=16
#bitmaskCache=int("1"*8,2)
bitmaskCache=int("1"*__bitmaskCacheBits__,2)
#bitmaskCache=int("1"*32,2)
def __bitcountCache__(v0):
if v0 in __bctable__:
... |
#!/usr/bin/env python
import os
import stat
import tempfile
import re
import getpass
import json
spy_file_pattern = re.compile(r'(.*)\.spy$')
shellpy_meta_pattern = re.compile(r'#shellpy-meta:(.*)')
shellpy_encoding_pattern = '#shellpy-encoding'
def preprocess_module(module_path):
"""The function compiles a modu... |
import numpy as np
test_data = np.array([16, 1, 2, 0, 4, 2, 7, 1, 2, 14])
np_data = np.loadtxt("data.txt", delimiter=",", dtype=int)
def one(data: np.ndarray) -> int:
"""
Determine the horizontal position that the crabs can align to using the least fuel possible. How much fuel must they
spend to align to... |
class Meta(type):
def __init__(cls, name, bases, namespace):
super(Meta, cls).__init__(name, bases, namespace)
print("Creating new class: {}".format(cls))
def __call__(cls):
new_instance = super(Meta, cls).__call__()
print("Class {} new instance: {}".format(cls, new_instance))
... |
import os, sys
import numpy as np
import random
import copy
import torch
import torch.autograd as autograd
from torch.autograd import Variable
from torch.utils.data import DataLoader, Dataset, TensorDataset
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from torch.utils.... |
"""Main module."""
import io
import pathlib
import time
import warnings
from pprint import pformat
from typing import Callable, Dict, List, Tuple, Union
from collections import Counter
import numpy as np
import pyqms
import scipy as sci
from intervaltree import IntervalTree
from loguru import logger
from psims.mzml im... |
"""This module contains the "Viz" internal simpleflow plugin objects
These plugin objects represent the backend of all the visualizations that
Superset can render for simpleflow
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unico... |
import numpy as np
import bempp.api
def direct(dirichl_space, neumann_space, q, x_q, ep_in, ep_out, kappa, operator_assembler):
from bempp.api.operators.boundary import sparse, laplace, modified_helmholtz
identity = sparse.identity(dirichl_space, dirichl_space, dirichl_space)
slp_in = laplace.singl... |
import io
class Decode:
"""
Decode primitive values from bytes.
"""
@staticmethod
def u8(b):
assert len(b) == 1
return b[0]
@staticmethod
def u16(b):
assert len(b) == 2
return b[0] << 8 | b[1]
@staticmethod
def u24(b):
assert len(b) == 3... |
# -*- coding: utf-8 -*-
#
# Licensed under the terms of the BSD 3-Clause or the CeCILL-B License
# (see codraft/__init__.py for details)
"""
CodraFT, the Codra Filtering Tool
Simple signal and image processing application based on guiqwt and guidata
Starter
"""
from codraft.app import run
run()
|
from fast_import import *
import sys
arg = sys.argv[1:]
#arg = ['offline']
mode = arg[0]
save = True
filename = mode+'_npz/'+'cb_al_'+mode+'.npz'
if len(arg)>1: eurm_k= int(arg[1])
else: eurm_k = 750
configs =[
{'cat':2, 'alpha':1, 'beta':0, 'k':60, 'shrink':0,'threshold':0 },
{'cat':3, 'alpha':0.75, 'beta':... |
# Copyright 2015 Technische Universitaet Berlin
# 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
#
# Unle... |
import numpy as np
import typing
import time
import tensorflow as tf
# convenient abbreviations
tfk = tf.keras
tfka = tfk.activations
tfkl = tf.keras.layers
# adversarial convolutional autoencoder
class AAE(object):
def __init__(self,
latent_dim: int, # latent dimension of style vector
n... |
''' This submodule provides basic preprocessing functionality to work with hyperspectral data/images.
E.g.
- Normalization
- Baseline Correction/Removal
- RGB-Image standardization
- Scatter correction (especially RMieS-correction)
- Data transformations from 3D to 2D and reverse
- ...
'''
# IMPORTS
#########
impor... |
# Lint as: python3
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
from django.db import models
from django.contrib.auth import get_user_model
# Create your models here.
User = get_user_model()
class Follow(models.Model):
from_user = models.ForeignKey(User,
on_delete=models.CASCADE,
related_name="following")
... |
import exceptions, os
from pypy.tool import slaveproc
class IsolateException(Exception):
pass
class IsolateInvoker(object):
# to have a nice repr
def __init__(self, isolate, name):
self.isolate = isolate
self.name = name
def __call__(self, *args):
return self.isolate._inv... |
from datetime import datetime, date
from decimal import Decimal
from typing import Tuple, Any, Optional, Dict
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import transaction
from django.utils.dateparse import parse_date
from django.utils.translation import gettext ... |
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional
__NAMESPACE__ = "NISTSchema-SV-IV-atomic-unsignedByte-enumeration-5-NS"
class NistschemaSvIvAtomicUnsignedByteEnumeration5Type(Enum):
VALUE_1 = 1
VALUE_21 = 21
VALUE_55 = 55
VALUE_9 = 9
VALUE_132 = 132
... |
# setup.py
import configparser
import os
import const
config = configparser.RawConfigParser()
setup_path = os.path.dirname(os.path.realpath(__file__))
config.read(setup_path + '/config.ini')
config = config[const.DEFAULT]
|
#Desafio 8 Escreva um programa que leia um valor em metros e o exiba convertido em centímetro e milímetros
print('{:=^20}'.format('Desafio 8'))
metros=float(input('Quantos metros ? '))
KM=metros/1000
hm=metros/100
decam=metros/10
diam=metros*10
cent=metros*100
mili=metros*1000
print('Conversão de {}m para demais unid... |
import json
import datetime
from bson import json_util
from tests.TestingSuite import BaseTestingSuite
class TestIotUpdateResource(BaseTestingSuite):
def setUp(self):
print("Testing Iot Update resources...")
super().setUp()
def test_successful_iot_entry(self):
new_entry = {
... |
#!/usr/bin/env python3
from argparse import ArgumentParser
from glob import glob
from os import path
from subprocess import run, CalledProcessError
from tempfile import TemporaryDirectory
from zipfile import ZipFile, BadZipFile
from database.connection_manager import get_connection
from database.database_config import... |
from django.db import models
from django.conf import settings
class Note(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='notes')
subject = models.CharField(max_length=100)
note = models.TextField(blank=True,null=True)
|
#!/usr/bin/env python
# Copyright (c) 2006-2019 Andrey Golovigin
#
# 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, cop... |
from Utils.string_utils import clear_spaces as clear
def test_validation_all_contacts_info(app, db):
ui_contacts_list = app.contact.get_contact_list()
db_contacts_list = db.get_contact_list()
assert len(ui_contacts_list) == len(db_contacts_list)
for ui_contact in ui_contacts_list:
db_contact =... |
test = {
'name': 'Question 11',
'points': 2,
'suites': [
{
'cases': [
{
'code': r"""
>>> swap_strategy(12, 60, 8, 6)
962aea5f59fc55bd65ccacf4603c8f22
# locked
""",
'hidden': False,
'locked': True
},
{
... |
class BackendPortPortNumber(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_backend_port_port_number(idx_name)
class BackendPortPortNumberColumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_backend_ports()
|
def additive_hash(input_string: str) -> int:
"""A stable hash function."""
value = 0
for character in input_string:
value += ord(character)
return value
|
"""
Functions for reading and processing input data
"""
import os
import sys
from pathlib import Path
import numpy as np
import pandas as pd
import pickle as pkl
from sklearn.model_selection import KFold, StratifiedKFold
from sklearn.preprocessing import MinMaxScaler
import pancancer_evaluation.config as cfg
def lo... |
try:
import binutil # required to import from dreamcoder modules
except ModuleNotFoundError:
import bin.binutil # alt import if called as module
from neural_seq.model import main
from neural_seq.utils import commandLineArgs
from neural_seq import decoderUtils
import os
if __name__ == '__main__':
print("... |
# This file contains the objects to be used in conjunction with SQLAlchemy
# Separating this file into so that the cloud computing elements are in their own module would allow
# for a more loosely coupled architecture.
import string
import random
import boto3
from sqlalchemy import create_engine, Column, Integer, Stri... |
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class Finca(models.Model):
nombre_finca = models.CharField(max_length=150, unique=True)
ubicacion = models.CharField(max_length=150)
latitud = models.CharField(max_length=150)
longitud = models... |
#!/usr/bin/env python
# D. Nidever
#
# testdlinterface.py
# Python code to (unit) test the DL Interface operations
from dl.dlinterface import Dlinterface
from dl import authClient, storeClient, queryClient
import os
import unittest
try:
from urllib import urlencode, quote_plus # Python 2
from urllib2 i... |
# -*- coding: utf-8 -*-
## \package globals.debug
# MIT licensing
# See: LICENSE.txt
from globals.commandline import GetOption
class dmode:
QUIET = 0
INFO = 1
WARN = 2
ERROR = 3
DEBUG = 4
name = {
QUIET: u'QUIET',
INFO: u'INFO',
WARN: u'WARN',
ERROR: u'ERRO... |
import numpy as np
from . import UncertMath
class ClusterList(object):
def __init__(self,ratios,nbins):
super(ClusterList, self).__init__()
self.nbins = nbins
self.ratios = ratios
# Create an array to hold bin assignments and initial set all to -1 == not clustered
self.... |
import logging
from django.db import models
from polymorphic.models import PolymorphicModel
from cabot.cabotapp.utils import create_failing_service_mock
logger = logging.getLogger(__name__)
class AlertPlugin(PolymorphicModel):
title = models.CharField(max_length=30, unique=True, editable=False)
enabled = m... |
from statistics import median
map_open_close = {"{": "}", "[": "]", "(": ")", "<": ">"}
score_part_1 = {
"}": 1197,
"]": 57,
")": 3,
">": 25137,
}
score_part_2 = {
"}": 3,
"]": 2,
")": 1,
">": 4,
}
def score_line(line: str) -> tuple[int, int]:
"""if the line is corrupted, then c... |
from dataclasses import dataclass
from typing import ClassVar
import datetime
@dataclass
class Some_Class:
some_const: ClassVar[int] = 20
some_int: int
some_float: float
some_float_less_than_3: float
some_datetime: datetime.datetime
some_use_of_const: int
def __post_init__(self):
... |
"""使用Python实现选择排序,并分析时间复杂度"""
#时间复杂度:O(n**2)
def selection_sort(lst):
for i in range(len(lst) - 1):
min_index = i
for j in range(i + 1, len(lst)):
if lst[j] < lst[min_index]:
min_index = j
if min_index != i:
lst[i], lst[min_index] = lst[min_... |
# -*- coding: utf-8 -*-
"""Implements a simple wrapper around urlopen."""
import logging
from functools import lru_cache
from http.client import HTTPResponse
from typing import Iterable, Dict, Optional
from urllib.request import Request
from urllib.request import urlopen
logger = logging.getLogger(__name__)
def _ex... |
from math import pi, sin, cos
import random
import pygame
from level import TILE_SIZE, CHARGERS_PER_STATION, tilepos_to_screenpos
from level import NORTH, EAST, SOUTH, WEST
from sensor import tiles_to
from main import FRAME_RATE
texture = pygame.image.load("res/robot{}.png".format(TILE_SIZE))
texture_unloading = pyg... |
from typing import List, Tuple, Optional
import numpy as np
from banditpylib.arms import PseudoArm
from .utils import OrdinaryLearner
class UCBV(OrdinaryLearner):
r"""UCBV policy :cite:`audibert2009exploration`
At time :math:`t`, play arm
.. math::
\mathrm{argmax}_{i \in [0, N-1]} \left\{ \hat{\mu}_i(t)... |
# -*- 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... |
# Licensed to the StackStorm, Inc ('StackStorm') 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, Version 2.0
# (the "License"); you may not use th... |
#!/usr/bin/env python
import twder
import unittest
import datetime
class TestStringMethods(unittest.TestCase):
def all_element_is_str(self, container):
for e in container:
self.assertIsInstance(e, str)
def check_range_result(self, range_result):
self.assertIsInstance(range_result... |
from django.contrib import admin
from .models import LearningResources
@admin.register(LearningResources)
class ArticleAdmin(admin.ModelAdmin):
list_display = ['title', 'order', 'url', 'desc']
list_editable = ['order']
|
"""
.. module:: test_datautil
:synopsis: Unit tests for datautil module
"""
import pytest
import numpy as np
import collections as cl
import nutsml.datautil as util
from nutsflow.common import StableRandom
@pytest.fixture(scope="function")
def sampleset():
"""Return list with 50 positive and 10 negative sam... |
#! /usr/bin/env python
"""
Unit tests for landlab.collections
"""
import pytest
from landlab import Arena, Implements, ImplementsOrRaise, NoProvidersError, Palette
from landlab.framework.interfaces import BmiBase, BmiNoGrid
@Implements(BmiBase)
class Sample1(object):
"""A sample component."""
__implements_... |
__author__ = 'jie'
import sys
from initialization import initAppWithGui
def main(args):
app = initAppWithGui(args)
sys.exit(app.exec_())
if __name__ == '__main__':
main(sys.argv)
|
#== __init__.py ==#
from .main import GHClient
__title__ = 'GitHubAPI'
__author__ = 'sudosnok'
__version__ = '0.0.1'
|
from multiprocessing import freeze_support
from fashionscrapper.brand.asos.helper.database.dbhelper import list_dbs_by_category
from fashionscrapper.brand.hm.HM import HM
from fashionscrapper.brand.hm.consts.parser import *
from fashionscrapper.brand.hm.helper.download.HMPaths import HMPaths
from fashionscrapper.brand... |
""""""
from __future__ import annotations
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.pyplot import figure
from panter.data.dataMisc import ret_hist
output_path = os.getcwd()
plt.rcParams.update({"font.size": 12})
bfound_root = True
try:
from ROOT import TF... |
__author__ = 'rvuine'
import json
import os
from micropsi_core.tools import post_mortem
from micropsi_core.nodenet import monitor
from micropsi_core.nodenet.node import Nodetype
from micropsi_core.nodenet.nodenet import Nodenet, NODENET_VERSION
from micropsi_core.nodenet.stepoperators import DoernerianEmotionalModula... |
# Generated by Django 4.0.3 on 2022-03-17 07:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('polls', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='question',
name='question_desc',
... |
# Generated by Django 2.0.5 on 2018-06-11 17:17
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import re
class Migration(migrations.Migration):
dependencies = [
('paikkala', '0005_program_automatic_max_tickets'),
]
operations = [
... |
"""Vera tests."""
from unittest.mock import MagicMock
from pyvera import VeraBinarySensor
from homeassistant.core import HomeAssistant
from .common import ComponentFactory
async def test_binary_sensor(
hass: HomeAssistant, vera_component_factory: ComponentFactory
) -> None:
"""Test function."""
vera_de... |
# Copyright 2019 DeepMind Technologies Ltd. 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 appl... |
"""
textgame.player
=====================
This module contains a class :class:`textgame.player.Player` that is used to define
what a player is able to do in the game. Every of its methods that get called by
:class:`textgame.parser.Parser` must take a noun (string) as an argument and return
either a string that describ... |
"""added directionality
Revision ID: 2de7150f9351
Revises: 85b225ba7bce
Create Date: 2021-08-27 10:06:09.044287
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '2de7150f9351'
down_revision = '85b225ba7bce'
branch_labels = No... |
#We want a single reference for the mediator to be used in all classes.
#For now just make it a static class variable
from mediator import Mediator
class MediatorResource:
Mediator = Mediator()
|
from django.conf import settings
import logging
from selenium import webdriver
from retry import retry
logger = logging.getLogger(__name__)
class WebDriverSingleton(object):
_instance = None
@classmethod
def instance(cls):
if cls._instance is None:
cls._instance = WebDriverSingleton... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.