content
stringlengths
4
20k
""" Refresh Scene Refresh the current scene, useful when working with libraries or drivers. Could also add an option to refresh the VSE maybe? Usage: Hit F5 or find it on the Specials menu W. """ import bpy KEYMAPS = list() class AMTH_SCENE_OT_refresh(bpy.types.Operator): """Refresh the current scene""" ...
""" MAP Client, a program to generate detailed musculoskeletal models for OpenSim. Copyright (C) 2012 University of Auckland This file is part of MAP Client. (http://launchpad.net/mapclient) MAP Client is free software: you can redistribute it and/or modify it under the terms of the GNU General Public Li...
"""Publish a sample using an UDP mechanism """ import socket import msgpack from oslo_config import cfg from oslo_log import log from oslo_utils import netutils import ceilometer from ceilometer.i18n import _ from ceilometer import publisher from ceilometer.publisher import utils cfg.CONF.import_opt('udp_port', 'ce...
"""Pumps data from Zabbix DB and provides it with HTTP API. Hosts with status 0 are real hosts, not templates. Items store histori data in few tables depending on values type: +------------------+--------------+ | items.value_type | table name | +------------------+--------------+ | 0 | history |...
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from pants.backend.core.targets.dependencies import Dependencies from pants.backend.python.python_artifact import PythonArtifact from pants.backend.python.python_requi...
#!/usr/bin/env python3 from setuptools import setup, find_packages setup(name='asc2netcdf', version='0.3', description='Reads asc data into netCDF files', long_description=('The script was written to access the header and to \ calculate the upper right corner centre of a grid. Some information ...
from spack import * class RIranges(RPackage): """Provides efficient low-level and highly reusable S4 classes for storing, manipulating and aggregating over annotated ranges of integers. Implements an algebra of range operations, including efficient algorithms for finding overlaps and neare...
""" A multivariate normal PDF. Author: Ilias Bilionis Date: 5/19/2014 """ __all__ = ['MultivariateNormal'] import numpy as np import math import scipy.linalg from . import make_vector from . import call_many from . import PDFBase class MultivariateNormal(PDFBase): """ A class representing the ...
import re from pu.utils import is_an_integer, is_a_string class Enumeration(object): """C's enum type in Python. Inspired by PC2e:{6.2, 16.9}. """ class ConstError(Exception): pass def __init__(self, name = 'enum', enumees = (), unique = True, freeze = False): """Enumerate t...
#!/usr/bin/python from opencv.cv import * from opencv.highgui import * import sys # Rearrange the quadrants of Fourier image so that the origin is at # the image center # src & dst arrays of equal size & type def cvShiftDFT(src_arr, dst_arr ): size = cvGetSize(src_arr) dst_size = cvGetSize(dst_arr) if(ds...
"""Distro helpers.""" import os import subprocess import time def CallDhclient( interfaces, logger, dhclient_script=None): """Configure the network interfaces using dhclient. Args: interfaces: list of string, the output device names to enable. logger: logger object, used to write to SysLog and seria...
#!/usr/bin/env python """ NAME iodp_dscr_magic.py DESCRIPTION converts ODP LIMS discrete sample format files to magic_measurements format files SYNTAX iodp_descr_magic.py [command line options] OPTIONS -h: prints the help message and quits. -ID: directory for input file if not included in -f flag...
import pkg_resources import mox from nova import context from nova.openstack.common.gettextutils import _ from nova import test from nova.tests.virt.xenapi import stubs from nova.virt.xenapi import driver as xenapi_conn from nova.virt.xenapi import fake from nova.virt.xenapi.image import bittorrent from nova.virt.xen...
__author__ = 'chick' import os import stat import inspect import shutil from mako.template import Template class Builder: """ Class that creates a directory and file hierarchy based on a template directory ordinary files are copied as is *.mako files are rendered with mako into files with the .mako ...
""" Tools for doing common subexpression elimination. """ from __future__ import print_function, division from sympy.core import Basic, Mul, Add, Pow, sympify, Symbol from sympy.core.singleton import S from sympy.core.function import _coeff_isneg from sympy.core.exprtools import factor_terms from sympy.core.compatibil...
from plplot_python_start import * import sys from plplot import * # Parse and process command line arguments plparseopts(sys.argv, PL_PARSE_FULL) # Simple line plot and multiple windows demo. from plplot_py_demos import * def main(): geometry_master = "500x410+100+200" geometry_slave = "500x410+650+2...
""" AWS SQS platform for notify component. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/notify.aws_sqs/ """ import logging import json import voluptuous as vol from homeassistant.const import ( CONF_PLATFORM, CONF_NAME) from homeassistant.compone...
# -*- coding: utf-8 -*- import time import logging import math import numpy as np from .models import Recommender __all__ = ["UserBase"] log = logging.getLogger(__name__) def similarity(di, dj): """Cos similarity. usage: >>> a = {0:2, 1:1, 2:1} >>> b = {0:1, 2:1} >>> print round(similarity(a...
from itertools import chain import unittest import unitils from io import StringIO try: from unittest import mock except ImportError: import mock class TestHeadCli(unittest.TestCase): """tests for the head.py cli """ @mock.patch("unitils.head") def test_will_take_one_argument_as_filename(self,...
import numbers from libearth.compat.parallel import cpu_count, parallel_map def test_cpu_count(): assert isinstance(cpu_count(), numbers.Integral) assert 0 < cpu_count() def test_parallel_map(): input = [1, 2, 3, 4] fn = lambda n: n * 2 result = parallel_map(4, fn, input) assert frozenset(r...
import logging log = logging.getLogger(__name__) class ProcessingError(Exception): pass class SpikeTask(object): """ Scenario task description """ def __init__(self, message): self.valid = False if not self.validate(message): return self.id = message["id"] ...
""" Tests basic Main Thread Checker support (detecting a main-thread-only violation). """ import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.lldbplatformutil import * import json class MTCSimpleTestCase(TestBase): ...
# -*- coding: utf-8 -*- from __future__ import division from copy import copy import numpy as np from Vertex import Vertex from procedural_city_generation.additional_stuff.Singleton import Singleton singleton=Singleton("roadmap") def getRule(vertex): """ Gets the correct growth_rule for a Vertex, depending on that ...
# coding=utf-8 """ Tests for md_utils script """ import logging import unittest import os from md_utils.namd_log_proc import main from md_utils.md_common import diff_lines, capture_stderr, capture_stdout, silent_remove __author__ = 'hbmayes' # logging.basicConfig(level=logging.DEBUG) # logging.basicConfig(level=lo...
from __future__ import unicode_literals import re from .common import InfoExtractor from ..compat import ( compat_HTTPError, compat_str, compat_urllib_request, compat_urlparse, ) from ..utils import ( determine_ext, extract_attributes, ExtractorError, float_or_none, int_or_none, ...
#!/usr/bin/python import argparse import sys import time import datetime import getpass import smtplib from email.mime.text import MIMEText import subprocess import os import boto from ec2_watchdata import WatchData def main(): global configuration now = int(time.time()) data = WatchData() """ Set default cla...
""" Marker types. From version 3.3 onwards, this is only kept to convert markers into tags when loading old database files. """ #------------------------------------------------------------------------- # # Python modules # #------------------------------------------------------------------------- from ..const import...
import os import sys import gc # Third Party import numpy as np from netCDF4 import Dataset import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import seaborn as sns import pyfilm as pf plt.rcParams.update({'figure.autolayout': True}) mpl.rcPa...
import adonthell import schedule import random # -- pygettext support def _(message): return message class jelom (schedule.speak): def __init__ (self, mapcharacterinstance): self.myself = mapcharacterinstance # -- make random remarks self.speech = [_("Someone fetch me a drink!"),...
import re from urlparse import urlparse from error import ResolutionException class Service: def __init__(self, fetcher, priority = 0): self.SUPPORTS_BATCH = False self.MAX_BATCH_SIZE = 0 self.priority = priority self.fetcher = fetcher() def expand(self, url_string): raise NotImplementedError() ...
import sys import os import os.path import time from datetime import datetime import httplib2 src_path = os.path.split(os.path.split(os.path.split(os.path.abspath(__file__))[0])[0])[0] sys.path.append(src_path) from utils.common import ask, safewfile, LogPrint, timesofar from utils.mongo import get_src_dump f...
from PyQt5.QtCore import Qt from PyQt5.QtWidgets import * from OpenNumismat.Collection.CollectionFields import ImageFields from OpenNumismat.EditCoinDialog.DetailsTabWidget import FormDetailsTabWidget from OpenNumismat.Tools.DialogDecorators import storeDlgSizeDecorator from OpenNumismat.Tools.Converters import ...
import logging import dbus from miro import app # Note: make sure that we catch dbus.DBusException. The DBus object can # fail to be created, or could also fail when it got created when we try # to make use of it. For example, DBus could have been stopped and in # a volatile state as it is being upgraded, or maybe ...
""" Single-channel CSC ================== This example demonstrates solving a convolutional sparse coding problem with a greyscale signal $$\mathrm{argmin}_\mathbf{x} \; \frac{1}{2} \left\| \sum_m \mathbf{d}_m * \mathbf{x}_{m} - \mathbf{s} \right\|_2^2 + \lambda \sum_m \| \mathbf{x}_{m} \|_1 \;,$$ where $\mathbf{d...
""" This sample shows how to copy a feature service """ import arcrest from arcresthelper import securityhandlerhelper def trace(): """ trace finds the line, the filename and error message and returns it to the user """ import traceback, inspect tb = sys.exc_info()[2] tbi...
from rinde.stage.node import ComplexNode from rinde.stage.node import SimpleNode from rinde.stage.node.util import Canvas class Region(SimpleNode): def __init__(self, **kwargs): super(Region, self).__init__(**kwargs) self.properties.create_number("stroke-width", self.__redraw) self.properties.create_number(...
import proto # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v7.enums", marshal="google.ads.googleads.v7", manifest={"TargetingDimensionEnum",}, ) class TargetingDimensionEnum(proto.Message): r"""The dimensions that can be targeted. """ class TargetingDimension(pro...
"""SparseFillEmptyRows operator""" from ..te import hybrid @hybrid.script def _sparse_fill_empty_rows( sparse_indices, sparse_values, dense_shape, default_value, new_sparse_indices_shape, new_sparse_values_shape, empty_row_indicator_shape, ): default_value_ = int64(default_value[0]) ...
"""hepdata - Research. Shared.""" import os import sys from setuptools import find_packages, setup from setuptools.command.test import test as TestCommand readme = open('README.rst').read() history = open('CHANGES.rst').read() tests_require = [ 'check-manifest>=0.25', 'coverage>=4.0', 'isort>=4.2.2', ...
from friendsecure import crypto def test_fingerprint(key): assert key.fingerprint == '657cd81a6b106b4c1f3e82af2ce9c1a50d61d3fea9bb5d44d6c6796362b257aa' def test_sign_message(key): data = key.sign_message('hello world') assert data['message'] == 'hello world' assert data['key'] == key.key.publickey()...
from openerp import models, api, fields from openerp.tools.translate import _ from openerp.exceptions import ValidationError class ResCompany(models.Model): _inherit = 'res.company' @api.model def _get_uom_hours(self): try: return self.env.ref("product.product_uom_hour") exce...
#!/usr/bin/env python #A node for saving visited locations by fg295. It is a two step process: #1. Place the current location (within the map frame) on to the stack. #2. Send nav goals to previously stored locations #import Wx dependencies import wx import os #import ROS dependencies import roslib; roslib.load_man...
# -*- coding: utf-8 -*- ''' genesis reborn Add-on Copyright (C) 2016 genesisreborn 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 you...
"""Tests for Utf8Chars Op from string_ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.platform import test from tensorflow_text.python.ops import string_ops class CoerceToUtf8Test(test.TestCase): def testCoercetoStructura...
from django.db import models import ast # Create your models here. class userloc(models.Model): #groupid = models.CharField(max_length=200) userid = models.CharField(max_length=200) username = models.CharField(max_length=200, default="kabali") Lat = models.CharField(max_length=200) Long = models.CharField(max_le...
from __future__ import absolute_import import sys import doctest import unittest import decimal import inspect import functools import collections from collections import defaultdict try: c = collections.abc except AttributeError: c = collections from decorator import dispatch_on, contextmanager, decorator try:...
"""Test the listsincelast RPC.""" from test_framework.test_framework import VergeTestFramework from test_framework.util import assert_equal, assert_array_result, assert_raises_rpc_error class ListSinceBlockTest (VergeTestFramework): def set_test_params(self): self.num_nodes = 4 self.setup_clean_ch...
from collections import namedtuple from .StateBase import StateBase from neo.Core.IO.BinaryReader import BinaryReader from neo.IO.MemoryStream import StreamManager from copy import deepcopy class SpentCoinItem: def __init__(self, index, height): """ Create an instance. Args: i...
"""Trusted Networks auth provider. It shows list of users if access from trusted network. Abort login flow if not access from trusted network. """ from ipaddress import IPv4Address, IPv4Network, IPv6Address, IPv6Network, ip_network from typing import Any, Dict, List, Optional, Union, cast import voluptuous as vol fr...
"""Helper functions for svg-parsing and writing. Note: To simplify testing, this file should not depend on ifaint.""" from math import tan, cos, pi, sin, atan2 _DEG_PER_RAD = 360 / (2 * pi) _RAD_PER_DEG = 1 / _DEG_PER_RAD def arrow_line_end(arrowTipX, arrowTipY, angle, lineWidth): x = arrowTipX + cos(angle) * 1...
""" Functions called after or before simulations of CyPhy-generated modelica models. If any of these fail, they will throw an IOProcessingError """ import os import json from py_modelica.mat_file_functions.mat_file_processing import MatFileProcessing REPORT_FILE = 'testbench_manifest.json' INVALID_NUMBER_IN...
from collections import OrderedDict from django.contrib import admin from edc_base.modeladmin.admin import BaseModelAdmin from edc_export.actions import export_as_csv_action from edc_visit_tracking.admin import VisitAdminMixin from microbiome.apps.mb.constants import INFANT from microbiome.apps.mb_lab.models import I...
default_app_config = 'providers.edu.oaktrust.apps.AppConfig' """ Example Record <record> <header> <identifier>oai:oaktrust.library.tamu.edu:1969.1/ETD-TAMU-1982-THESIS-B276</identifier> <datestamp>2016-06-08T21:03:13Z</datestamp> <setSpec>com_1969.1_1</setSpec> <setSpec>com_1969.1_...
import os import StringIO files = {} disk_sizes = {} disk_backing_files = {} def get_iscsi_initiator(): return "fake.initiator.iqn" def create_image(disk_format, path, size): pass def create_cow_image(backing_file, path): pass def get_disk_backing_file(path): return disk_backing_files.get(path...
import sys from prettytable import PrettyTable from tintri.common import TintriServerError from tintri.v310 import Tintri """ This Python script prints server information. Command usage: get_appliance_status <server_name> <userName> <password> """ # For exhaustive messages on console, make it to True; otherwise ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ g_collections.py ~~~~~~~~~~~~~~~~ Customized classes of standard python data types for use withing g-sorcery for custom formatted string output substitution in our ebuild templates and classes for storing information about packages and dependen...
# -*- coding: utf-8 -*- """ OCR - Controllers """ import StringIO #Importing reportlab stuff from reportlab.pdfgen.canvas import Canvas from reportlab.lib.pagesizes import A4 # Fonts Courier = 'Courier' Helvetica = 'Helvetica' Helvetica_Bold = 'Helvetica-Bold' Helvetica_Bold_Oblique = 'Helvetica-BoldOblique' Hel...
#!/usr/bin/python3 from __future__ import print_function import os import datetime import configparser import time #import pytz from enum import Enum import paho.mqtt.client as mqtt from threading import Thread from queue import Queue heatMgrQueue = 0 ECS_COMMAND_OFF = b'1' ECS_COMMAND_ON = b'2' lastTemp...
from south.db import db from django.db import models from cthulhubot.models import * class Migration: def forwards(self, orm): "Write your forwards migration here" for master in Buildmaster.objects.all(): if not getattr(master, "api_port", None) and hasattr(master, "generate_api_po...
import tensorflow as tf from tensorflow.contrib.layers.python.layers import batch_norm as batch_norm import numpy as np import math # Hyper Parameters LAYER1_SIZE = 200 LAYER2_SIZE = 100 LEARNING_RATE = 1e-4 TAU = 0.001 BATCH_SIZE = 64 class ActorNetwork: """docstring for ActorNetwork""" def __init__(self,se...
# -*- coding: utf-8 -*- # pylint: disable=protected-access """Test for Video Xmodule functional logic. These test data read from xml, not from mongo. We have a ModuleStoreTestCase class defined in common/lib/xmodule/xmodule/modulestore/tests/django_utils.py. You can search for usages of this in the cms and lms tests ...
import asyncio import argparse import logging import logging.config from pathlib import Path import sys from typing import Any, List, Dict import yaml from assignment.server import init_app def main() -> None: config = parse_app_config(sys.argv[1:]) logging.config.dictConfig(config['logging']) log = lo...
def verbing(s): # +++your code here+++ if len(s) >= 3: if s[-3:] == 'ing': return s + 'ly' else: return s + 'ing' else: return s # E. not_bad # Given a string, find the first appearance of the # substring 'not' and 'bad'. If the 'bad' follows # the 'not', replace the whole 'not'...'bad' ...
import tigre import numpy as np from tigre.utilities import sample_loader from tigre.utilities import CTnoise import tigre.algorithms as algs #%% Geometry geo = tigre.geometry_default(high_resolution=False) #%% Load data and generate projections # define angles angles = np.linspace(0, 2 * np.pi, 100) ## Define angles...
from flask import render_template, Blueprint, redirect, url_for, flash from flask.ext.login import current_user, logout_user, login_user from app.forms import Register, Login from app.models import db, User from datetime import datetime auth = Blueprint('auth', __name__) @auth.route('/login', methods=['GET', 'POST']...
"""Create tarball of differences.""" import argparse import json import os import shutil import sys import tarfile import tempfile def CreateArchive(first, second, input_files, output_file): """Create archive of input files to output_dir. Args: first: the first build directory. second: the second build ...
from email.MIMEBase import MIMEBase from django.core.mail.backends.base import BaseEmailBackend from django.core.mail import EmailMultiAlternatives from django.core.exceptions import ImproperlyConfigured from google.appengine.api import mail as aeemail from google.appengine.runtime import apiproxy_errors def _send_...
import logging from django.contrib.auth.models import User from django.http import HttpResponse from django.test import TestCase from django.test.client import RequestFactory from django.utils.log import NullHandler from django_requestlogging.logging_filters import RequestFilter from django_requestlogging.middleware ...
# coding: utf8 { ' Quotas: %(quotas)s x%(quota_amount).2f': ' Quotas: %(quotas)s x%(quota_amount).2f', ' Transaction number: %s': ' Transaction number: %s', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" é uma expressão opcional como "campo1...
from __future__ import unicode_literals from datetime import timedelta import dateutil.parser import pytz from sqlalchemy import inspect from werkzeug.utils import cached_property from indico.core.db import db class SettingConverter(object): """ Implement a custom conversion between Python types and JS...
import config import urllib.parse import datetime import traceback import time import tqdm import zlib import settings import datetime import sqlalchemy.exc from sqlalchemy import or_ from sqlalchemy import and_ from sqlalchemy import not_ from sqlalchemy import func from sqlalchemy import text import common.database a...
import re import sys import Tkinter import CrazyLogic import BugLogic import ChessBoard import CrazyBoard class BugBoard(Tkinter.Frame): def __init__(self, parent, pieceWidth=48, pieceHeight=48): Tkinter.Frame.__init__(self, parent) self.parent = parent # two boards self.boardA =...
import envelope_detector from scipy.io import wavfile import matplotlib.pyplot as plt import numpy as np import unittest class TestEnvelopeDetector(unittest.TestCase): def setUp(self): self.frecuency = 25500 self.w = 2*np.pi*self.frecuency (self.sample_rate, self.audio_data) = wavfile.read("test_data.w...
from __future__ import print_function import os.path import re import subprocess import sys import tempfile import unittest from src.test.skylark import testenv class SkylarkTest(unittest.TestCase): """Tests for Skylark. In a test file, chunks are separated by "---". Each chunk is evaluated separately. Use "...
# -*- coding: utf-8 -*- from StringIO import StringIO from datetime import datetime from go.vumitools.tests.helpers import GoMessageHelper, djangotest_imports with djangotest_imports(globals()): from go.base.tests.helpers import GoDjangoTestCase, DjangoVumiApiHelper from go.base.management.commands import go_...
from __future__ import division import os import numpy as np import pandas as pd import pytest from utils import absolute_magnitude, hz, planetAndStar, plDensity, readSC from utils import table_convert, stellar_radius, planetary_radius, get_default from utils import luminosity, author_html, generate_missing_link d...
import re import datetime import traceback from . import generic from sickbeard import logger, tvcache, helpers from sickbeard.bs4_parser import BS4Parser from lib.unidecode import unidecode class MoreThanProvider(generic.TorrentProvider): def __init__(self): generic.TorrentProvider.__init__(self, 'More...
from DateTime import DateTime from AccessControl import ClassSecurityInfo from App.class_init import InitializeClass from OFS.SimpleItem import SimpleItem from Products.CMFCore import permissions from Products.CMFCore.utils import UniqueObject, getToolByName from bika.lims.config import ManageAnalysisRequests from bika...
# -*- coding: utf-8 -*- import sys import os import time import calendar from datetime import date from datetime import datetime import argparse # Parse args parser = argparse.ArgumentParser() action = parser.add_mutually_exclusive_group(required=True) action.add_argument('-s', action='store', dest='get_since', help='...
from __future__ import absolute_import, division, print_function, unicode_literals import errno import glob import ntpath import os import subprocess import sys import tempfile from .copytree import containing_repo_type from .envfuncs import Env, add_path_entry from .fetcher import get_fbsource_repo_data from .manife...
from gettext import gettext, bindtextdomain, textdomain from locale import setlocale, LC_ALL #setlocale(LC_ALL, '') #bindtextdomain('blueegg', 'locale') #textdomain('blueegg') _ = gettext #import gtk #auth_dial = gtk.Dialog( # title=_('Authentication Required'), # parent=None, # flags=gtk.DIALOG_...
"""Testing for dynamodb backend.""" # pylama:ignore=D101,D102 import gludb.config from gludb.data import DeleteNotSupported import simple_data_tests from simple_data_tests import SimpleStorage import index_tests from index_tests import IndexedData class SpecificStorageTesting(simple_data_tests.DefaultStorageTesti...
import sys from services.spawn import MobileTemplate from services.spawn import WeaponTemplate from resources.datatables import WeaponType from resources.datatables import Difficulty from resources.datatables import Options from java.util import Vector def addTemplate(core): mobileTemplate = MobileTemplate() mobi...
import sys import time from oslo.config import cfg from neutron.common import exceptions as q_exc from neutron.openstack.common import log as logging # Check needed for unit testing on Unix if sys.platform == 'win32': import wmi CONF = cfg.CONF LOG = logging.getLogger(__name__) class HyperVException(q_exc.Neu...
""" Testing for custom_post_processing_utils.py.""" import unittest from unittest import TestCase from custom_post_processing_utils import post_processing class CustomPostProcessingUtils(TestCase): def test_with_leading_unpaired_punctuation_marks(self): input_text = "' \" Test" output = post_processing(in...
#!/usr/bin/env python import math import random import sys from qt import * from qwt import * # Adapt to the new enum/int type checking in SIP-4.2.x try: colorGroupValues = [ QPalette.ColorGroup(i) for i in range(QPalette.NColorGroups) ] colorRoleValues = [ QColorGroup.ColorRole(i) f...
""" gamedata.py DESCRIPTION: Holds GameData class, described below. Copyright (C) 2013 Adam Beagle - All Rights Reserved You may use, distribute, and modify this code under the terms of the GNU General Public License, viewable at http://opensource.org/licenses/GPL-3.0 This copyright notice must be retained with an...
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import TestSCons import sys import os test = TestSCons.TestSCons() if sys.platform == 'win32': test.write('duplicate a file.bat', 'copy foo.in foo.out\n') copy = test.workpath('duplicate a file.bat') else: test.write('duplicate a file.sh', 'cp...
from django.core.exceptions import ImproperlyConfigured from django.contrib.gis.db.models.fields import GeometryField as django_GeometryField from django.contrib.gis.geos import Polygon from rest_framework.serializers import ModelSerializer, ListSerializer, LIST_SERIALIZER_KWARGS from rest_framework.utils.field_mappin...
from oslo_config import cfg import oslo_messaging from oslo_messaging._drivers import impl_rabbit from oslo_messaging.notify import notifier from oslo_messaging import serializer as oslo_serializer DEFAULT_URL = "__default__" TRANSPORTS = {} def setup(): oslo_messaging.set_transport_defaults('ceilometer') # ...
import pytest from datatables import ColumnDT, DataTables from .helpers import create_dt_params from .models import Address, User def test_list(session): """Test if it returns a list of users.""" columns = [ColumnDT(User.id)] query = session.query().select_from(User) params = create_dt_params(colu...
from common.chrome_proxy_benchmark import ChromeProxyBenchmark from integration_tests import chrome_proxy_measurements as measurements from integration_tests import chrome_proxy_pagesets as pagesets from telemetry import benchmark DESKTOP_PLATFORMS = ['mac', 'linux', 'win', 'chromeos'] WEBVIEW_PLATFORMS = ['android-we...
from math import pi, cos, sin, sqrt, acos from .cvisual import vector, norm, rotate from . import shapes as sh def convert(pos=(0,0,0), up=(0,1,0), points=None, closed=True): pos = vector(pos) up = norm(vector(up)) up0 = vector(0,1,0) angle = acos(up.dot(up0)) reorient = (angle ...
# -*- coding: utf-8 -*- from .yadisk_object import YaDiskObject __all__ = ["TokenObject", "TokenRevokeStatusObject"] class TokenObject(YaDiskObject): """ Token object. :param token: `dict` or `None` :ivar access_token: `str`, token string :ivar refresh_token: `str`, the refresh-...
"""Unit tests""" from zoe_master.backends.docker import config class TestDockerEngineBackendConfig: """Docker configuration parsing tests.""" def test_new_docker_host_config(self): """Test the DockerHostConfig object.""" config.DockerHostConfig() def test_parsing_config_file(self): ...
import sys, math from optparse import OptionParser ''' Get mean and standard deviation for cross-validation job output files. ''' def to_float(s): try: return float(s) except: return s def parse_line(line): return dict(map(lambda x: (x[0], to_float(x[1])), map(lambda x: x.rsplit('=', ...
from __future__ import print_function import re import h2o from tests import pyunit_utils def test_show_time(): h2o.cluster().timezone = "UTC" df = h2o.H2OFrame.from_python( {"A": [1, 2, 3], "B": ["a", "a", "b"], "C": ["hello", "all", "world"], "D": ["12MAR2015:11:00:00", "...
from odoo import _, api, exceptions, fields, models class AccountMoveLine(models.Model): _inherit = "account.move.line" payment_slip_ids = fields.One2many(comodel_name='l10n_ch.payment_slip', inverse_name='move_line_id', string='P...
"""Module containing class for GCP's bigtable clusters. Clusters can be created and deleted. """ import json import logging from perfkitbenchmarker import flags from perfkitbenchmarker import resource from perfkitbenchmarker.providers.gcp import util FLAGS = flags.FLAGS class GcpBigtableCluster(resource.BaseResou...
#!/usr/bin/env python # -*- coding: utf-8 -*- try: import RPi.GPIO as GPIO except: pass import datetime import threading from sound import SoundClass class LaserClass(object): ''' Class that handles the hardware laser module ''' def __init__(self): super(LaserClass, self).__init__(...