content
stringlengths
4
20k
from libcloud.loadbalancer.providers import Provider from libcloud.loadbalancer.drivers.cloudstack import CloudStackLBDriver class NinefoldLBDriver(CloudStackLBDriver): "Driver for load balancers on Ninefold's Compute platform." host = 'api.ninefold.com' path = '/compute/v1.0/' type = Provider.NINE...
#!/usr/bin/env python from vtk import * source = vtkRandomGraphSource() source.DirectedOff() source.SetNumberOfVertices(50) source.SetEdgeProbability(0.01) source.SetUseEdgeProbability(True) source.AllowParallelEdgesOn() source.AllowSelfLoopsOn() source.SetStartWithTree(True) # Connect to the Boost centrality filter...
""" HttpError Spider Middleware See documentation in docs/topics/spider-middleware.rst """ import logging from scrapy.exceptions import IgnoreRequest logger = logging.getLogger(__name__) class HttpError(IgnoreRequest): """A non-200 response was filtered""" def __init__(self, response, *args, **kwargs): ...
""" :class:`~xblock.field_data.FieldData` subclasses used by the LMS """ from xblock.field_data import ReadOnlyFieldData, SplitFieldData from xblock.fields import Scope class LmsFieldData(SplitFieldData): """ A :class:`~xblock.field_data.FieldData` that reads all UserScope.ONE and UserScope.ALL fields fr...
import os import mock from nova.compute import arch from nova import exception from nova import test class ArchTest(test.NoDBTestCase): @mock.patch.object(os, "uname") def test_host(self, mock_uname): os.uname.return_value = ( 'Linux', 'localhost.localdomain', '3...
"""Reuters newswire topic classification dataset. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import numpy as np from six.moves import zip # pylint: disable=redefined-builtin from tensorflow.contrib.keras.python.keras.utils.data_utils...
from rdflib.graph import ConjunctiveGraph from rdflib.term import URIRef, Literal from rdflib.namespace import RDFS from StringIO import StringIO import unittest testContent = """ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . <http://example.org/doc/1> rdfs:label "Document 1","Document 2". <http:...
import cgi import time import Axon from Kamaelia.Protocol.AIM.AIMHarness import AIMHarness from Kamaelia.Util.Console import ConsoleReader, ConsoleEchoer from Kamaelia.Chassis.Graphline import Graphline from Kamaelia.File.UnixProcess import UnixProcess class AIMUserTalkAdapter(Axon.ThreadedComponent.threadedcomponent)...
import unittest from test import support from weakref import proxy, ref, WeakSet import operator import copy import string import os from random import randrange, shuffle import sys import warnings import collections from collections import UserString as ustr import gc import contextlib class Foo: pass class Ref...
r"""Saves out a .wav file with synthesized conversational data and labels. The best way to estimate the real-world performance of an audio recognition model is by running it against a continuous stream of data, the way that it would be used in an application. Training evaluations are only run against discrete individu...
""" An end to end test which tests: - client cmd line parsing - client operation - client logging - server cmd line parsing - server operation - simulated variantSet backend - server logging """ from __future__ import division from __future__ import print_function from __future__ import unicode_literals import server_...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase from ansible.utils.listify import listify_lookup_plugin_terms class LookupModule(LookupBase): def __lookup_variabless(self, terms, variable...
from openerp import api, models, fields, SUPERUSER_ID class project_project(models.Model): _inherit = 'project.project' partner_country_image = fields.Binary('Partner\'s country flag', related='partner_id.country_id.image') partner_country_name = fields.Char('Partner\'s country name', related='partner_id....
"""Support for Alexa skill service end point.""" import logging import voluptuous as vol from homeassistant.const import CONF_NAME from homeassistant.helpers import config_validation as cv, entityfilter from . import flash_briefings, intent, smart_home_http from .const import ( CONF_AUDIO, CONF_CLIENT_ID, ...
import pandas as pd import numpy as np import math from sklearn.linear_model import LinearRegression train = pd.read_csv('C:/Users/caijiawen/Desktop/train.csv') test = pd.read_csv('C:/Users/caijiawen/Desktop/testt.csv') rate=0.00001 #train=pd.double(train) train=train.astype(float) test=test.astype(float) n=pd.Series(...
#!/usr/bin/env python from subprocess import Popen,PIPE from time import clock, time from pyPgSQL import PgSQL import ConfigParser import os import string import random class GameResult: ai_config1 = '' ai_config2 = '' ai_ident1 = '' ai_ident2 = '' duration = '0' faction1 = '' faction2 = '' is_success = 'false...
# -*- coding: utf-8 -*- import logging import os import time from os import listdir from os.path import join from threading import Thread, Lock from select import select from Queue import Queue, Empty import openerp import openerp.addons.hw_proxy.controllers.main as hw_proxy from openerp import http from openerp.http ...
import os import os.path import re import sys import subprocess import shlex # WAF modules from waflib import Options, Utils, Logs, TaskGen, Build, Context from waflib.Errors import WafError # these are set from the main wscript file APPNAME=None VERSION=None bld=None def get_command_template(env, arguments=()): ...
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} import os from ansible.module_utils.basic import AnsibleModule def is_installed(xbps_output): """Returns package install state""" return bool(len(xbps_output)) def qu...
from subprocess import Popen,PIPE import sys import json result = {} result['all'] = {} pipe = Popen(['virsh', '-q', '-c', 'lxc:///', 'list', '--name', '--all'], stdout=PIPE, universal_newlines=True) result['all']['hosts'] = [x[:-1] for x in pipe.stdout.readlines()] result['all']['vars'] = {} result['all']['vars']['a...
#! /usr/bin/python """ This will generate an API file for formula. in dir/statsmodels/formula/api.py It first builds statsmodels in place, then generates the file. It's to be run by developers to add files to the formula API without having to maintain this by hand. usage generate_formula_api /home/skipper/statsmodel...
"""AffineLinearOperator Tests.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib import linalg from tensorflow.contrib.distributions.python.ops.bijectors.affine_linear_operator import AffineLinearOperator from te...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} import traceback import xml.dom.minidom from xml.etree.ElementTree import fromstring, tost...
#!/usr/bin/env python2 #!---coding:utf-8--- from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0 from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0 from selenium.common.exceptions...
""" Nose test runner module. This script is a front-end to "nosetests" which installs SQLAlchemy's testing plugin into the local environment. The script is intended to be used by third-party dialects and extensions that run within SQLAlchemy's testing framework. The runner can be invoked via:: python -m sqlal...
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} import re try: import shade HAS_SHADE = True except ImportError: HAS_SHADE = False from distutils.version import StrictVersion def main(): argument_spec = open...
from flatland import Form, String from flatland.ext.creditcard import CreditCardNumber, VISA, MASTERCARD def test_simple(): class Schema(Form): num = CreditCardNumber.named('num') data = Schema({}) assert not data.validate() assert data.el('num').errors e1 = list(data.el('num').errors) ...
from __future__ import print_function from os import environ from twisted.internet import reactor from twisted.internet.defer import inlineCallbacks from autobahn.wamp.types import SubscribeOptions from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner class Component(ApplicationSession): """ ...
from sympy import (pi, sin, cos, Symbol, Integral, summation, sqrt, log, oo, LambertW, I, meijerg, exp_polar, Max) from sympy.plotting import (plot, plot_parametric, plot3d_parametric_line, plot3d, plot3d_parametric_surface) from sympy.plotting.plot import unset_show from ...
from case9_3_1 import Case9_3_1 class Case9_3_7(Case9_3_1): DESCRIPTION = """Send fragmented text message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 256k.""" EXPECTATION = """Receive echo'ed text message (with payload as sent).""" def init(self): self.DAT...
from __future__ import absolute_import, division, print_function __metaclass__ = type from functools import wraps from ansible.module_utils._text import to_native PYXCLI_INSTALLED = True try: from pyxcli import client, errors except ImportError: PYXCLI_INSTALLED = False AVAILABLE_PYXCLI_FIELDS = ['pool', 'si...
RELEASE_LEVELS = [ALPHA, BETA, RELEASE_CANDIDATE, FINAL] = ['alpha', 'beta', 'candidate', 'final'] RELEASE_LEVELS_DISPLAY = {ALPHA: ALPHA, BETA: BETA, RELEASE_CANDIDATE: 'rc', FINAL: ''} # version_info format: (MAJOR, MINOR, MICRO, RELEASE_L...
""" Test the lms/staticbook views. """ import textwrap import mock import requests from django.test.utils import override_settings from django.core.urlresolvers import reverse, NoReverseMatch from courseware.tests.modulestore_config import TEST_DATA_MIXED_MODULESTORE from student.tests.factories import UserFactory,...
# -*- coding: utf-8 -*- """QGIS Unit tests for QgsNetworkContentFetcher .. 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 the Free Software Foundation; either version 2 of the License, or (at your option) any later versio...
import fnmatch import optparse import os import sys REPOSITORY_ROOT = os.path.abspath(os.path.join( os.path.dirname(__file__), '..', '..', '..')) sys.path.append(os.path.join(REPOSITORY_ROOT, 'build/android/gyp/util')) import build_utils def ExtractJars(options): # The paths of the files in the jar will be th...
from telex import auth from telex.utils.decorators import pm_only from telex import plugin class ConfigPlugin(plugin.TelexPlugin): """ Plugin to manage other plugin configuration. """ patterns = { "^{prefix}config ([\w-]+) show$": "show_options", "^{prefix}config ([\w-]+) set ([\w-]+) ...
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'EmailUser.email' db.alter_column(u'emailuserapp_emailu...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ bonus property """ from rebulk.remodule import re from rebulk import Rebulk, AppendMatch, Rule from .title import TitleFromPosition from ..common.formatters import cleanup from ..common.validators import seps_surround def bonus(): """ Builder for rebulk obje...
import subprocess import getpass def kill_process_tree(pid, including_parent=True): parent = psutil.Process(pid) for child in parent.get_children(recursive=True): child.kill() if including_parent: parent.kill() def kill_child_processes(): me = os.getpid() kill_process_tree(me, incl...
""" .. module: security_monkey.tests.interface.test_manager :platform: Unix .. version:: $$VERSION$$ .. moduleauthor:: Bridgewater OSS <<EMAIL>> """ from security_monkey.datastore import Account, Technology, Item, store_exception, ExceptionLogs, AccountType from security_monkey import db, ARN_PREFIX from securit...
from pingo.board import Board, DigitalPin, AnalogPin, IN, OUT, HIGH, LOW from pingo.board import AnalogInputCapable class PcDuino(Board, AnalogInputCapable): """ pcDuino board (works on V1 and V3) """ DIGITAL_PINS_PATH = '/sys/devices/virtual/misc/gpio/' ADC_PATH = '/proc/' DIGITAL_PIN_MODES ...
try: from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver from libcloud.common.google import GoogleBaseError, QuotaExceededError, \ ResourceExistsError, ResourceNotFoundError, InvalidRequestError _ = Provider.GCE HAS_LIBCLOUD = True except ImportErro...
"""The tests for the notify.group platform.""" import unittest from unittest.mock import MagicMock, patch from homeassistant.setup import setup_component import homeassistant.components.notify as notify import homeassistant.components.group.notify as group import homeassistant.components.demo.notify as demo from homea...
import os import re import sys import unittest class TestDiscovery(unittest.TestCase): # Heavily mocked tests so I can avoid hitting the filesystem def test_get_name_from_path(self): loader = unittest.TestLoader() loader._top_level_dir = '/foo' name = loader._get_name_from_path('/fo...
import logging import dcm.agent.plugins.api.base as plugin_base import dcmdocker.utils as docker_utils _g_logger = logging.getLogger(__name__) class RestartContainer(docker_utils.DockerJob): protocol_arguments = { "container": ("", True, str, None), "timeout": ("", False, int, 10), } ...
"""Hold and parse key/value configurations. The :class:`Config` describes valid configuration keys along with their types, and performs parsing and type conversion from a dict of config options. It also checks required keys and applies default values if an option is not provided. As an example:: config = Config( ...
from __future__ import print_function import argparse import os from isort import isort def imports_incorrect(filename, show_diff=False): return isort.SortImports(filename, check=True, show_diff=show_diff).incorrectly_sorted def main(argv=None): parser = argparse.ArgumentParser() parser.add_argument(...
from __future__ import absolute_import, division, print_function from re import compile, escape, IGNORECASE from ..util import tagre from ..scraper import _BasicScraper, _ParserScraper from ..helpers import indirectStarter from .common import _WPNaviIn, _WordPressScraper, xpath_class class FalconTwin(_BasicScraper):...
"""tests dicom.extract_keywords functionality""" import unittest from sparktkregtests.lib import sparktk_test import numpy from lxml import etree class DicomExtractKeywordsTest(sparktk_test.SparkTKTestCase): def setUp(self): """import dicom data for testing""" super(DicomExtractKeywordsTest, sel...
from tests.unit import unittest from boto.exception import BotoServerError, S3CreateError, JSONResponseError from httpretty import HTTPretty, httprettified class TestBotoServerError(unittest.TestCase): def test_botoservererror_basics(self): bse = BotoServerError('400', 'Bad Request') self.assert...
# """geonames - Imports geonames.org data files.""" # Copyright © 2007-2021 James Rowe <<EMAIL>> # # SPDX-License-Identifier: GPL-3.0-or-later # # This file is part of upoints. # # upoints is free software: you can redistribute it and/or modify it under the # terms of the GNU General Public License as published by the...
from __future__ import absolute_import, print_function, unicode_literals, division import mock from jormungandr.tests.utils_test import MockRequests from tests.check_utils import get_not_null from .tests_mechanism import AbstractTestFixture, dataset MOCKED_PROXY_CONF = [ { "object_id_tag": "Kisio数字", ...
"""MX-like base classes.""" import cStringIO import struct import dns.exception import dns.rdata import dns.name class MXBase(dns.rdata.Rdata): """Base class for rdata that is like an MX record. @ivar preference: the preference value @type preference: int @ivar exchange: the exchange name @type ...
import struct from ryu.base import app_manager from ryu.controller.handler import MAIN_DISPATCHER from ryu.controller.handler import set_ev_cls from ryu.ofproto import ofproto_v1_0 from ryu.lib import addrconv from ryu.lib import igmplib from ryu.lib.dpid import str_to_dpid class SimpleSwitchIgmp(app_manager.RyuApp)...
import wx # name for translations texts _ = wx.GetTranslation class TBIcon(wx.TaskBarIcon): '''mfc1.TBIcon2(frame, icon, title, textdic) Taskbar applet for the MindfulClock. frame = wx.Frame icon = path to the icon, shown in the taskbar notification area. title = tooltip of the takskbar icon. ...
import os import w3ctestlib os.environ['XML_CATALOG_FILES'] = os.path.join(w3ctestlib.__path__[0], 'catalog/catalog.xml') ###### File path manipulation ###### import os.path from os.path import sep, pardir def assetName(path): return intern(os.path.splitext(os.path.basename(path))[0].lower().encode('ascii')) de...
# -*- coding: utf-8 -*- ## @package ivf.core.sparse_interpolation.sparse_sampling # # ivf.core.sparse_interpolation.sparse_sampling utility package. # @author tody # @date 2016/02/03 import numpy as np from skimage.segmentation import slic, mark_boundaries import cv2 from ivf.core.image_features.ima...
"""Launches Chrome. This script launches Chrome and waits until its window shows up. """ import optparse import sys import time import win32process import chrome_helper def WaitForWindow(process_id, class_pattern): """Waits until a window specified by |process_id| and class name shows up. Args: process_id...
import pytest import re import yaml from mock import Mock, patch from oneview_module_loader import ONEVIEW_MODULE_UTILS_PATH from hpOneView.oneview_client import OneViewClient class OneViewBaseTest(object): @pytest.fixture(autouse=True) def setUp(self, mock_ansible_module, mock_ov_client, request): m...
from openerp.osv import fields,osv class account_invoice_report(osv.osv): _inherit = 'account.invoice.report' _columns = { 'section_id': fields.many2one('crm.case.section', 'Sales Team'), } _depends = { 'account.invoice': ['section_id'], } def _select(self): return sup...
""" Check that all of the certs on all service endpoints validate. """ import unittest from tests.integration import ServiceCertVerificationTest import boto.iam class IAMCertVerificationTest(unittest.TestCase, ServiceCertVerificationTest): iam = True regions = boto.iam.regions() def sample_service_call...
ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} from ansible.module_utils.aws.core import AnsibleAWSModule from ansible.module_utils.ec2 import boto3_conn, ec2_argument_spec, get_aws_connection_info try: import botocore exc...
class Symbols(object): """A dictionary of symbols indexed by the key 'exec_path+0xoffset'.""" def __init__(self): self.symbols = {} # 'foo.so+0x1234' -> |Symbol| def Add(self, exec_file_rel_path, offset, symbol): assert(isinstance(symbol, Symbol)) self.symbols[Symbols._GetKey(exec_file_rel_path, of...
# -*- coding: UTF-8 -*- """ -------------------------------------------------------------------------------- DAI - Desarrollo de Aplicaciones para Internet Grado en Ingeniería Informática (UGR) Proyecto Final: Evita Controles 2015 - Ernesto Serrano <<EMAIL>> -----------------------------------------------------------...
#!/usr/bin/env python """ Build 'use others module data' mechanism for f2py2e. Unfinished. Copyright 2000 Pearu Peterson all rights reserved, Pearu Peterson <<EMAIL>> Permission to use, modify, and distribute this software is given under the terms of the NumPy License. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT Y...
from sqlalchemy import Column, Integer, MetaData, String, Table meta = MetaData() instances_vm_mode = Column('vm_mode', String(length=255, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=...
from __future__ import absolute_import from __future__ import print_function import mock from twisted.trial import unittest from buildbot.mq import simple class SimpleMQ(unittest.TestCase): def setUp(self): self.master = mock.Mock(name='master') self.mq = simple.SimpleMQ(self.master) # th...
#!/usr/bin/env python import sys import uuid from pprint import pprint import time import json if len(sys.argv) < 3: print(sys.argv[0] + " stream value") sys.exit(1) vid = str(uuid.uuid4()) stream = sys.argv[1] value = sys.argv[2] millis = int(round(time.time() * 1000)) inner = { "http://www.modaclouds....
#!/usr/bin/env python3 import sys import argparse import os import subprocess from concurrent.futures import ThreadPoolExecutor, Future from typing import Dict, Set, NamedTuple, List IMAGE_BUCKET_CLI_PARAMETER = "image_bucket" TERRAFORM_PLAN_LOCATION_CLI_PARAMETER = "terraform_plan_location" _PREPARE_OS_IMAGE_SCRIPT...
script = ''' <script> function fetchCachedFileTest() { return fetch('appcache-data.py?type=cached') .then(res => res.text(), _ => { throw new Error('Failed to fetch cached file'); }) .then(text => { if (text != 'cached') { throw new Error('cached file missmatch'); } }); } fu...
# -*- coding: utf-8 -*- """Utilities for advanced work and validation of xml data format .. module:: lib.data.xmlgen :platform: Unix :synopsis: Utilities for advanced work and validation of xml data format .. moduleauthor:: Petr Czaderna <<EMAIL>> """ from lxml import etree from hydratk.lib.system import fs imp...
from __future__ import unicode_literals import six from moto.core.responses import BaseResponse from moto.ec2.utils import keypair_names_from_querystring, filters_from_querystring class KeyPairs(BaseResponse): def create_key_pair(self): name = self.querystring.get('KeyName')[0] keypair = self.ec2...
#!/usr/bin/env python import os import textwrap def main(): targets_dir = 'test/integration/targets' with open('test/integration/target-prefixes.network', 'r') as prefixes_fd: network_prefixes = prefixes_fd.read().splitlines() missing_aliases = [] for target in sorted(os.listdir(targets_di...
"""Functions to copy translations from previous to child distroseries.""" __metaclass__ = type __all__ = [ 'copy_active_translations', ] from lp.services.database.multitablecopy import MultiTableCopy from lp.services.database.sqlbase import ( cursor, quote, ) def omit_redundant_pofiles(from_tab...
from __future__ import unicode_literals import os from datetime import date from unittest import skipUnless from django.apps import apps from django.conf import settings from django.contrib.sitemaps import GenericSitemap, Sitemap from django.contrib.sites.models import Site from django.core.exceptions import Improper...
# -*- coding: iso-8859-1 -*- from DriverInterface import DriverInterface import serial import sys import logging logger = logging.getLogger('drivers.FiscalPrinterDriver') def debugEnabled(*args): # print >> sys.stderr, " ".join(map(str, args)) res = " ".join(map(str, args)) logger.debug(res) def debug...
from neutron_lib import constants as n_const from neutron.plugins.common import utils as p_utils MAX_VLAN_POSTFIX_LEN = 5 def get_vlan_device_name(src_dev, vlan): """Generating the vlan device name.""" # Ensure that independent of the vlan len the same name prefix is used. src_dev = p_utils.get_interfa...
"""This module represents the Sinhala language. .. seealso:: http://en.wikipedia.org/wiki/Sinhala_language """ from translate.lang import common class si(common.Common): """This class represents Sinhala.""" ignoretests = ["startcaps", "simplecaps"]
{'name': 'Switzerland - Payment Slip (BVR/ESR)', 'description': """ Swiss localization Payment slip known as ESR/BVR: ================================================= This addon allows you to print the ESR/BVR report. It will also allows you to reconcile from V11 filea provided by financial institutes. If voucher is...
#!/usr/bin/python # -*- coding: utf-8 -*- from setuptools import setup import pymisp setup( name='pymisp', version=pymisp.__version__, author='Raphaël Vinot', author_email='<EMAIL>', maintainer='Raphaël Vinot', url='https://github.com/MISP/PyMISP', description='Python API for MISP.', p...
"""Plot suite ancestry.""" import textwrap import time import pygraphviz import rose.metadata_graph import rose.opt_parse import rose.reporter import rosie.suite_id import rosie.ws_client import rosie.ws_client_cli class NoConnectionsEvent(rose.reporter.Event): """An event raised if the graph has no edges or n...
# -*- coding: UTF-8 -*- from gi.repository import Gtk, Pango from pychess.System import uistuff from pychess.System.prefix import addDataPrefix from pychess.System.glock import * from pychess.Utils.const import * from pychess.Utils.repr import reprColor, reprPiece from pychess.Utils.lutils.lsort import staticExchangeE...
#!/usr/bin/env python """ This file provides a more advanced example of vtkTable access and manipulation methods. """ from vtk import * #------------------------------------------------------------------------------ # Script Entry Point (i.e., main() ) #----------------------------------------------------------------...
#!/usr/bin/env python # This script converts xrdb (X11) color scheme format to terminator color # scheme format # # Usage: # xrdb2terminator.py path/to/xrdb/files -d /terminator/schemes/output # import os import sys import re import argparse if __name__ == "__main__": parser = argparse.ArgumentParser( d...
import logging import traceback from .base import Command class ImportValidator(Command): """Run the ImportValidate to detect invalid imports """ def __init__(self, callback, uid, vid, linter, code, filename): self.vid = vid self.code = code self.linter = linter self.file...
""" Support for toolset definition. """ import feature, property, generators, property_set import b2.util.set from b2.util import cached, qualify_jam_action from b2.util.utility import * from b2.util import bjam_signature from b2.manager import get_manager __re_split_last_segment = re.compile (r'^(.+)\.([^\.])*') __r...
''' Provides the echo example client. ''' import logging from jsonrpc2 import loop, JsonRpcClient def run(): def _on_result(result): message = result['echo'] logging.info('Echo: %s' % message) return message def on_result(result): message = _on_result(result) message ...
""" Package that implements a stream wrapper that has 'meters' as well as regular output. A 'meter' is a single line of text that can be erased and rewritten repeatedly, without producing multiple lines of output. It can be used to produce effects like progress bars. """ class MeteredStream: """This class is a wr...
__metaclass__ = type from zope.component import getUtility from zope.formlib.interfaces import ( IBrowserWidget, IInputWidget, ) from zope.interface import ( implements, Interface, ) from lp.services.webapp.interfaces import ILaunchBag class RequestWidget(object): '''A widget that sets i...
import locale import re from natural.constant import CONVENTION, ORDINAL_SUFFIX, LARGE_NUMBER_SUFFIX def _format(value, digits=None): if isinstance(value, basestring): value = locale.atof(value) number = long(value) convention = locale.localeconv() if digits is None: digits = convent...
""" Tests for `api.defined_names`. """ import textwrap from jedi import api from ..helpers import TestCase class TestDefinedNames(TestCase): def assert_definition_names(self, definitions, names): self.assertEqual([d.name for d in definitions], names) def check_defined_names(self, source, names): ...
"""Simple API for XML (SAX) implementation for Python. This module provides an implementation of the SAX 2 interface; information about the Java version of the interface can be found at http://www.megginson.com/SAX/. The Python version of the interface is documented at <...>. This package contains the following modu...
"""Test that sys.modules is used properly by import.""" from .. import util from . import util as import_util import sys from types import MethodType import unittest class UseCache(unittest.TestCase): """When it comes to sys.modules, import prefers it over anything else. Once a name has been resolved, sys.m...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging from ccx_keys.locator import CCXLocator from courseware.courses import get_course_by_id from django.db import migrations from django.http import Http404 from django_comment_common.models import FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_MODERAT...
from __future__ import unicode_literals import frappe from frappe.model.naming import make_autoname from frappe import msgprint, _ import frappe.defaults from erpnext.utilities.transaction_base import TransactionBase from erpnext.utilities.address_and_contact import load_address_and_contact from erpnext.accounts.party...
from mock import sentinel from tests import TestCase from exam.decorators import before, after, around, patcher from exam.cases import Exam from tests.dummy import get_thing, get_it, get_prop, ThingClass class SimpleTestCase(object): """ Meant to act like a typical unittest.TestCase """ def __init_...
# -*- coding: utf-8 -*- """ Coinkit ~~~~~ :copyright: (c) 2014 by Halfmoon Labs :license: MIT, see LICENSE for more details. """ import re import binascii from hashlib import sha256 from characters.charset import change_charset HEX_KEYSPACE = "0123456789abcdef" B58_KEYSPACE = "123456789ABCDEFGHJKLMN...
""" A Sphinx extension for documenting devicetree content. It adds a role and a directive with the same name, 'dtcompatible'. :dtcompatible:`vnd,foo` This role can be used inline to make a reference to the generated documentation for a devicetree compatible given as argument. For example, :dtcompatible:`vnd,...
from __future__ import absolute_import from __future__ import unicode_literals import pickle import sys from functools import wraps from kombu import version_info_t from kombu import utils from kombu.utils.text import version_string_as_tuple from kombu.five import string_t from kombu.tests.case import ( Case, M...
# encoding: 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 field 'Alias.created' db.add_column('hansard_alias', 'created', self.gf('django.db.models.fields....