content
stringlengths
4
20k
import logging as LOG from quantum.common.utils import find_config_file from quantum.plugins.cisco.common import cisco_configparser as confp from quantum.plugins.cisco.common import cisco_constants as const from quantum.plugins.cisco.common import cisco_exceptions as cexc from quantum.plugins.cisco.db import network_d...
#!/usr/bin/env python3 """ Extract the names of functions within the given IDA Pro database. author: Willi Ballenthin email: <EMAIL> """ import argparse import logging import sys import idb import idb.analysis import idb.netnode logger = logging.getLogger(__name__) def main(argv=None): if ar...
""" Distutils setup script for googlemaps module. """ from distutils.core import setup import sys sys.path.insert(0, 'googlemaps') import googlemaps setup(name='googlemaps', version=googlemaps.VERSION, author='John Kleint', author_email='<EMAIL>', url='http://sourceforge.net/projects/py-goo...
# -*- coding: utf-8 -*- """upload_docs Implements a Distutils 'upload_docs' subcommand (upload documentation to PyPI's pythonhosted.org). """ from base64 import standard_b64encode from distutils import log from distutils.errors import DistutilsOptionError from distutils.command.upload import upload import os import s...
from builtins import object import shutil import os.path import tempfile import unittest import configparser from unittest import mock import responses from bugwarrior import config from bugwarrior.data import BugwarriorData class AbstractServiceTest(object): """ Ensures that certain test methods are implemente...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import pytest import sys from nose.plugins.skip import SkipTest if sys.version_info < (2, 7): raise SkipTest("F5 Ansible modules require Python >= 2.7") from ansible.compat.tests import unittest from ans...
__author__ = 'Martin Felder, <EMAIL>' from scipy import random from pybrain.tools.networking.udpconnection import UDPServer import threading from pybrain.utilities import threaded from time import sleep from pybrain.rl.environments.environment import Environment class ShipSteeringEnvironment(Environment): """ ...
import sys, os, string, re # location of source file, relative to current program directory relativeSourcePath = "../avd/hardware-properties.ini" # location of target file, relative to current program directory relativeTargetPath = "../avd/hw-config-defs.h" def quoteStringForC(str): """quote a string so it can ...
""" Form classes """ from __future__ import unicode_literals import copy from collections import OrderedDict from django.core.exceptions import NON_FIELD_ERRORS, ValidationError # BoundField is imported for backwards compatibility in Django 1.9 from django.forms.boundfield import BoundField # NOQA from django.forms...
''' option declarations. The options will be used to update the settings dict in module common. ''' from optionparser import * def getParser(): ''' make sure the parser is created anew on each request ''' parser = OptionParser() parser.append(BoolOption( "help", ...
""" /*************************************************************************** Albero A QGIS plugin permette di selezionare rapidamente gli elementi di un progetto qgis tramite una struttura ad albero ------------------- begin : 2012-04-06 author : (C) 2012 by Giuseppe D'Amico email ...
from __future__ import unicode_literals import webnotes from webnotes.utils import flt, fmt_money, getdate from webnotes import _ class DocType: def __init__(self,d,dl): self.doc, self.doclist = d, dl def validate(self): self.check_mandatory() self.pl_must_have_cost_center() self.validate_posting_date() ...
import struct import array class proto_env: id = 0 name = "env" size = 4 bytesize = 33 hash = "a7c9bdbae9b7c692af5d65a935fa8c78" meta = (("time",1,"double"),("camera",3,"double"),) def __init__(self): self.time = 0.0; self.camera = array.array('d',[0 for i in range(0,3)]); def decode(self,data): if len(da...
from ..excel_comparsion_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.maxDiff = None filename = 'autofilter06.xlsx' ...
import six # PyPy < 2.6 compatibility try: from libqtile._ffi_pango import ffi except ImportError: from libqtile.ffi_build import pango_ffi as ffi gobject = ffi.dlopen('libgobject-2.0.so') pango = ffi.dlopen('libpango-1.0.so') pangocairo = ffi.dlopen('libpangocairo-1.0.so') def CairoContext(cairo_t): de...
from datetime import time from django.forms import TimeInput from django.test import override_settings from django.utils import translation from .base import WidgetTest class TimeInputTest(WidgetTest): widget = TimeInput() def test_render_none(self): self.check_html(self.widget, 'time', None, html=...
""" Run and manage servers for local development. """ from __future__ import print_function import argparse from paver.easy import * from .assets import collect_assets from .utils.cmd import django_cmd from .utils.process import run_process, run_multi_processes DEFAULT_PORT = {"lms": 8000, "studio": 8001} DEFAULT_SE...
# -*- coding: utf-8 -*- """ sphinx.websupport ~~~~~~~~~~~~~~~~~ Base Module for web support functions. :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ import sys import cPickle as pickle import posixpath from os import path from jinja2...
from collections import deque import unittest from thrift_tools.sniffer import Sniffer from thrift_tools.stream_handler import StreamHandler from thrift_tools.thrift_struct import ThriftField, ThriftStruct from .util import get_pcap_path class BasicTestCase(unittest.TestCase): def setUp(self): pass ...
from rope.base import ast def find_visible(node, lines): """Return the line which is visible from all `lines`""" root = ast_suite_tree(node) return find_visible_for_suite(root, lines) def find_visible_for_suite(root, lines): if len(lines) == 1: return lines[0] line1 = lines[0] line2 ...
import numpy as np import os.path as osp class Imdb(object): """ Base class for dataset loading Parameters: ---------- name : str name of dataset """ def __init__(self, name): self.name = name self.classes = [] self.num_classes = 0 self.image_set_ind...
""" DIRAC API Base Class """ __RCSID__ = '$Id$' import pprint import sys from DIRAC import gLogger, gConfig, S_OK, S_ERROR from DIRAC.Core.Security.ProxyInfo import getProxyInfo, formatProxyInfoAsString from DIRAC.ConfigurationSystem.Client.Helpers.Registry import getDNForUsername from DIRAC.Core.Utilities.Version i...
""" mbed SDK Copyright (c) 2011-2013 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in wr...
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor class RadioFranceIE(InfoExtractor): _VALID_URL = r'^https?://maison\.radiofrance\.fr/radiovisions/(?P<id>[^?#]+)' IE_NAME = 'radiofrance' _TEST = { 'url': 'http://maison.radiofrance.fr/radiovisio...
from __future__ import unicode_literals from guessit.transfo import SingleNodeGuesser from guessit.patterns import find_properties import re import logging log = logging.getLogger(__name__) def guess_properties(string): try: prop, value, pos, end = find_properties(string)[0] return { prop: value ...
"""Unit tests for the Paver asset tasks.""" import os from unittest import TestCase import ddt import paver.tasks import six from mock import patch from paver.easy import call_task, path from watchdog.observers import Observer from pavelib.assets import COLLECTSTATIC_LOG_DIR_ARG, collect_assets from ..utils.envs i...
"""SimpleStore Flask Blueprint""" from flask import Blueprint, render_template from flask.ext.breadcrumbs import register_breadcrumb from invenio.base.i18n import _ from flask import redirect import markdown, os CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) blueprint = Blueprint('docs', __name__, url_pref...
from Child import Child from Node import Node # noqa: I201 ATTRIBUTE_NODES = [ # token-list -> token? token-list? Node('TokenList', kind='SyntaxCollection', element='Token'), # token-list -> token token-list? Node('NonEmptyTokenList', kind='SyntaxCollection', element='Token', omit_w...
from pants.engine.collection import Collection, DeduplicatedCollection class Examples(Collection[int]): """A new type to ensure that subclassing works properly.""" class Examples2(Collection[int]): pass def test_collection_contains() -> None: c1 = Collection([1, 2]) assert 1 in c1 assert 2 in ...
import os.path from django import forms from django.contrib.admin.widgets import FilteredSelectMultiple from django.core.serializers import get_serializer_formats from django.utils.translation import ugettext_lazy as _ from smuggler import settings class MultiFileInput(forms.FileInput): def render(self, name, val...
import threading import unittest import pydevconsole from pydev_imports import xmlrpclib, SimpleXMLRPCServer import sys from pydev_localhost import get_localhost from pydev_ipython_console_011 import get_pydev_frontend try: raw_input raw_input_name = 'raw_input' except NameError: raw_input_name = 'input' ...
"""A pure Python implementation of import.""" __all__ = ['__import__', 'import_module', 'invalidate_caches'] # Bootstrap help ##################################################### # Until bootstrapping is complete, DO NOT import any modules that attempt # to import importlib._bootstrap (directly or indirectly). Since...
"""This code example shows how to get recently updated line items. To create line items, run create_line_items.py.""" import datetime # Import appropriate modules from the client library. from googleads import dfp ORDER_ID = 'INSERT_ORDER_ID_HERE' def main(client, order_id): # Initialize appropriate service. ...
from functools import update_wrapper from django.http import Http404, HttpResponseRedirect from django.contrib.admin import ModelAdmin, actions from django.contrib.admin.forms import AdminAuthenticationForm from django.contrib.auth import logout as auth_logout, REDIRECT_FIELD_NAME from django.contrib.contenttypes impor...
#!python """Windows-specific part of the installation""" from __future__ import print_function import os, sys, shutil pjoin = os.path.join # import setuptools if we can try: import setuptools except ImportError: pass def mkshortcut(target,description,link_file,*args,**kw): """make a shortcut if it does...
import warnings import numpy as np import logging import pandas as pd logger = logging.getLogger(name=__name__) def _to_2d(df): df_2d = to_nd(df, 2) return df_2d def _to_3d(df): df_3d = to_nd(df, 3) return df_3d def to_nd(df, ndim): """ Give a new shape to an input data by duplicating its...
# -*- coding: utf-8 -*- import logging import pprint import werkzeug from werkzeug.urls import url_unquote_plus from odoo import http from odoo.http import request from odoo.addons.payment.models.payment_acquirer import ValidationError from odoo.addons.payment.controllers.portal import PaymentProcessing _logger = log...
"""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 from contextlib import contextmanager import zlib import io from socket import timeout as SocketTimeout from socket import error as SocketError from ._collections import HTTPHeaderDict from .exceptions import ( ProtocolError, DecodeError, ReadTimeoutError, ResponseNotChunked ...
from datetime import date from django.conf import settings from django.utils.http import int_to_base36, base36_to_int from django.utils.crypto import constant_time_compare, salted_hmac from django.utils import six class PasswordResetTokenGenerator(object): """ Strategy object used to generate and check tokens...
""" Nuke 9 exposed a Python API for retrieving performance metrics from nodes during rendering, which had previously only been possible via command-line on Linux and was limited. Using that API, this script extends Nuke's standard node performance profiling with additional data as to where each node's cost fits into t...
import os import subprocess import tempfile import mock from helpers import unittest import luigi import luigi.lock import luigi.notifications luigi.notifications.DEBUG = True class TestCmd(unittest.TestCase): def test_getpcmd(self): p = subprocess.Popen(["sleep", "1"]) self.assertTrue( ...
import unittest2 as unittest from webkitpy.tool.bot.expectedfailures import ExpectedFailures class MockResults(object): def __init__(self, failing_tests=[], failure_limit=10): self._failing_tests = failing_tests self._failure_limit_count = failure_limit def failure_limit_count(self): ...
from __future__ import absolute_import, division, print_function import numpy as np from matplotlib.transforms import blended_transform_factory from glue.core.callback_property import CallbackProperty, add_callback PICK_THRESH = 30 # pixel distance threshold for picking class Grip(object): def __init__(self...
from pathlib import Path import re import gzip import tarfile from elm_doc.run_config import Build from elm_doc.utils import Namespace tarball = Path(__file__).parent.parent / 'assets' / 'assets.tar.gz' bundled_helps = [ 'assets/help/documentation-format.md', 'assets/help/design-guidelines.md', ] bundled_ass...
"""Tests for distutils.sysconfig.""" import os import test import unittest import shutil import subprocess import sys import textwrap from distutils import sysconfig from distutils.tests import support from test.test_support import TESTFN class SysconfigTestCase(support.EnvironGuard, unittest....
"""Abstract tests against the interfaces of the base layer of RPC Framework.""" import threading import time from grpc.framework.base import interfaces from grpc.framework.base import util from grpc.framework.foundation import stream from grpc.framework.foundation import stream_testing from grpc.framework.foundation ...
""" CLI interface for nova bare-metal management. """ import os import sys from oslo.config import cfg from nova import config from nova.openstack.common import cliutils from nova.openstack.common import log as logging from nova import version from nova.virt.baremetal.db import migration as bmdb_migration CONF = ...
"""Tests for Keras combinations.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import unittest from absl.testing import parameterized from tensorflow.python import tf2 from tensorflow.python.eager import context from tensorflow.python.keras import co...
from functools import partial, update_wrapper from django.http import HttpResponse from django.views.generic import RedirectView from django.core.urlresolvers import reverse_lazy from django.contrib.auth.decorators import user_passes_test def empty_view(request, *args, **kwargs): return HttpResponse('') def kwa...
from openerp.osv import fields, osv from openerp.tools.translate import _ class purchase_config_settings(osv.osv_memory): _name = 'purchase.config.settings' _inherit = 'res.config.settings' _columns = { 'default_invoice_method': fields.selection( [('manual', 'Based on purchase order li...
import matplotlib.pyplot as _plt from matplotlib.widgets import Button _plt.style.use('ggplot') ## Plot an interactive version. class LineDrawer(object): def __init__(self, scores, guide_lines, threshold_lines): self.guide_lines = guide_lines self.threshold_lines = threshold_lines self.fig...
from unittest.mock import patch import pytest from pontoon.base.models import ProjectLocale from pontoon.test.factories import ( EntityFactory, LocaleFactory, ResourceFactory, SubpageFactory, TranslatedResourceFactory, ) @pytest.fixture def locale_c(): return LocaleFactory(code="nv", name="N...
from neutron.cmd.sanity import checks from neutron.plugins.openvswitch.agent import ovs_neutron_agent as ovsagt from neutron.tests.common import machine_fixtures from neutron.tests.common import net_helpers from neutron.tests.functional.agent import test_ovs_lib from neutron.tests.functional import base class ARPSpoo...
import os import tempfile import Image import subprocess from django.shortcuts import render, redirect from django.forms.formsets import formset_factory from django.template import RequestContext, loader from django.template.loader import render_to_string from django.contrib import messages from django.contrib.auth im...
"""Useful Script constants and utils.""" from test_framework.script import CScript # To prevent a "tx-size-small" policy rule error, a transaction has to have a # non-witness size of at least 82 bytes (MIN_STANDARD_TX_NONWITNESS_SIZE in # src/policy/policy.h). Considering a Tx with the smallest possible single # input...
"""runpy.py - locating and running Python code using the module namespace Provides support for locating and running Python scripts using the Python module namespace instead of the native filesystem. This allows Python code to play nicely with non-filesystem based PEP 302 importers when locating support scripts as wel...
import py from py._path.svnurl import InfoSvnCommand import datetime import time from svntestbase import CommonSvnTests def pytest_funcarg__path1(request): repo, repourl, wc = request.getfuncargvalue("repowc1") return py.path.svnurl(repourl) class TestSvnURLCommandPath(CommonSvnTests): @py.test.mark.xfail...
""" Base file upload handler classes, and the built-in concrete subclasses """ from __future__ import unicode_literals from io import BytesIO from django.conf import settings from django.core.files.uploadedfile import ( InMemoryUploadedFile, TemporaryUploadedFile, ) from django.utils.encoding import python_2_uni...
#!/usr/bin/env python3 import argparse import datetime import os import traceback import asyncio import termios import sys from prompt_toolkit.completion import WordCompleter from prompt_toolkit.history import FileHistory from prompt_toolkit.shortcuts import print_formatted_text, PromptSession from prompt_toolkit.form...
"""Keras callback classes.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.keras._impl.keras.callbacks import BaseLogger from tensorflow.python.keras._impl.keras.callbacks import Callback from tensorflow.python.keras._impl.keras.ca...
from __future__ import division, print_function, unicode_literals # This code is so you can run the samples without installing the package import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) # testinfo = "s, t 2, s, t 4, s, q" tags = "schedule, position" import cocos from cocos.dir...
from nova import test from lxml import etree import nova.tests.virt.libvirt.fakelibvirt as libvirt def get_vm_xml(name="testname", uuid=None, source_type='file', interface_type='bridge'): uuid_tag = '' if uuid: uuid_tag = '<uuid>%s</uuid>' % (uuid,) return '''<domain type='kvm'> ...
# functions that implement transformations using the hpsModel import numpy as np from scipy.interpolate import interp1d def stochasticTimeScale(stocEnv, timeScaling): """ Time scaling of the stochastic representation of a sound stocEnv: stochastic envelope timeScaling: scaling factors, in time-value pairs retur...
import decimal def isNum(value): # Einai to value arithmos, i den einai ? """ use: Returns False if value is not a number , True otherwise input parameters: 1.value : the value to check against. output: True or False """ if not value: return False try: float(value)...
from openerp.addons.web.http import Controller, route, request from openerp.addons.web.controllers.main import _serialize_exception from openerp.osv import osv import simplejson from werkzeug import exceptions, url_decode from werkzeug.test import Client from werkzeug.wrappers import BaseResponse from werkzeug.datastr...
import os import re from lxml import etree import openerp import openerp.tools as tools import openerp.modules import print_xml import render import urllib from openerp import SUPERUSER_ID from openerp.report.render.rml2pdf import customfonts # # coerce any type to a unicode string (to preserve non-ascii characters...
import unittest2 as unittest import os from copy import deepcopy from webkitpy.common.system.executive_mock import MockExecutive, MockExecutive2 from webkitpy.common.system.outputcapture import OutputCapture from webkitpy.common.system.systemhost_mock import MockSystemHost from webkitpy.port import port_testcase from ...
"""Tests for the Heos config flow module.""" from urllib.parse import urlparse from pyheos import HeosError from homeassistant import data_entry_flow from homeassistant.components import ssdp from homeassistant.components.heos.config_flow import HeosFlowHandler from homeassistant.components.heos.const import DATA_DIS...
__version__ = "2.3.0" from sys import version_info def detect(aBuf): if ((version_info < (3, 0) and isinstance(aBuf, unicode)) or (version_info >= (3, 0) and not isinstance(aBuf, bytes))): raise ValueError('Expected a bytes object, not a unicode object') from . import universaldetector ...
""" This example requires numpy (http://www.numpy.org/) """ import sys import numpy as np from pyspark import SparkContext def parseVector(line): return np.array([float(x) for x in line.split(' ')]) def closestPoint(p, centers): bestIndex = 0 closest = float("+inf") for i in range(len(centers)): ...
from spack import * class PyAppdirs(PythonPackage): """A small Python module for determining appropriate platform-specific dirs, e.g. a "user data dir".""" homepage = "https://github.com/ActiveState/appdirs" url = "https://pypi.io/packages/source/a/appdirs/appdirs-1.4.3.tar.gz" import_modul...
#!/usr/bin/env python __all__ = ['kugou_download'] from ..common import * from json import loads from base64 import b64decode import re import hashlib def kugou_download(url, output_dir=".", merge=True, info_only=False, **kwargs): if url.lower().find("5sing")!=-1: #for 5sing.kugou.com html=get_ht...
# coding=utf-8 # Пример # def parse(): # global regexp, current # terms = [] # term = [] # while current < len(regexp) and regexp[current] != ')': # if regexp[current] == '(': # current += 1 # term.append(parse()) # elif regexp[current] == '|': # te...
from cerbero.commands import Command, register_command from cerbero.utils import N_ from cerbero.bootstrap.bootstraper import Bootstraper class Bootstrap(Command): doc = N_('Bootstrap the build system installing all the dependencies') name = 'bootstrap' def __init__(self): Command.__init__(self, ...
# -*- coding: utf-8 -*- """ *************************************************************************** las2dem.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com --------------------- D...
from django.conf import settings from django.test import TestCase import os from django.test.utils import override_settings from tempfile import NamedTemporaryFile from .status import get_site_status_msg # Get a name where we can put test files TMP_FILE = NamedTemporaryFile(delete=False) TMP_NAME = TMP_FILE.name # Cl...
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline ...
import random, shlex import driver, utils, vcoptparse, workload_runner def prepare_option_parser_mode_flags(opt_parser): opt_parser["valgrind"] = vcoptparse.BoolFlag("--valgrind") opt_parser["valgrind-options"] = vcoptparse.StringFlag("--valgrind-options", "--leak-check=full --track-origins=yes --child-silent...
#!/usr/bin/env python #coding:utf-8 import sys import os import subprocess import time class ToughError(Exception): def __init__(self, message): self.message = message class ToughShell(object): def __init__(self,logfile=None,debug=False): self.logfile = logfile self.is_debug = deb...
from pyflink.datastream.state_backend import (_from_j_state_backend, CustomStateBackend, MemoryStateBackend, FsStateBackend, RocksDBStateBackend, PredefinedOptions) from pyflink.java_gateway import get_gateway from pyflink.pyfli...
def f1(): class A(object): k = 2 def __init__(self, x): # 12 (<A|B>,int) -> None self.x = x self.m = 1 pass def bar(self): # 12 (<A|B>) -> int self.y = 2 return self.x def baz(self): # 16 A self.z = 1 ...
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} try: import ovirtsdk4.types as otypes except ImportError: pass import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ovirt impor...
# -*- coding: utf-8 -*- """ requests.exceptions ~~~~~~~~~~~~~~~~~~~ This module contains the set of Requests' exceptions. """ from .packages.urllib3.exceptions import HTTPError as BaseHTTPError class RequestException(IOError): """There was an ambiguous exception that occurred while handling your request. ...
nsURI = "http://iec.ch/TC57/2009/CIM-schema-cim14?profile=http://iec.ch/TC57/2007/profile#IEC61968" nsPrefix = "cimIEC61968"
# -*- 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 field 'CourseMode.currency' db.add_column('course_modes_coursemode', 'currency', ...
import os import re ROOT_PATH = os.path.join("..", "..", "..") INPUT_FILE = os.path.join(ROOT_PATH, "components", "style", "gecko_bindings", "bindings.rs") OUTPUT_FILE = os.path.join(os.environ["OUT_DIR"], "check_bindings.rs") GLUE_FILE = os.path.join(ROOT_PATH, "ports", "geckolib", "glue.rs") GLUE_OUTPUT_FILE = os.pa...
#!/usr/bin/env python # -*- coding: utf-8 -*- # pofix - perform string fixups on incoming .po files. # # The purpose of this script is to save translators from having to # apply various string fixes needed before stable release by hand. It is # intended to be run on each incoming .po file as the Lord of # Translation...
"""Fix incompatible imports and module references.""" # Authors: Collin Winter, Nick Edds # Local imports from .. import fixer_base from ..fixer_util import Name, attr_chain MAPPING = {'StringIO': 'io', 'cStringIO': 'io', 'cPickle': 'pickle', '__builtin__' : 'builtins', ...
import os import stat import pytest from . import environment from .textwrap import DALS from . import contexts class TestEggInfo: setup_script = DALS(""" from setuptools import setup setup( name='foo', py_modules=['hello'], entry_points={'console_scripts': ...
from openerp import fields, models, api class partner(models.Model): """""" _inherit = 'res.partner' internal_code = fields.Char( 'Internal Code') def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100): args = args or [] ...
import json import time dal = DAL('sqlite://wanke.sqlite3.sqlite') """ 获取推荐页顶部互动的广告信息 http://54.64.105.44/wanketv/live/ads """ def ads(): parseRequest() db = DAL('sqlite://wanke.sqlite3.sqlite') allAds = db.executesql("select * from ads order by _id") result = {} result["error"] = 0 jsonAds =...
""" =========================== Covertype dataset benchmark =========================== Benchmark stochastic gradient descent (SGD), Liblinear, and Naive Bayes, CART (decision tree), RandomForest and Extra-Trees on the forest covertype dataset of Blackard, Jock, and Dean [1]. The dataset comprises 581,012 samples. It ...
"""Manage Treadmill vIPs allocations""" import errno import glob import logging import os from . import fs _LOGGER = logging.getLogger(__name__) class VipMgr(object): """VIP allocation manager. :param basepath: Base directory that will contain all the allocated VIPs. :type basepath: ...
from __future__ import print_function, absolute_import import time import logging from threading import Thread from Queue import Queue, Empty logger = logging.getLogger(__name__) import Hardware.ampfunctions as AmpLib import Hardware.fcgenfunctions as FCGenLib import Hardware.powermeterfunctions as PMeterLib #import ...
import numpy as np import numba as nb import matplotlib.pyplot as plt def calc_ber(e_array): return np.mean(np.abs(e_array)) # Imitate static variable for a python function using decorate and setattr def static_vars(**kwargs): ''' @static_vars(counter=0) def foo(): foo.counter += 1 pri...
import unittest from unittest import mock from unittest.mock import PropertyMock from airflow.exceptions import AirflowException from airflow.providers.google.cloud.hooks.functions import CloudFunctionsHook from tests.providers.google.cloud.utils.base_gcp_mock import ( GCP_PROJECT_ID_HOOK_UNIT_TEST, get_open_m...
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'core'} import re from functools import partial from ansible.module_utils.nxos import run_commands, load_config from ansible.module_utils.nxos import nxos_argument_spec from ansible.module_u...
import mock from oslo_utils import uuidutils from ironic.common import driver_factory from ironic.common import exception from ironic.common import states from ironic.conductor import task_manager from ironic.conductor import utils as conductor_utils from ironic import objects from ironic.tests import base as tests_ba...
from openerp.osv import fields, osv from openerp.tools.translate import _ class product(osv.osv): _inherit = 'product.product' _columns = { 'event_ok': fields.boolean('Event Subscription', help='Determine if a product needs to create automatically an event registration at the confirmation of a sales or...