content stringlengths 4 20k |
|---|
import base64
import hashlib
import os
import zlib
def copy_from_host(module):
compress = module.params.get('compress')
src = module.params.get('src')
if not os.path.exists(src):
module.fail_json(msg="file not found: {}".format(src))
if not os.access(src, os.R_OK):
module.fail_json(ms... |
import pyspeckit
import numpy as np
from pyspeckit.spectrum.models import inherited_voigtfitter
# technically, the voigt fitter works as a singlefitter (i.e., you can fit the
# background level and the peak simultaneously)
# in practice, however, you need to fit the background independently except for
# gaussians. I... |
# -*- coding: utf-8 -*-
"""
InaSAFE Disaster risk assessment tool developed by AusAid -
**metadata utilities module.**
Contact : <EMAIL>
.. versionadded:: 3.3
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
... |
import torch
from torch.distributions import Transform, constraints
from pyro.distributions.conditional import ConditionalTransformModule
from pyro.distributions.torch_transform import TransformModule
from pyro.distributions.util import copy_docs_from
from pyro.nn import DenseNN
@copy_docs_from(Transform)
class Cond... |
from __future__ import absolute_import, division, print_function
import os.path
import yaml
from appr.formats.appr.manifest import ManifestBase
from appr.pack import all_files
from appr.render_jsonnet import RenderJsonnet, yaml_to_jsonnet
__all__ = ['ManifestJsonnet']
MANIFEST_FILES = ['manifest.jsonnet', 'manifes... |
import logging
_LOG = logging.getLogger("gui.widgets.reorderfam")
#-------------------------------------------------------------------------
#
# GTK/Gnome modules
#
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
#
#... |
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.11.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
... |
from optparse import make_option
from subprocess import Popen, PIPE
from django.conf import settings
from django.core.mail import mail_admins
from django.core.management.base import BaseCommand
from dynamic_scraper.models import Scraper
class Command(BaseCommand):
help = 'Runs all checker tests'
option_li... |
"""Invenio Alert Engine config parameters."""
__revision__ = \
"$Id$"
# are we debugging?
## 0 = production, nothing on the console, email sent
## 1 = messages on the console, email sent
## 2 = messages on the console, no email sent
## 3 = many messages on the console, no email sent
## 4 = many messages on the co... |
import gtk
import glib
import gobject
import datetime
from math import pi as M_PI
M_PI_1_5 = M_PI*1.5
M_PI_0_5 = M_PI*0.5
from EventWidget import EventWidget
from agenda import FilterType
from agenda import ANOTHER_DAY_FMT
from agenda import get_timeout_add_time
class DateWidget (gtk.EventBox):
__gtype_name__ ... |
import pytest
from plenum.common.messages.node_messages import BackupInstanceFaulty
from plenum.common.types import f
from plenum.server.backup_instance_faulty_processor import BackupInstanceFaultyProcessor
from plenum.server.quorums import Quorums
from plenum.server.replica import Replica
from plenum.server.suspicion... |
#!/usr/bin/env python
import urllib
import urllib2
import json
# Append the service name to this base URL, eg 'con', 'obs', etc.
BASEURL = 'http://mwa-metadata01.pawsey.org.au/metadata/'
def getmeta(service='obs', params=None):
"""
Function to call a JSON web service and return a dictionary:
Given a JSON web ... |
"""
Tests For Console proxy.
"""
import datetime
from nova import context
from nova import db
from nova import exception
from nova import flags
from nova import test
from nova import utils
from nova.auth import manager
from nova.console import manager as console_manager
FLAGS = flags.FLAGS
class ConsoleTestCase(te... |
"""
SALTS XBMC Addon
Copyright (C) 2014 tknorris
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
T... |
'''
Analyzers that produce data models from Binary blobs
@author: Michael Eddington
@version: $Id$
'''
#
# Copyright (c) Michael Eddington
#
# 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... |
# -*- test-case-name: higgins.http.test.test_stream -*-
import time, os
from higgins.http import http, http_headers, responsecode, stream
# Some starts at writing a response filter to handle request ranges.
class UnsatisfiableRangeRequest(Exception):
pass
def canonicalizeRange((start, end), size):
"""Retur... |
import psycopg2
import csv
def connectToDatabase(hostname, username, password, database):
try:
connectString = "dbname='" + str(database) + "' user='" + str(username) + "' host='" + str(hostname) + "' password='" + str(password) + "'"
conn = psycopg2.connect(connectString)
return conn
ex... |
import jmespath
from c7n_gcp.provider import resources
from c7n_gcp.query import QueryResourceManager, TypeInfo
@resources.register('ml-model')
class MLModel(QueryResourceManager):
class resource_type(TypeInfo):
service = 'ml'
version = 'v1'
component = 'projects.models'
enum_spe... |
#!/usr/bin/env ambari-python-wrap
"""
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, Version 2.0 (the... |
from unittest import TestCase
from morelia.decorators import tags
from morelia.parser import DocStringParser, LabelParser, LanguageParser, LineSource
@tags(["unit"])
class LabelParserParseTestCase(TestCase):
""" Test :py:meth:`LabelParser.parse`. """
def test_should_return_false_if_line_without_labels(self)... |
# Задача 13. Вариант 50
# Разработайте искуственный интеллект для игры "Крестики-нолики"
# Alekseev I.S.
# 11.05.2016
from random import randint
# change size of board
size = 3
board = [ 0 ] * size * size
pics = [' . ', ' x ', ' o ']
def print_board (board):
print()
# upper numbers
for num in range(size):
... |
"""Devops module"""
from contextlib import suppress
from functools import partial
from gettext import gettext as _
import json
import logging
import os
import platform
import re
import umake.frameworks.baseinstaller
from umake.interactions import Choice, TextWithChoices, DisplayMessage
from umake.network.download_cent... |
#!/usr/bin/env python
# Content: Contains the main program of ab4. It compares harmonic series calculated with different number of addends.
# Task from Uebungsblatt 4 EWR
from __future__ import print_function
from decimal import *
from utils import *
from Sum import Sum
from DecimalComparer import DecimalComparer
f... |
__author__ = 'yupeng'
from temporal_network.tpnu import Tpnu
from tpn.tpn_autogen import tpn as ParseTpnClass
from collections import defaultdict
from graph_theory import spfa
from controllability.distance_graph_edge import EdgeType, DistanceGraphEdge
from controllability.temporal_consistency import EdgeSupport
impo... |
class PebbleError(Exception):
"""Pebble base exception."""
pass
class PoolError(PebbleError):
"""Raised if an error occurred within the Pool."""
pass
class TaskCancelled(PebbleError):
"""Raised if get is called on a cancelled task."""
pass
class TimeoutError(PebbleError):
"""Raised whe... |
from __future__ import unicode_literals
import frappe
import json
import random
from frappe.model.document import Document
class DesktopIcon(Document):
def validate(self):
if not self.label:
self.label = self.module_name
def on_trash(self):
clear_desktop_icons_cache()
def after_doctype_insert():
frappe.db... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
PySharkGui beta
This script create a simple tkinter GUI
to manage accounts and passwords using PyShark module
authors: tabuto83
last modified: May 2015
website:
"""
#from Tkinter import Tk, Text, BOTH, W, N, E, S
from pyshark import PyShark,PyLogin
from ttk import Fram... |
from glanceclient.v2 import client as glanceclient
from heatclient.v1 import client as heatclient
from oslo_config import cfg
from oslo_log import log as logging
from magnum.common import exception
from magnum.common import magnum_keystoneclient
from magnum.i18n import _
LOG = logging.getLogger(__name__)
heat_clie... |
from casing import title
from license import C_LICENSE_COMMENT
class Printer(object):
def __init__(self):
self._anyFieldIsANode = False
def start_file(self):
print C_LICENSE_COMMENT + '/** @generated */'
def end_file(self):
pass
def start_type(self, name):
self._anyFieldIsANode = False
de... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Post'
db.create_table(u'processing_post', (
(u'id', self.gf('django.db.models.fi... |
import unittest
import numpy
import copy
from TicTacToe import TicTacToe
class TicTacToeTests(unittest.TestCase):
def test_3_by_3_horizontal(self):
game = TicTacToe()
game.playX(0, 0)
self.assertFalse(game.isFinished())
game.playX(1, 0)
self.assertFalse(game.isFinished())
... |
from django import forms
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from web.generator.models import Template, Profile
from web.nodes import ipcalc
from datetime import datetime
import re
IPV4_ADDR_RE = re.compile(r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}... |
import os
import unittest
import utils
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
IMAGE_DIR = os.environ.get("IMAGE_DIR") or os.path.join(CURRENT_DIR, "..")
def get_dockerfile_path(image_dir):
return os.path.join(IMAGE_DIR, image_dir)
class BaseImageTest(unittest.TestCase):
def setUp(self):
... |
"""
Created on 9 Nov 2012
@author: plish
"""
class TrelloObject(object):
"""
This class is a base object that should be used by all trello objects;
Board, List, Card, etc. It contains methods needed and used by all those
objects and masks the client calls as methods belonging to the object.
"""
... |
from collections import defaultdict
from datetime import datetime
import logbot
import utils
import config
import inventory
from entities import Entities
from grid import Grid
from statistics import Statistics
from chat import Chat
from botentity import BotEntity
from signwaypoints import SignWayPoints
from eventregis... |
import eventlet
eventlet.monkey_patch(os=False)
import socket
from oslo.config import cfg
from oslo import messaging
_opts = [
cfg.StrOpt('host', default=socket.gethostname()),
]
CONF = cfg.CONF
CONF.register_opts(_opts)
class Server(object):
def __init__(self, transport):
self.target = messagin... |
from datetime import datetime
from datetime import timedelta
from todoman.cli import cli
from todoman.model import Database
from todoman.model import Todo
def test_priority(tmpdir, runner, create):
result = runner.invoke(cli, ["list"], catch_exceptions=False)
assert not result.exception
assert not result... |
from config import *
from MySQLdb import connect
from MySQLdb.cursors import DictCursor
from time import ctime
from requests import Session
import os
import codecs
# Change working directory to the directory of this script so log files
# are created in this directory no matter where the script is run
os.chdir(os.path.... |
from jsonrpc import ServiceProxy
import sys
import string
# ===== BEGIN USER SETTINGS =====
# if you do not set these you will be prompted for a password for every command
rpcuser = ""
rpcpass = ""
# ====== END USER SETTINGS ======
if rpcpass == "":
access = ServiceProxy("http://127.0.0.1:18823")
else:
access = Se... |
from shellforge.cpu_sparc import Binutils_sparc, CodeTuner_gcc_sparc as The_CodeTuner, Loaders_sparc as The_Loaders
class Binutils_linux_sparc(Binutils_sparc): # need to subclass for self.__module__ to return the correct arch
pass
The_Binutils = Binutils_linux_sparc |
import webob
from cinder.api import common
from cinder.api.openstack import wsgi
from cinder import exception
from cinder import volume
class Controller(wsgi.Controller):
"""The volume metadata API controller for the OpenStack API."""
def __init__(self):
self.volume_api = volume.API()
super(... |
"""This example gets all campaigns. To add a campaign, run add_campaign.py.
Tags: CampaignService.get
"""
__author__ = '<EMAIL> (Kevin Winter)'
import time
import os
import sys
sys.path.insert(0, os.path.join('..', '..', '..', '..', '..'))
# Import appropriate classes from the client library.
from adspygoogle impor... |
"""
core.version
"""
import commands
import ConfigParser
import json
import os
from datetime import datetime
def get_version_base__release_type__provides():
"""
get_version_base ... get version string base from the setup.cfg
"""
config = ConfigParser.ConfigParser()
config.read(os.path.dir... |
import uuid
import ddt
import mock
from oslo_config import cfg
from poppy.model import ssl_certificate
from poppy.storage.cassandra import certificates
from poppy.storage.cassandra import driver
from tests.unit import base
@ddt.ddt
class CassandraStorageCertificateTests(base.TestCase):
def setUp(self):
... |
import inspect
import re
#
# Reuseable IShards
#
def ShutdownHandler(self):
while self.dataReady("control"):
cmsg = self.recv("control")
if isinstance(cmsg, Axon.Ipc.producerFinished) or \
isinstance(cmsg, Axon.Ipc.shutdownMicroprocess):
self.send(cmsg, "signal")
... |
"""Support for Daikin AC sensors."""
import logging
from homeassistant.const import CONF_ICON, CONF_NAME, CONF_TYPE
from homeassistant.helpers.entity import Entity
from homeassistant.util.unit_system import UnitSystem
from . import DOMAIN as DAIKIN_DOMAIN
from .const import (
ATTR_INSIDE_TEMPERATURE,
ATTR_OUT... |
# -*- coding: utf-8 -*-
# Python stdlib
import unittest
# py.test
import pytest
# Python tfstate
from tfstate.provider.aws import AwsResource, DataAwsSecurityGroupResource
# Unit tests
from unit_tests.base import BaseResourceUnitTest
@pytest.mark.provider_aws
class DataAwsSecurityGroupResourceUnitTest(BaseResourc... |
import os
import subprocess
import platform
from . import requirements
from . _package_version_descriptor import PackageVersionDescriptor
from . _package_installer import PackageInstaller
def install_project_dependencies(project_dp, root_source_packages_dp=None, as_link=True, environment=None, destination_... |
import json
import sys
import re
import xml.etree.ElementTree as ET
def str2bool(v):
return v.lower() in ("yes", "true", "t", "1")
def parse_header(upf_dict, root):
# header
node = root.findall("./PP_HEADER")[0]
upf_dict['header'] = {}
upf_dict['header']['number_of_proj'] = int(node.attrib['number_o... |
import json
import time
import urllib
from tempest_lib import exceptions as lib_exc
from tempest.common import service_client
from tempest import exceptions
class BaseVolumesClientJSON(service_client.ServiceClient):
"""
Base client class to send CRUD Volume API requests to a Cinder endpoint
"""
cre... |
from django.test import TestCase
from django.contrib.auth import get_user_model
class TestPost(TestCase):
def setUp(self):
self.test_username = "test_user"
self.test_userpassword = "test_password"
user = self.user = get_user_model().objects.create_user(
username=self.test_use... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 8 14:45:34 2013
@author: localadmin
"""
import numpy as np
from matplotlib.path import Path
def sort_poly_verts(verts):
'''Sort polygon vertices by increasing angle from the centroid
Assumes convex polygon
'''
x, y = verts.T
x_cent, y_cent = np.me... |
#! /usr/bin/env python
"""Copyright (c) 2008, University of Cambridge.
All rights reserved.
Redistribution and use of this software in source and binary forms
(where applicable), with or without modification, are permitted
provided that the following conditions are met:
* Redistributions of source code must retai... |
import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-workflow',
version='0.1.0',
description="A lightweight workflow engine application for Django based web-applications.",
long_description=read('README.t... |
import datetime
import time
import matplotlib.pyplot as plt
import numpy as np
import pyautogui
import Calvar as var
def move_cursor():
pyautogui.moveTo(var.rand)
def open_IQ():
pyautogui.click(var.chrome)
move_cursor()
time.sleep(1)
def put():
pyautogui.click(var.put)
move_cursor()
def c... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
gdalcalc.py
---------------------
Date : Janaury 2015
Copyright : (C) 2015 by Giovanni Manghi
Email : giovanni dot manghi at naturalgis dot pt
**********... |
##Vector geometry tools=group
##Polygons=vector polygon
##To_keep=number 1
##Biggest parts=output vector
from qgis.core import Qgis, QgsGeometry, QgsWkbTypes
from operator import itemgetter
To_keep = int(To_keep)
if To_keep < 1:
progress.setInfo("'To keep' value has been modified to be at least 1.")
To_keep =... |
# encoding: utf-8
import os
import datetime
import json
from django.core.urlresolvers import reverse
from django.test import TestCase
from website.settings import BASE_DIR
from .models import Petition
from .forms import MemberForm
# @todo split in MemberTest and PettitionTest?
# A: yes, that is recomended
# @to... |
import sys
import time
import hashlib
import socketserver
import http.server
class HashHandler(http.server.BaseHTTPRequestHandler):
"""
"""
def do_GET(self):
resolution = time.clock_getres(time.CLOCK_MONOTONIC)
do_parse = False
if 't=' in self.path and self.path.split('t=', 1)[1]... |
from ChainingIterators import pySketchyChainingIterator
from freestyle import IncreasingColorShader, IncreasingThicknessShader, Operators, \
QuantitativeInvisibilityUP1D, SamplingShader, SmoothingShader, SpatialNoiseShader, \
TextureAssignerShader, TrueUP1D
from shaders import pyBackboneStretcherNoCuspShader
O... |
from __future__ import unicode_literals
"""Test MotorGridFSBucket."""
from io import BytesIO
from gridfs.errors import NoFile
from tornado import gen
from tornado.testing import gen_test
import motor
from test.tornado_tests import MotorTest
class MotorGridFSBucketTest(MotorTest):
@gen.coroutine
def _reset... |
"""
WSGI config for djangoapp project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`... |
"""Gnosis module offline training."""
import sys
import time
import os
from analytics_platform.kronos.gnosis.src.gnosis_package_topic_model import GnosisPackageTopicModel
from analytics_platform.kronos.gnosis.src.gnosis_ref_arch import GnosisReferenceArchitecture
from analytics_platform.kronos.src import config
import... |
"""Implementation of the class to deal with an UI element (based on UI Automation API)"""
from comtypes import COMError
from six import integer_types, text_type
from ctypes.wintypes import tagPOINT
from .uia_defines import IUIA
from .uia_defines import get_elem_interface
from .handleprops import dumpwindow, controli... |
# coding: utf-8
from Word import Word
import random
from datetime import datetime
class Recite (object):
def __init__(self, filename):
self.words = []
self.reciting_words = []
self.err_words = []
self.familiar_words = []
self.current_index = -1
self.shuffled = False
self.err_times_threshold = 0
try:
... |
import argparse
import json
import os
import sys
from . import TimeoutError, run_script
def main():
parser = argparse.ArgumentParser(description='Run tests.')
parser.add_argument('action', nargs='+', choices=['build', 'test'])
parser.add_argument('--workspace', required=True, help='Workspace to build and ... |
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class ParticipantTestCase(Integ... |
#!/usr/bin/env python
def configuration(parent_package='', top_path=None):
import os.path as op
from numpy.distutils.misc_util import Configuration
from sfepy import Config
site_config = Config()
system = site_config.system()
os_flag = {'posix' : 0, 'windows' : 1}[system]
auto_dir = op.d... |
#!/usr/bin/python3
# ------------------------------------------------------------------------------
# Python
from os import path, makedirs
import sqlite3
# Alohomora
from app.salt import gen_salt
# ------------------------------------------------------------------------------
db_path = path.join(path.dirname(path... |
'''Tests about locks'''
import redis
from common import TestQless
class TestLocks(TestQless):
'''Locks tests'''
def test_malformed(self):
'''Enumerate malformed inputs into heartbeat'''
self.assertMalformed(self.lua, [
('heartbeat', 0),
('heartbeat', 0, 'jid'),
... |
'''
This tests what CPythons test_sha.py does not hit.
'''
from __future__ import absolute_import
#--IMPORTS---------------------------------------------------------------------
from iptest.assert_util import *
skiptest("silverlight")
import _sha512
#--GLOBALS----------------------------------------------------------... |
# -*- coding: latin1 -*-
################################################################################################
import snap, sys, time, os, os.path, math, calc
reload(sys)
sys.setdefaultencoding('utf-8')
########################################################################################################... |
#!/usr/bin/env python
# Load common imports and system envs to build the core object
import sys, os
# Load the Environment:
os.environ["ENV_DEPLOYMENT_TYPE"] = "NoApps"
from src.common.inits_for_python import *
#####################################################################
#
# Start Arg Processing:
#
action... |
#!/usr/bin/env python3
from USB import *
from USBDevice import *
from USBConfiguration import *
from USBInterface import *
from USBEndpoint import *
class PwnUSBDevice(USBDevice):
name = "USB device"
def handle_buffer_available(self, lll):
return
def __init__(self, maxusb_app, verbose=0):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name='AerospikeClientMock',
version='1.0.3.1',
description='Aerospike client mock',
long_description=
"""
Aerospike client mock based on dict used for unit testing
""",
url='https://github.com/tivvit/a... |
"""The qutebrowser test suite conftest file."""
import re
import os
import sys
import warnings
import operator
import pytest
import hypothesis
from helpers import logfail
from helpers.logfail import fail_on_logging
from helpers.messagemock import message_mock
from helpers.fixtures import * # pylint: disable=wildcar... |
from librato_python_web.instrumentor.base_instrumentor import BaseInstrumentor
from librato_python_web.instrumentor.instrument import get_complex_wrapper
class MysqlInstrumentor(BaseInstrumentor):
modules = {
'MySQLdb.cursors': ['Cursor']
}
def __init__(self):
super(MysqlInstrumentor, sel... |
# Example #1: Language Translator
#Adaptee: Incompatible interface # 1
class EnglishSpeaker:
def responseToGreeting(self):
return "Hello to you too!"
def responseToFarewell(self):
return "Goodbye my friend."
# Adapter Class
class Translator:
'''Accespts an engli... |
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.db.models import signals
from django_notify import notify
from django_notify.models import Subscription
from wiki import models as wiki_models
from wiki.models.pluginbase import Art... |
from abc import abstractmethod, ABCMeta
from six import with_metaclass
import pandas
from pixiedust.utils.dataFrameAdapter import PandasDataFrameAdapter
__all__ = ['StreamingDataAdapter']
class StreamingDataAdapter(with_metaclass(ABCMeta)):
def __init__(self):
self.channels = []
def getNextD... |
FILENAME = "tests-learn-2.nn"
import collections
import gzip
import pickle
import operator
import os
import re
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import StandardScaler
# The threshhold for predicting based on learned data
PREDICT_THRESHHOLD = 0.70
def load(directory):
pa... |
from ripcord.openstack.common import uuidutils
from ripcord.tests.api.v1 import base
class TestCase(base.FunctionalTest):
def test_all_fields(self):
json = {
'disabled': True,
'name': 'example.org',
'project_id': '793491dd5fa8477eb2d6a820193a183b',
'updated... |
from Tribler.Core.Category.Category import Category, cmp_rank
from Tribler.Test.test_as_server import AbstractServer
class TriblerCategoryTest(AbstractServer):
def setUp(self, annotate=True):
super(TriblerCategoryTest, self).setUp(annotate=annotate)
self.category = Category()
self.categor... |
"""Test function :func:`iris.util.mask_cube"""
# Import iris.tests first so that some things can be initialised before
# importing anything else.
import iris.tests as tests # isort:skip
import numpy as np
import numpy.ma as ma
from iris.tests.stock import (
make_bounds_discontiguous_at_point,
sample_2d_latl... |
#!/usr/bin/env python
# -*- coding: utf-8; mode: python -*-
"""
setup.py script for the ansicolortags project (https://bitbucket.org/lbesson/ansicolortags)
References:
- https://packaging.python.org/en/latest/distributing/#setup-py
- http://the-hitchhikers-guide-to-packaging.readthedocs.io/en/latest/creation.html#setu... |
'''
Test two delayed client hello callbacks
'''
# 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 ... |
from functools import wraps
from lxml import etree, objectify
def add_text_argument(f):
@wraps(f)
def wrapper(*args, **kwargs):
text = kwargs.pop("text", None)
cdata = kwargs.pop("cdata", None)
element = f(*args, **kwargs)
if cdata:
element.text = etree.CDATA(cdata... |
from __future__ import absolute_import
__author__ = 'andrews'
import unittest
import uuid
import array
from libpebble2.protocol.voice import *
class TestVoiceProtocol(unittest.TestCase):
def test_session_setup_command(self):
# this test is a bit of a sanity check to ensure that the voice control endpo... |
from binascii import hexlify
from typing import TYPE_CHECKING
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey
from cryptography.hazmat.backends import default_backend
import six
from .._internal impo... |
"""Test of apps/millionaires.py example."""
import re
import os
import os.path as path
from twisted.trial.unittest import TestCase
from twisted.internet import reactor
from twisted.internet.utils import getProcessOutput
from twisted.internet.defer import Deferred, gatherResults
from viff.field import GF256
from viff... |
"""Support for Verizon FiOS Quantum Gateways."""
import logging
from requests.exceptions import RequestException
import voluptuous as vol
from homeassistant.components.device_tracker import (
DOMAIN,
PLATFORM_SCHEMA,
DeviceScanner,
)
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_SSL
impor... |
from keystoneclient.auth.identity import v3
from keystoneclient import session
from cinderclient import client
from utils import log
class Cinder():
def __init__(self, auth_url, username, password, project_name, cacert,
project_id):
auth = v3.Password(auth_url=auth_url,
... |
import copy
import logging
import pytest # noqa needed for capsys
import os
import pickle
from crush import Crush
from crush.ceph import Ceph
from crush.main import Main
from crush.analyze import BadMapping
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
level=logging.INFO)
c... |
import os
#os.environ['PYUSB_DEBUG'] = 'debug'
#os.environ['PYUSB_LOG_FILENAME'] = 'err.log'
import usb.core
import usb.util
import time
import random
class FusionBrainV3:
"""
Wraps the FusionBrain multifunction IO device, v.3. Specifically, tested with v. 3c.
One instance per actual device -- not more, ... |
#!/usr/bin/python3
""" webcam driver """
import time
import datetime
import os
from Interface import utils, strings
video_dev = '/dev/video0'
video_res= '160x120'
class Logitech():
def __init__(self, log_file):
self.log_file = log_file
self.last_activity = datetime.datetime.now()
... |
#!/usr/bin/env python
from __future__ import print_function
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
from distutils.command.build_py import build_py as _build_py
from setuptools.... |
#!/usr/bin/env python
# The pyfftw namespace
''' The core of ``pyfftw`` consists of the :class:`FFTW` class,
:ref:`wisdom functions <wisdom_functions>` and a couple of
:ref:`utility functions <utility_functions>` for dealing with aligned
arrays.
This module represents the full interface to the underlying `FFTW
librar... |
from django.test import TestCase
from django.core.urlresolvers import reverse
from main import contratlocation as contratlocation_view
from main.tests.factories.contrat_location import ContratLocationFactory
from main.tests.factories.assurance import AssuranceFactory
from main.tests.factories.batiment import BatimentFa... |
#!/usr/bin/env python
# coding=utf-8
import glob
import click
import os
import json
import datetime
import re
import csv
from requests.exceptions import ConnectionError
from exchangelib import DELEGATE, IMPERSONATION, Account, Credentials, ServiceAccount, \
EWSDateTime, EWSTimeZone, Configuration, NT... |
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
from pants.java.util import execute_java
from pants.backend.jvm.tasks.jvm_tool_task_mixin import JvmToolTaskMixin
from pants.backend.jvm.tasks.jvm_task import JvmTask
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.