content
stringlengths
4
20k
from ._compat import unittest from ._adapt import DEFAULT_URI, IS_GAE, IS_IMAP, drop from pydal._compat import integer_types from pydal import DAL, Field from pydal.helpers.methods import smart_query @unittest.skipIf(IS_IMAP, "Skip nosql") class TestSmartQuery(unittest.TestCase): def testRun(self): db = D...
from cStringIO import StringIO from twisted.internet.protocol import FileWrapper class IOPump: """Utility to pump data between clients and servers for protocol testing. Perhaps this is a utility worthy of being in protocol.py? """ def __init__(self, client, server, clientIO, serverIO): self.cl...
import math import argparse import PIL.Image as Image def median(data): data = sorted(data) length = len(data) if length % 2 == 0: return (data[length // 2] + data[length // 2 + 1]) / 2.0 return data[length // 2] def total_value_rgba(im, data, x, y): r, g, b, a = data[y * im.size[0] + x] ...
from __future__ import unicode_literals import frappe, json from frappe.utils import cstr, cint, get_fullname from frappe import msgprint, _ from frappe.model.mapper import get_mapped_doc from erpnext.setup.utils import get_exchange_rate from erpnext.utilities.transaction_base import TransactionBase from erpnext.accoun...
"""Base Mapping tests $Id: basemapping.py 110736 2010-04-11 10:59:30Z regebro $ """ from operator import __getitem__ def testIReadMapping(self, inst, state, absent): for key in state: self.assertEqual(inst[key], state[key]) self.assertEqual(inst.get(key, None), state[key]) self.failUnless(...
from __future__ import division version = '0.8.1'
import json import os import re from collections import deque from functools import partial, wraps from flask import Flask, jsonify, make_response, request from flask_compress import Compress from flask_cors import CORS from flask_restplus import Api as RestPlusAPI from flask_restplus import Resource from jsonschema i...
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.utils import html #Local Imports import models as cont import utils.admin as utils class ConnectionInline(admin.TabularInline): model = cont.Connection extra = 0 class Note...
from mock import patch, Mock import unittest import ddt from django.conf import settings from django.http import HttpResponse from django.test import TestCase from django.test.utils import override_settings from django.test.client import RequestFactory from django.core.urlresolvers import reverse import edxmako.middle...
""" The Response class in REST framework is similar to HTTPResponse, except that it is initialized with unrendered data, instead of a pre-rendered string. The appropriate renderer is called during Django's template response rendering. """ from __future__ import unicode_literals from django.template.response import Si...
from bson.objectid import ObjectId from flask.ext.pymongo import PyMongo builtin_list = list mongo = PyMongo() def _id(id): if not isinstance(id, ObjectId): return ObjectId(id) return id def from_mongo(data): """ Translates the MongoDB dictionary format into the format that's expected ...
#!/usr/bin/env python2 import shutil, os, argparse, sys, stat,time def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('-name', type=str, required = True) parser.add_argument('-author', type=str, required = True) parser.add_argument('-prepath', type=str, required = True) retu...
import ImpactPacket """Classes to convert from raw packets into a hierarchy of ImpactPacket derived objects. The protocol of the outermost layer must be known in advance, and the packet must be fed to the corresponding decoder. From there it will try to decode the raw data into a hierarchy of ImpactPacket derived obj...
"""The :class:`.Annotated` class and related routines; creates hash-equivalent copies of SQL constructs which contain context-specific markers and associations. """ from .. import util from . import operators class Annotated(object): """clones a ClauseElement and applies an 'annotations' dictionary. Unlike ...
import contextlib import datetime import mock from oslo_utils import timeutils import testscenarios from neutron.common import constants from neutron.common import topics from neutron import context from neutron.db import agents_db from neutron.db import agentschedulers_db as sched_db from neutron.db import models_v2...
from libsaas import http, parsers from libsaas.services import base from . import resource def parse_passthrough(body, code, headers): if not 200 <= code < 300: raise http.HTTPError(body, code, headers) return body class InvoicesBase(resource.RecurlyResource): path = 'invoices' def updat...
import os from optparse import make_option from django.contrib.gis import gdal from django.core.management.base import LabelCommand, CommandError def layer_option(option, opt, value, parser): """ Callback for `make_option` for the `ogrinspect` `layer_key` keyword option which may be an integer or a string....
"""times module This module provides some Date and Time classes for dealing with MySQL data. Use Python datetime module to handle date and time columns.""" import math from time import localtime from datetime import date, datetime, time, timedelta from _mysql import string_literal Date = date Time = tim...
from airflow.contrib.hooks.spark_submit_hook import SparkSubmitHook from airflow.models import BaseOperator from airflow.settings import WEB_COLORS from airflow.utils.decorators import apply_defaults class SparkSubmitOperator(BaseOperator): """ This hook is a wrapper around the spark-submit binary to kick off...
from twisted.internet import defer from test.support.integration import SoledadTestBase, MailBuilder from pixelated.adapter.model.status import Status class MarkAsReadUnreadTest(SoledadTestBase): @defer.inlineCallbacks def test_mark_single_as_read(self): input_mail = MailBuilder().build_input_mail()...
import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix, log_loss, roc_curve, auc, precision_recall_curve, average_precision_score def initialize_with_JASPAR(enhancer_conv_layer, promoter_conv_layer): JASPAR_motifs = list(np.load('/home/sss1/Desktop/projects/DeepInteractions...
try: from collections import namedtuple except ImportError: from ucollections import namedtuple T = namedtuple("Tup", ["foo", "bar"]) # CPython prints fully qualified name, what we don't bother to do so far #print(T) for t in T(1, 2), T(bar=1, foo=2): print(t) print(t[0], t[1]) print(t.foo, t.bar) ...
#!/usr/bin/env python """Capability Container""" __author__ = 'Adam R. Smith, Michael Meisinger, Dave Foster <<EMAIL>>' from pyon.container import ContainerCapability from pyon.core import bootstrap from pyon.core.bootstrap import CFG from pyon.core.exception import ContainerError, BadRequest from pyon.datastore.dat...
__version__ = "0.1" import string import Image, ImageFile, ImagePalette def i16(c): return ord(c[1]) + (ord(c[0])<<8) ## # Image plugin for the GD uncompressed format. Note that this format # is not supported by the standard <b>Image.open</b> function. To use # this plugin, you have to import the <b...
SEP = "/" def _splitnode(nodeid): """Split a nodeid into constituent 'parts'. Node IDs are strings, and can be things like: '' 'testing/code' 'testing/code/test_excinfo.py' 'testing/code/test_excinfo.py::TestFormattedExcinfo::()' Return values are lists e.g. [] ...
#!/usr/bin/env python # encoding: utf-8 import logging import datetime from django.utils import timezone from modularodm import Q from framework.email.tasks import send_email from website import mails from website import models from website import settings from website.app import init_app from scripts import utils...
from __future__ import (division, absolute_import, print_function, unicode_literals) import time from datetime import datetime from test._common import unittest from test.helper import TestHelper from beets.util.confit import ConfigValueError class TypesPluginTest(unittest.TestCase, TestHel...
from synapse.appservice import ApplicationServiceState, AppServiceTransaction from synapse.appservice.scheduler import ( _ServiceQueuer, _TransactionController, _Recoverer ) from twisted.internet import defer from ..utils import MockClock from mock import Mock from tests import unittest class ApplicationServiceSc...
"""Provides high-level common email utilities.""" from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from smtplib import SMTP, SMTPRecipientsRefused from celery import shared_task from flask import current_app from flask_celeryext import create_celery_app def create_send_email_task(...
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..compat import ( compat_urllib_request, ) from ..utils import ( clean_html, ExtractorError, float_or_none, parse_iso8601, ) class TapelyIE(InfoExtractor): _VALID_URL = r'https?://(?:www\...
import logging from django.conf import settings from django.contrib.auth import logout as auth_logout from django.http import HttpResponseRedirect from paucore.utils.web import smart_reverse from paucore.web.template import render_template_response from paucore.web.views import MMLActionView from pau import bridge ...
# -*- coding: utf-8 -*- """ requests.adapters ~~~~~~~~~~~~~~~~~ This module contains the transport adapters that Requests uses to define and maintain connections. """ import os.path import socket from .models import Response from .packages.urllib3.poolmanager import PoolManager, proxy_from_url from .packages.urllib...
"""Tests for the experimental input pipeline ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.data.python.ops import batching from tensorflow.python.data.kernel_tests import test_base from tensorflow.python....
"""The test controller for the chromoting localhost browser_tests. This test uses the legion framework to setup this controller which will run the chromoting_integration_tests on a task machine. This is intended to be an example Legion-based test for the chromoting team. The controller will start a task machine to ru...
OLD_SLACK_INCOMING_WEBHOOK = 'https://%s/services/hooks/incoming-webhook?token=%s' SLACK_INCOMING_WEBHOOK = 'https://hooks.slack.com/services/%s' def build_payload_for_slack(module, text, channel, username, icon_url, icon_emoji, link_names, parse, color): if color == 'normal': payload = dict(text=text) ...
"""Dummy Socks5 server for testing.""" import socket, threading, queue import logging logger = logging.getLogger("TestFramework.socks5") ### Protocol constants class Command: CONNECT = 0x01 class AddressType: IPV4 = 0x01 DOMAINNAME = 0x03 IPV6 = 0x04 ### Utility functions def recvall(s, n): """...
import os from fabric.api import abort, cd, env, local, put, run current_dir = os.path.abspath(os.path.dirname(__file__)) env.user = 'git' env.gandalf_path = '/home/%s/gandalf' % env.user def build(): goos = local("go env GOOS", capture=True) goarch = local("go env GOARCH", capture=True) if goos != "linu...
class OntologyTerm(object): def __init__(self, ontology, oboStanza = None, *args, **keywordArgs): object.__init__(self, *args, **keywordArgs) self.ontology = ontology self.oboStanza = oboStanza self.identifier = None self.name = None self.abbreviation = None...
import functools import os import pkgutil import sys from collections import OrderedDict, defaultdict from importlib import import_module import django from django.apps import apps from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.management.base import ( Bas...
from pycerberus.api import Validator from pycerberus.compat import set from pycerberus.lib import PythonicTestCase from pycerberus.schema import SchemaValidator from pycerberus.validators import StringValidator class ExtendSchemaTest(PythonicTestCase): class BasicSchema(SchemaValidator): id = Validat...
"""\ Migrates hit counts from legacy to cnx-archive's database at schema version 1. """ import os import sys import csv import argparse from datetime import datetime, timedelta import psycopg2 __all__ = ('cli_loader', 'do_migration',) here = os.path.abspath(os.path.dirname(__file__)) RESOURCES_DIRECTORY = os.path.j...
class ConnectionError(Exception): """ This exception indicates a generic HPIT connection problem. """ class AuthenticationError(Exception): """ This exception raised on HPIT 403. """ pass class AuthorizationError(Exception): """ This exception is raised when you've made an authoriz...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'certified'} DOCUMENTATION = r''' --- module: bigip_snmp short_description: Manipulate general SN...
#!/usr/bin/python from boto import connect_s3, connect_ec2 from boto.s3.key import Key from kombu import Exchange #from otpsetup.client.models import GtfsFile from otpsetup import settings from shutil import copyfileobj from datetime import datetime import os, socket, traceback, subprocess, builder, json, uuid #impo...
import plotter import common import wx import numpy import math import pubsub from constants import * from gnuradio import gr #for gr.prefs import forms ################################################## # Constants ################################################## SLIDER_STEPS = 100 AVG_ALPHA_MIN_EXP, AVG_ALPHA_MAX_...
import numpy import os from nmt import train def main(job_id, params): print params validerr = train(saveto=params['model'][0], reload_=params['reload'][0], dim_word=params['dim_word'][0], d...
import StringIO import logging import unittest2 as unittest from webkitpy.test.skip import skip_if class SkipTest(unittest.TestCase): def setUp(self): self.logger = logging.getLogger(__name__) self.old_level = self.logger.level self.logger.setLevel(logging.INFO) self.old_propaga...
__all__ = ['FlashShotInstanceAdderWdg', 'FlashLayerInstanceAdderWdg', 'FlashEpisodePlannerWdg', 'FlashLayerStageWdg', 'EpisodePlannerCbk'] from pyasm.web import * from pyasm.widget import * from pyasm.search import * from pyasm.biz import * from pyasm.flash import * from pyasm.prod.biz import * from pyasm.prod.web imp...
import functools from pip._vendor.requests.adapters import HTTPAdapter from .controller import CacheController from .cache import DictCache from .filewrapper import CallbackFileWrapper class CacheControlAdapter(HTTPAdapter): invalidating_methods = set(['PUT', 'DELETE']) def __init__(self, cache=None, ...
import json import pytest_bdd as bdd bdd.scenarios('misc.feature') @bdd.then(bdd.parsers.parse('the PDF {filename} should exist in the tmpdir')) def pdf_exists(quteproc, tmpdir, filename): path = tmpdir / filename data = path.read_binary() assert data.startswith(b'%PDF') @bdd.when(bdd.parsers.parse('I ...
import boto import boto.exception import boto.regioninfo import errno import os from multiprocessing import Process, Event import signal import testtools as unittest import basicdb def run_server(port, server_ready, done): from coverage.collector import Collector from coverage.control import coverage if C...
#!/usr/bin/env python """ Uses for generators * Pull pipelining (iterators) * Push pipelining (coroutines) * State machines (coroutines) * "Cooperative multitasking" (coroutines) * Algorithm -> Object transform for cohesiveness (for example context managers) (coroutines) Design considerations * When should...
from __future__ import absolute_import, division, print_function, unicode_literals import re from guessit.containers import PropertiesContainer, WeakValidator, LeavesValidator, QualitiesContainer, ChainedValidator, DefaultValidator, OnlyOneValidator, LeftValidator, NeighborValidator, FullMatchValidator from guessit.p...
#! /usr/bin/env python # -*- coding: utf-8 -*- """character.py""" """ This file is part of The Last Caturai. The Last Caturai 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 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Simple built-in backend. """ __author__ = "Lluís Vilanova <<EMAIL>>" __copyright__ = "Copyright 2012, Lluís Vilanova <<EMAIL>>" __license__ = "GPL version 2 or (at your option) any later version" __maintainer__ = "Stefan Hajnoczi" __email__ = "<EMAIL>" ...
import struct from packet_utils import * from packet_base import packet_base from eap import * class eapol(packet_base): "EAP over LAN packet" MIN_LEN = 4 V1_PROTO = 1 V2_PROTO = 2 EAP_TYPE = 0 EAPOL_START_TYPE = 1 EAPOL_LOGOFF_TYPE = 2 EAPOL_KEY_TYPE = 3 EAPOL_ENCAPSULAT...
"""IP address pool management functions. """ import ipaddr from bitarray import bitarray from ganeti import errors def _ComputeIpv4NumHosts(network_size): """Derives the number of hosts in an IPv4 network from the size. """ return 2 ** (32 - network_size) IPV4_NETWORK_MIN_SIZE = 30 # FIXME: This limit is...
""" ======================================== Comparison of Calibration of Classifiers ======================================== Well calibrated classifiers are probabilistic classifiers for which the output of the predict_proba method can be directly interpreted as a confidence level. For instance a well calibrated (bi...
import math,os import FreeCAD, FreeCADGui, Animation, PySide from Animation import say,sayErr,sayexc,sayd from EditWidget import EditWidget __vers__= '0.1' __dir__ = os.path.dirname(__file__) def createScaler(name='My_Scaler'): obj = FreeCAD.ActiveDocument.addObject("App::DocumentObjectGroupPython",name) obj.ad...
from django.conf import settings from bedrock.base.middleware import LocaleURLMiddleware class TabzillaLocaleURLMiddleware(LocaleURLMiddleware): def process_request(self, request): resp = super(TabzillaLocaleURLMiddleware, self).process_request(request) # no locale redirect happening if ...
from __future__ import print_function from builtins import object from os import path import shutil import py_compile from tempfile import mkdtemp import codecs import pytest import locale import time import psychopy.experiment from psychopy import prefs from psychopy.app.builder.dialogs import DlgComponentProperties...
import unittest from ant.core.message import * class MessageTest(unittest.TestCase): def setUp(self): self.message = Message() def test_get_setPayload(self): self.assertRaises(MessageError, self.message.setPayload, '\xFF' * 15) self.message.setPayload('\x11'...
import os import platform from subprocess import Popen, STDOUT from selenium.common.exceptions import WebDriverException from selenium.webdriver.common import utils import time class FirefoxBinary(object): NO_FOCUS_LIBRARY_NAME = "x_ignore_nofocus.so" def __init__(self, firefox_path=None, log_file=None): ...
import re __all__ = ['parse_mdstat'] MULTIPLIER = { 'KB' : 1024, 'K' : 1024, 'MB' : 1024 * 1024, 'M' : 1024 * 1024, 'B' : 1 } def parse_mdstat(results): linePattern = re.compile(r"\n\s*\n") mds = [] # strip first and last line: # > Personalities : # > unused devices: <non...
from django.contrib import admin from reversion.admin import VersionAdmin from package.models import ( Category, Commit, PackageExample, Project, ProjectImage, TeamMembership, Version, ) class PackageExampleInline(admin.TabularInline): model = PackageExample class PackageAdmin(Versi...
# Based on http://stackoverflow.com/questions/2333872/atomic-writing-to-file-with-python import os from contextlib import contextmanager # We would ideally atomically replace any existing file with the new # version. However, on Windows there's no Python-only solution prior # to Python 3.3. (This library includes a C...
+# Copyright (C) 2011 Nippon Telegraph and Telephone Corporation. +# +# 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...
""" Represents an SQS Attribute Name/Value set """ class Attributes(dict): def __init__(self, parent): self.parent = parent self.current_key = None self.current_value = None def startElement(self, name, attrs, connection): pass def endElement(self, name, value, connec...
#!/usr/bin/python # -*- coding: utf-8 -*- """ (c) 2016, Loic Blot <<EMAIL>> Sponsored by Infopro Digital. http://www.infopro-digital.com/ Sponsored by E.T.A.I. http://www.etai.fr/ This file is part of Ansible Ansible is free software: you can redistribute it and/or modify it under the terms of the GNU General Public...
""" django_extensions.management.jobs """ import os from imp import find_module _jobs = None def noneimplementation(meth): return None class JobError(Exception): pass class BaseJob(object): help = "undefined job description." when = None def execute(self): raise NotImplementedError("Jo...
#!/usr/bin/env python __author__ = 'Phil Schwartz' # gitignore-grabber.py - Grabs gitignore generated files from gitignore.io depending on the programming language # and/or IDE and/or OS args given (comma separated). # python gitignore-grabber.py language,IDE,OS repoDirectory import sys import os import urllib impo...
"""Autodiscovery helper functions.""" import inspect from invenio.utils.text import wrap_text_in_a_box def get_callable_signature_as_string(the_callable): """ Returns a string representing a callable as if it would have been declared on the prompt. >>> def foo(arg1, arg2, arg3='val1', arg4='val2', ...
from django.conf.urls import include, patterns, url from rest_framework import routers from treeherder.webapp.api import (artifact, bug, job_log_url, jobs, logslice, note, performance_data, refdata, resultset) # router for views that are bound to ...
import unittest import errno import os import signal import subprocess import tempfile import nose import httplib2 from httplib2 import socks from httplib2.test import miniserver tinyproxy_cfg = """ User "%(user)s" Port %(port)s Listen 127.0.0.1 PidFile "%(pidfile)s" LogFile "%(logfile)s" MaxClients 2 StartServers 1...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from units.compat.mock import patch from ansible.modules.network.netvisor import pn_vrouter_ospf6 from units.modules.utils import set_module_args from .nvos_module import TestNvosModule class TestVrouterOSPF6Module(TestNvosModule...
import res_country import res_lang import res_partner import res_bank import res_config import res_currency import res_company import res_users import res_request import res_lang import ir_property import report import wizard # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
""" imageProcesser is used to process images received from UI. This file can be test standalone using cmd: python imageProcesser.py """ import cv2 import os import re import sys import matplotlib.pyplot as plt import numpy as np from PySide import QtGui, QtCore import math import time # pylint: disable=C0103,R0...
"""Parser engine for the grammar tables generated by pgen. The grammar table must be loaded first. See Parser/parser.c in the Python distribution for additional info on how this parsing engine works. """ # Local imports from . import token class ParseError(Exception): """Exception to signal the parser is stuck...
import os import tempfile import unittest from telemetry import benchmark from telemetry.core import bitmap from telemetry.core import util # This is a simple base64 encoded 2x2 PNG which contains, in order, a single # Red, Yellow, Blue, and Green pixel. test_png = """ iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91 JpzAAA...
""" :mod:`~matplotlib.gridspec` is a module which specifies the location of the subplot in the figure. ``GridSpec`` specifies the geometry of the grid that a subplot will be placed. The number of rows and number of columns of the grid need to be set. Optionally, the subplot layout parameter...
""" Tests course_creators.admin.py. """ from django.test import TestCase from django.contrib.auth.models import User from django.contrib.admin.sites import AdminSite from django.http import HttpRequest import mock from course_creators.admin import CourseCreatorAdmin from course_creators.models import CourseCreator fr...
"""GDB Pretty printers and convenience functions for Go's runtime structures. This script is loaded by GDB when it finds a .debug_gdb_scripts section in the compiled binary. The [68]l linkers emit this with a path to this file based on the path to the runtime package. """ # Known issues: # - pretty printing only w...
"""HTML utilities suitable for global use.""" from __future__ import unicode_literals import re import warnings from django.utils import six from django.utils.deprecation import RemovedInDjango110Warning from django.utils.encoding import force_str, force_text from django.utils.functional import allow_lazy from djang...
#!/usr/bin/python import os import sys import shutil import uuid import subprocess import charmhelpers.contrib.openstack.utils as openstack import charmhelpers.contrib.hahelpers.cluster as cluster from swift_utils import ( register_configs, restart_map, determine_packages, ensure_swift_dir, SWIFT_...
#!/usr/bin/env python import os import shutil import glob import time import sys import subprocess import string from optparse import OptionParser, make_option SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) PKG_NAME = os.path.basename(SCRIPT_DIR) PARAMETERS = None #XW_ENV = "export DBUS_SESSION_BUS_ADDRESS=...
from __future__ import print_function, absolute_import import numpy as np import numba.unittest_support as unittest from numba import hsa class TestDecorators(unittest.TestCase): def test_kernel_jit(self): @hsa.jit("(float32[:], float32[:])") def copy_vector(dst, src): tid = hsa.get_...
from flask import Flask, render_template, session, redirect, url_for, g from flask.ext.script import Manager from flask.ext.bootstrap import Bootstrap from flask.ext.moment import Moment from datetime import datetime import os from flask.ext.wtf import Form from wtforms import StringField, SubmitField from wtforms.vali...
from telemetry.core import exceptions class InspectorRuntime(object): def __init__(self, inspector_websocket): self._inspector_websocket = inspector_websocket self._inspector_websocket.RegisterDomain('Runtime', self._OnNotification) self._contexts_enabled = False self._max_context_id = None def _...
from __future__ import unicode_literals from future.builtins import str from collections import defaultdict from django.core.exceptions import ImproperlyConfigured from django.template import Context, TemplateSyntaxError, Variable from django.template.loader import get_template from django.utils.translation import ug...
from __future__ import unicode_literals import frappe from frappe import _, msgprint from frappe.utils import comma_and from frappe.model.document import Document from frappe.utils.nestedset import get_ancestors_of from erpnext.utilities.doctype.address.address import get_territory_from_address class ShoppingCartSetup...
from scrapy.tests import test_utils_queue as t from scrapy.squeue import MarshalFifoDiskQueue, MarshalLifoDiskQueue, PickleFifoDiskQueue, PickleLifoDiskQueue from scrapy.item import Item, Field from scrapy.http import Request from scrapy.contrib.loader import ItemLoader class TestItem(Item): name = Field() def te...
from oslo_concurrency import processutils from oslo_config import cfg from neutron import service from neutron.tests import base class TestService(base.BaseTestCase): def test_api_workers_default(self): self.assertEqual(processutils.get_worker_count(), service._get_api_workers()...
""" Scheduler host filters """ from cinder.scheduler import base_filter class BaseHostFilter(base_filter.BaseFilter): """Base class for host filters.""" def _filter_one(self, obj, filter_properties): """Return True if the object passes the filter, otherwise False.""" return self.host_passes(o...
import json import logging from typing import List, Optional import sdk_cmd import sdk_plan import sdk_tasks LOG = logging.getLogger(__name__) def check_permanent_recovery( package_name: str, service_name: str, pod_name: str, recovery_timeout_s: int, pods_with_updated_tasks: Optional[List[str]]...
import json import logging import sys import urllib from citest.base import ExecutionContext import citest.base import citest.gcp_testing as gcp import citest.json_contract as jc import citest.service_testing as st # Spinnaker modules. import spinnaker_testing as sk import spinnaker_testing.front50 as front50 clas...
#!/usr/bin/env python # -*- coding: utf-8 -*- import argh import sys from functools import partial from argparse import FileType from .cli import dicts_from_lines, to_int from .misc import as_bulk_queries from cr8 import aio, clients from .metrics import Stats from .log import format_stats def to_insert(table, d): ...
from spack import * class Xkill(AutotoolsPackage): """xkill is a utility for forcing the X server to close connections to clients. This program is very dangerous, but is useful for aborting programs that have displayed undesired windows on a user's screen.""" homepage = "http://cgit.freedesktop.org/...
"""Config flow for Goal Zero Yeti integration.""" import logging from goalzero import Yeti, exceptions import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_HOST, CONF_NAME from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import DEF...
""" SNEXTRACT extract supernova spectra from image or images and combine them """ import os, sys, glob, shutil, string import numpy as np import pyfits from scipy import ndimage as nd from pyraf import iraf from iraf import pysalt from specsky import skysubtract from specextract import extract, write_extract fr...
# -*- coding: utf-8 -*- """ Copyright (C) 2015, MuChu Hsu Contributed by Muchu Hsu (<EMAIL>) This file is part of BSD license <https://opensource.org/licenses/BSD-3-Clause> """ from subprocess import call """ 以 shell script 執行 sikuli 從 parsed_resul 取得資訊 透過 sikuli 將 HTML 抓取到 source_html 下 """ class SpiderForINDIEGOGO: ...