code
stringlengths
1
199k
from datetime import date import os def today(): return str(date.today()) def check_dir(directory): if not os.path.exists(directory): os.makedirs(directory) def write_list_to_text(data, filename): with open(filename, 'w') as f: f.write('\n'.join(str(d) for d in data)) print "Written to %...
from basic import Basic from singleton import Singleton, S from evalf import EvalfMixin from numbers import Float, Integer from sympify import _sympify, sympify, SympifyError from sympy.mpmath import mpi, mpf from containers import Tuple class Set(Basic): """ Represents any kind of set. Real intervals are r...
from git_repo import GitRepo, MultiGitRepo import json; import os; import re; import subprocess; import sys; import pandas as pd import requests import fnmatch from IPython.nbformat import current as nbformat from IPython.nbconvert import PythonExporter import networkx as nx import compiler from compiler.ast import Fro...
import project_scrum_work_type
_api_key = None _application_key = None _api_version = 'v1' _api_host = None _host_name = None _cacert = True _proxies = None _timeout = 3 _max_timeouts = 3 _max_retries = 3 _backoff_period = 300 _mute = True from datadog.api.comments import Comment from datadog.api.downtimes import Downtime from datadog.api.timeboards...
""" Copyright (C) 2007 Collabora Limited This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distribute...
from spack import * class DtDiamondLeft(Package): """This package has an indirect diamond dependency on dt-diamond-bottom""" homepage = "http://www.example.com" url = "http://www.example.com/dt-diamond-left-1.0.tar.gz" version('1.0', '0123456789abcdef0123456789abcdef') depends_on('dt-diamond-bottom'...
from __future__ import print_function import os import shutil import itertools import tempfile import subprocess from distutils.spawn import find_executable import numpy as np import mdtraj as md from mdtraj.testing import get_fn, eq, skipif HAVE_DSSP = find_executable('mkdssp') DSSP_MSG = "This tests required mkdssp ...
from django.test import TestCase from app.detective.models import Topic from app.detective.utils import topic_cache, get_leafs_and_edges import json class TopicCachierTestCase(TestCase): fixtures = ['app/detective/fixtures/default_topics.json',] def setUp(self): ontology_str = """ [ ...
"""Testing support (tools to test IPython itself). """ def test(): """Run the entire IPython test suite. For fine-grained control, you should use the :file:`iptest` script supplied with the IPython installation.""" # Do the import internally, so that this function doesn't increase total # import tim...
import os import sys import re from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): ...
""" Show how to display two scales on the left and right y axis -- Fahrenheit and Celsius """ import matplotlib.pyplot as plt fig, ax1 = plt.subplots() # ax1 is the Fahrenheit scale ax2 = ax1.twinx() # ax2 is the Celsius scale def Tc(Tf): return (5./9.)*(Tf-32) def update_ax2(ax1): y1, y2 = ax1.get_yli...
from __future__ import unicode_literals import re from .common import InfoExtractor from ..compat import ( compat_etree_fromstring, compat_urllib_request, ) from ..utils import ( ExtractorError, int_or_none, ) class VevoIE(InfoExtractor): """ Accepts urls from vevo.com or in the format 'vevo:{id...
import abc from typing import Union, Any from py4j.java_gateway import JavaObject from pyflink.java_gateway import get_gateway class Function(abc.ABC): """ The base class for all user-defined functions. """ pass class MapFunction(Function): """ Base class for Map functions. Map functions take el...
from .UIElement import UIElement, Root
from lib.actions import YammerAction __all__ = [ 'GetUserByIdAction' ] class GetUserByIdAction(YammerAction): def run(self, id=None): yammer = self.authenticate() user = yammer.users.find(id) return user
"""Framework utilities. @@assert_same_float_dtype @@assert_scalar_int @@convert_to_tensor_or_sparse_tensor @@get_graph_from_inputs @@is_numeric_tensor @@is_non_decreasing @@is_strictly_increasing @@reduce_sum_n @@safe_embedding_lookup_sparse @@with_shape @@with_same_shape @@arg_scope @@add_arg_scope @@has_arg_scope @@a...
from st2common.runners.base_action import Action class IncreaseIndexAndCheckCondition(Action): def run(self, index, pagesize, input): if pagesize and pagesize != "": if len(input) < int(pagesize): return (False, "Breaking out of the loop") else: pagesize = 0 ...
import filecmp import json import os import os.path import re import subprocess import sys import time import tempfile import traceback import uuid import shutil from Utils import HandlerUtil from Common import CommonVariables, CryptItem from ExtensionParameter import ExtensionParameter from DiskUtil import DiskUtil fr...
"""Kazoo Exceptions""" from collections import defaultdict class KazooException(Exception): """Base Kazoo exception that all other kazoo library exceptions inherit from""" class ZookeeperError(KazooException): """Base Zookeeper exception for errors originating from the Zookeeper server""" class Cancelle...
import sqlalchemy as sa from quantum.db import model_base class NetworkState(model_base.BASEV2): """Represents state of vlan_id on physical network""" __tablename__ = 'network_states' physical_network = sa.Column(sa.String(64), nullable=False, primary_key=True) vlan_id =...
"""Train a simple TF classifier for MNIST dataset. This example comes from the cloudml-samples keras demo. github.com/GoogleCloudPlatform/cloudml-samples/blob/master/census/tf-keras """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from six.moves ...
"""Experimental library that exposes XLA operations directly in TensorFlow. It is sometimes useful to be able to build HLO programs directly from TensorFlow. This file provides Tensorflow operators that mirror the semantics of HLO operators as closely as possible. Note: There is no promise of backward or forward compat...
""" Unit test for lvm - Linux Volume Manager """ import os import shutil import tempfile import unittest import mock import treadmill from treadmill import lvm class LVMTest(unittest.TestCase): """Tests for teadmill.fs.""" def setUp(self): self.root = tempfile.mkdtemp() def tearDown(self): i...
"""Interface implementation for cloud client.""" import asyncio from pathlib import Path from typing import Any, Dict import aiohttp from hass_nabucasa.client import CloudClient as Interface from homeassistant.core import callback from homeassistant.components.alexa import smart_home as alexa_sh from homeassistant.comp...
from nova.api.openstack import common class ViewBuilder(common.ViewBuilder): _collection_name = 'os-keypairs' # TODO(takashin): After v2 and v2.1 is no longer supported, # 'type' can always be included in the response. _index_params = ('name', 'public_key', 'fingerprint') _create_params = _index_par...
"""Tests for Python ops defined in nn_grad.py.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.ops import gradient_...
import os from setuptools import find_packages from setuptools import setup base_dir = os.path.dirname(__file__) setup( name='elastalert', version='0.0.55', description='Runs custom filters on Elasticsearch and alerts on matches', author='Quentin Long', author_email='qlo@yelp.com', setup_require...
"""Support for Dialogflow webhook.""" import logging import voluptuous as vol from aiohttp import web from homeassistant.const import CONF_WEBHOOK_ID from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import intent, template, config_entry_flow _LOGGER = logging.getLogger(__name__) DEPEND...
"""High level ssh library. Usage examples: Execute command and get output: ssh = sshclient.SSH("root", "example.com", port=33) status, stdout, stderr = ssh.execute("ps ax") if status: raise Exception("Command failed with non-zero status.") print stdout.splitlines() Execute command with huge outp...
"""Support for media browsing.""" from homeassistant.components.media_player import BrowseMedia from homeassistant.components.media_player.const import ( MEDIA_CLASS_APP, MEDIA_CLASS_DIRECTORY, MEDIA_TYPE_APP, MEDIA_TYPE_APPS, ) def build_app_list(app_list): """Create response payload for app list."...
''' Grains for junos. NOTE this is a little complicated--junos can only be accessed via salt-proxy-minion. Thus, some grains make sense to get them from the minion (PYTHONPATH), but others don't (ip_interfaces) ''' from __future__ import absolute_import import logging __proxyenabled__ = ['junos'] __virtualname__ = 'jun...
"""Generated test for checking pynos based actions """ import xml.etree.ElementTree as ET from st2tests.base import BaseActionTestCase from interface_private_vlan_type import interface_private_vlan_type __all__ = [ 'TestInterfacePrivateVlanType' ] class MockCallback(object): # pylint:disable=too-few-public-methods...
import webob.exc from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova import compute from nova import exception sa_nsmap = {None: wsgi.XMLNS_V11} authorize = extensions.extension_authorizer('compute', 'server_action_list') class ServerActionsTemp...
import sys import argparse import json import datetime import logging import logging.handlers import time import re from opserver_util import OpServerUtils from sandesh_common.vns.ttypes import Module from sandesh_common.vns.constants import ModuleNames, NodeTypeNames import sandesh.viz.constants as VizConstants from p...
A = 1 def f(a): print("a={}".format(a))
from webob import Response as WebobResponse from functools import update_wrapper from zope.interface import Interface from pyramid.interfaces import ( IResponse, ITraverser, IResourceURL, ) from pyramid.config.util import ( action_method, takes_one_arg, ) class AdaptersConfiguratorMixin(obje...
from django.core.exceptions import ImproperlyConfigured from django.core.handlers.wsgi import WSGIHandler, WSGIRequest, get_script_name from django.core.signals import request_finished, request_started from django.db import close_old_connections, connection from django.test import ( RequestFactory, SimpleTestCase, ...
""" common handler,webhandler,apihandler 要获得torngas的中间件等特性需继承这些handler """ import json import tornado.locale from tornado.web import RequestHandler from settings_manager import settings from mixins.exception import UncaughtExceptionMixin from exception import HttpBadRequestError, Http404 from torngas.cache import close...
import csv import jinja2 from collections import namedtuple Row = namedtuple('Row', ('id', 'title', 'body')) with open('submissions.csv') as f: f.readline() reader = csv.reader(f) rows = [Row(row[0], row[1].decode('utf-8'), row[2].decode('utf-8')) for row in reader] template = jinja2.Template(open('submissi...
import cgi import codecs import logging import sys import tempfile import traceback import warnings from asgiref.sync import async_to_sync, sync_to_async from django import http from django.conf import settings from django.core import signals from django.core.exceptions import RequestDataTooBig from django.core.handler...
import datetime import pytz from unittest import TestCase from mock import patch, Mock, call from purchasing.jobs.job_base import JobBase, EmailJobBase from purchasing_test.factories import JobStatusFactory import logging logging.getLogger("factory").setLevel(logging.WARN) class FakeJobBase(JobBase): jobs = [] ...
import wx import wx.html from ..utils.generic_class import GenericClass from ..utils.constants import control, dtype from ..utils.validator import CharValidator import pkg_resources as p class GroupAnalysis(wx.html.HtmlWindow): def __init__(self, parent, counter = 0): from urllib2 import urlopen wx...
"""Usage: <win-path-to-pdb.pdb> This tool will take a PDB on the command line, extract the source files that were used in building the PDB, query SVN for which repository and revision these files are at, and then finally write this information back into the PDB in a format that the debugging tools understand. This all...
"""Truncated SVD for sparse matrices, aka latent semantic analysis (LSA). """ import numpy as np import scipy.sparse as sp try: from scipy.sparse.linalg import svds except ImportError: from ..utils.arpack import svds from ..base import BaseEstimator, TransformerMixin from ..utils import check_array, as_float_ar...
import subprocess import sys import threading import time bundle_id = sys.argv[1] args = sys.argv[2:] logp = subprocess.Popen(['idevicesyslog'], stdout=subprocess.PIPE, bufsize=-1) log = '' def collect_log(): global log while True: out = logp.stdout.read() if out: log = log + out else: retur...
''' Script to generate list of seed nodes for chainparams.cpp. This script expects two text files in the directory that is passed as an argument: nodes_main.txt nodes_test.txt These files must consist of lines in the format <ip> <ip>:<port> [<ipv6>] [<ipv6>]:<port> <onion>.onion 0xDDBBCC...
from __future__ import division, print_function, absolute_import import petl as etl table1 = [['foo', 'bar', 'baz'], [1, 'a', None], [1, None, .23], [1, 'b', None], [2, None, None], [2, None, .56], [2, 'c', None], [None, 'c', .72]] table2 = etl.filld...
""" homeassistant.components.switch.hikvision ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Support turning on/off motion detection on Hikvision cameras. Note: Currently works using default https port only. CGI API Guide: http://bit.ly/1RuyUuF Configuration: To use the Hikvision motion detection switch you will need to add...
import codecs import os from plasTeX.Base import Command from plasTeX.Logging import getLogger log = getLogger() status = getLogger('status') class import_sty(Command): macroName = 'import' args = 'dir:str file:str' def invoke(self, tex): a = self.parse(tex) path = os.path.join(a['dir'], a['...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from mock import Mock from pytest import fixture from uber_rides.errors import ClientError from uber_rides.errors import ErrorDetails from uber_rides.errors import ServerE...
"""A parser for XML, using the derived class as static DTD.""" import re import string version = '0.3' class Error(RuntimeError): pass _S = '[ \t\r\n]+' # white space _opS = '[ \t\r\n]*' # optional white space _Name = '[a-zA-Z_:][-a-zA-Z0-9._:]*' # valid XML name _QStr =...
import errno import operator import os import shutil import site from optparse import SUPPRESS_HELP, Values from typing import Iterable, List, Optional from pip._vendor.packaging.utils import canonicalize_name from pip._internal.cache import WheelCache from pip._internal.cli import cmdoptions from pip._internal.cli.cmd...
""" Support for a local MQTT broker. For more details about this component, please refer to the documentation at https://home-assistant.io/components/mqtt/#use-the-embedded-broker """ import logging import tempfile from homeassistant.core import callback from homeassistant.components.mqtt import PROTOCOL_311 from homea...
import os import sys from unittest2 import TestLoader, TextTestRunner if __name__ == '__main__': tests_dir = os.path.dirname(os.path.abspath(__file__)) authorize_dir = os.path.join(tests_dir, os.path.pardir) sys.path.append(authorize_dir) suite = TestLoader().discover(tests_dir) runner = TextTestRun...
import os from argparse import ArgumentParser import list_white import list_ip def parse_args(): parser = ArgumentParser() parser.add_argument('-i', '--input', dest='input', default=os.path.join('data','whitelist.pac'), help='path to gfwlist') parser.add_argument('-o', '--output', dest='output', default='whitelist...
import os from twisted.internet import reactor from twisted.python import filepath, util from nevow import athena, inevow, loaders, tags, static from twisted.web import server, resource from zope.interface import implements, Interface import coherence.extern.louie as louie from coherence import log class IWeb(Interface...
import unittest import os import time import re import glob import logging try: import autotest.common as common except ImportError: import common from autotest.client.shared.test_utils import mock from autotest.client.shared import boottool from autotest.client import kernel, job, utils, kernelexpand from auto...
import os import shutil from cStringIO import StringIO from tempfile import mkstemp from tests import TestCase, add import warnings warnings.simplefilter("ignore", DeprecationWarning) from mutagen.m4a import M4A, Atom, Atoms, M4ATags, M4AInfo, \ delete, M4ACover, M4AMetadataError try: from os.path import devnull e...
import os import re from avocado import Test from avocado.utils import process, build, archive from avocado.utils.software_manager import SoftwareManager class Flail(Test): ''' Flail is system call fuzzer :avocado: tags=fs ''' def setUp(self): ''' Setup Flail ''' smm ...
import re import aexpect from avocado.utils import process from . import utils_misc from . import error_context class QemuIOParamError(Exception): """ Parameter Error for qemu-io command """ pass class QemuIO(object): """ A class for execute qemu-io command """ def __init__(self, test, p...
""" *************************************************************************** ExtentSelectionPanel.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com *******************************************...
""" Unit tests for module_generator.py. @author: Toon Willems (Ghent University) @author: Kenneth Hoste (Ghent University) """ import os import shutil import sys import tempfile from test.framework.utilities import EnhancedTestCase, init_config from unittest import TestLoader, TestSuite, TextTestRunner, main from vsc.u...
ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.0'} DOCUMENTATION = ''' --- module: data_pipeline version_added: "2.4" author: - Raghu Udiyar <raghusiddarth@gmail.com> (@raags) - Sloane Hertel <shertel@redhat.com> requirements: [...
"""Spellcheck using google""" from urlparse import urljoin import re from madcow.util import Module, strip_html from madcow.util.text import * from madcow.util.http import getsoup class Main(Module): pattern = re.compile(r'^\s*spell(?:\s*check)?\s+(.+?)\s*$', re.I) help = u'spellcheck <word> - use google to spe...
import _surface import chimera try: import chimera.runCommand except: pass from VolumePath import markerset as ms try: from VolumePath import Marker_Set, Link new_marker_set=Marker_Set except: from VolumePath import volume_path_dialog d= volume_path_dialog(True) new_marker_set= d.new_marker_set marker_set...
from django.contrib.auth.decorators import login_required from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse_lazy from django.utils.decorators import method_decorator from django.views.generic import (DetailView, ListView) from django.views...
from django.core import mail from bedrock.mozorg.tests import TestCase from funfactory.urlresolvers import reverse from nose.tools import eq_ class PrivacyFormTest(TestCase): def setUp(self): self.contact = 'foo@bar.com' with self.activate('en-US'): self.url = reverse('privacy') ...
__author__ = 'kszalai'
from openerp.osv import fields, orm class mgmtsystem_nonconformity_type(orm.Model): """Claim Type: Nonconformity, Good Practice, Improvement Opportunity, Observation, ... """ _name = "mgmtsystem.nonconformity.type" _description = "Claim Type" _columns = { 'name': fields.char('Title', siz...
from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests.common import Form from odoo.tests import tagged from odoo import fields @tagged('post_install', '-at_install') class TestAccountMoveInRefundOnchanges(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_templ...
from openerp.osv import fields, osv class ple_3_22 (osv.Model): _name = "l10n_pe.ple_3_22" _inherit = "l10n_pe.ple" _columns= { 'lines_ids': fields.one2many ('l10n_pe.ple_line_3_22', 'ple_3_22_id', 'Lines', readonly=True, states={'draft':[('readonly',False)],}), } def action_reload (self, cr...
""" | Database of molecules that are challenging to optimize. | Geometries from Baker J. Comput. Chem. 14 1085 (1993), as reported in Bakken and Helgaker, J. Chem. Phys. 117, 9160 (2002), with a few further corrections. | No reference energies defined. - **cp** ``'off'`` - **rlxd** ``'off'`` - **subset** - ``'sm...
"""Tests for distutils.command.bdist.""" import os import unittest from test.support import run_unittest from distutils.command.bdist import bdist from distutils.tests import support class BuildTestCase(support.TempdirManager, unittest.TestCase): def test_formats(self): # let's create a ...
"""check for signs of poor design""" from collections import defaultdict from astroid import If, BoolOp from astroid import decorators from pylint.interfaces import IAstroidChecker from pylint.checkers import BaseChecker from pylint.checkers.utils import check_messages from pylint import utils MSGS = { 'R0901': ('T...
data = ( ' @ ', # 0x00 ' ... ', # 0x01 ', ', # 0x02 '. ', # 0x03 ': ', # 0x04 ' // ', # 0x05 '', # 0x06 '-', # 0x07 ', ', # 0x08 '. ', # 0x09 '', # 0x0a '', # 0x0b '', # 0x0c '', # 0x0d '', # 0x0e '[?]', # 0x0f '0', # 0x10 '1', # 0x11 '2', # 0x12 '3', # 0x13 '...
from __future__ import division, print_function, absolute_import from rep.estimators import XGBoostClassifier, XGBoostRegressor from rep.test.test_estimators import check_classifier, check_regression, generate_classification_data __author__ = 'Alex Rogozhnikov' def test_xgboost(): check_classifier(XGBoostClassifier...
from airflow.providers.microsoft.azure.hooks.azure_cosmos import AzureCosmosDBHook from airflow.sensors.base import BaseSensorOperator class AzureCosmosDocumentSensor(BaseSensorOperator): """ Checks for the existence of a document which matches the given query in CosmosDB. Example: .. code-block:: a...
assert hex(unhex(hex(0xcafebabe))) == 'CAFEBABE' assert unhex(hex(unhex('cafebabe'))) == 0xCAFEBABE assert hex(unhex(hex(0xdecaf))) == '000DECAF' assert unhex(hex(unhex('DECAF'))) == 0xDECAF print 'OK' exit()
"""This code example deletes content metadata key hierarchies. To determine which content metadata key hierarchies exist, run get_all_content_metadata_key_hierarchies.py. This feature is only available to DFP video publishers. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file...
from unittest import TestCase from boundary import PluginList from cli_test import CLITest class PluginListTest(TestCase): def setUp(self): self.cli = PluginList() def test_cli_description(self): CLITest.check_description(self, self.cli) def test_cli_help(self): CLITest.check_cli_hel...
from __future__ import absolute_import, division, print_function, unicode_literals from c7n.manager import resources from c7n.query import QueryResourceManager, TypeInfo @resources.register('waf') class WAF(QueryResourceManager): class resource_type(TypeInfo): service = "waf" enum_spec = ("list_web_...
import uuid from tempest_lib import exceptions as lib_exc from tempest.api.identity import base from tempest.common.utils import data_utils from tempest import test class RolesNegativeTestJSON(base.BaseIdentityV2AdminTest): def _get_role_params(self): self.data.setup_test_user() self.data.setup_test...
"""Tests for the Ambiclimate config flow.""" from unittest.mock import AsyncMock, patch import ambiclimate from homeassistant import data_entry_flow from homeassistant.components.ambiclimate import config_flow from homeassistant.config import async_process_ha_core_config from homeassistant.const import CONF_CLIENT_ID, ...
try: import http.client as httplib except ImportError: import httplib import socket from contextlib import contextmanager @contextmanager def tcpip4_socket(host, port): """Open a TCP/IP4 socket to designated host/port.""" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((...
import re from datetime import datetime from tower import ugettext_lazy as _ STATUS_NULL = 0 # No review type chosen yet, add-on is incomplete. STATUS_UNREVIEWED = 1 # Waiting for prelim review. STATUS_PENDING = 2 # Personas (lightweight themes) waiting for review. STATUS_NOMINATED = 3 # Waiting for full review. ST...
from __future__ import absolute_import, division, print_function from .common import Benchmark import numpy as np from numpy.random import RandomState try: from numpy.random import Generator except ImportError: pass class Random(Benchmark): params = ['normal', 'uniform', 'weibull 1', 'binomial 10 0.5', ...
""" This module defines :class:`DataObject`, the abstract base class used by all :module:`neo.core` classes that can contain data (i.e. are not container classes). It contains basic functionality that is shared among all those data objects. """ from copy import deepcopy import warnings import quantities as pq import nu...
__version__ = "2.0" __author__ = ["Richard Jones <richard@cottagelabs.com>"] __license__ = "bsd"
from appengine_wrappers import urlfetch from future import Future class _AsyncFetchDelegate(object): def __init__(self, rpc): self._rpc = rpc def Get(self): return self._rpc.get_result() class AppEngineUrlFetcher(object): """A wrapper around the App Engine urlfetch module that allows for easy async fetc...
import numpy as np import numpy.testing as npt from nose.tools import (assert_equal, assert_almost_equal, assert_raises, assert_true) from skbio.stats import subsample_counts from skbio.diversity.alpha import lladser_pe, lladser_ci from skbio.diversity.alpha._lladser import ( _expand_counts,...
from django.utils import translation import pytest from unittest.mock import Mock from olympia import amo from olympia.activity.models import ActivityLog from olympia.amo import LOG from olympia.amo.tests import addon_factory, days_ago, user_factory from olympia.amo.tests.test_helpers import render from olympia.devhub....
"""Command line tool for generating ProtoRPC definitions from descriptors.""" import errno import logging import optparse import os import sys from protorpc import descriptor from protorpc import generate_python from protorpc import protobuf from protorpc import registry from protorpc import transport from protorpc imp...
from ntsecuritycon import * import win32api, win32security, winerror def GetDomainName(): try: tok = win32security.OpenThreadToken(win32api.GetCurrentThread(), TOKEN_QUERY, 1) except win32api.error as details: if details[0] != winerror.ERROR_NO_TOKEN: ...
from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import cint from frappe.model.naming import validate_name @frappe.whitelist() def rename_doc(doctype, old, new, force=False, merge=False, ignore_permissions=False): """ Renames a doc(dt, old) to doc(dt, new) and updates al...
"""Test result object""" import sys import traceback import unittest from StringIO import StringIO from unittest2 import util from unittest2.compatibility import wraps __unittest = True def failfast(method): @wraps(method) def inner(self, *args, **kw): if getattr(self, 'failfast', False): se...
import inc_const as const PJSUA = ["--null-audio", # UA0 "--null-audio", # UA1 "--null-audio" # UA2 ] PJSUA_EXPECTS = [ # A calls B [0, "", "m"], [0, "", "$PJSUA_URI[1]"], [0, const.STATE_CALLING, ""], [1, const.EVENT_INCOMING_CALL, "a"], [1, "", "200"], [0, const.STATE_CONFIRMED, ""...
""" What: Reproduces Figure 13, third column, of Sanz-Leon P., Knock, S. A., Spiegler, A. and Jirsa V. Mathematical framework for large-scale brain network modelling in The Virtual Brain. Neuroimage, 2014, (in review) Needs: A working installation of tvb Run: python region_deterministic_bnm_g2d...
"""Provides :py:class:`SavedSettingsObject` implementing settings-dict based property storage. See Also -------- :py:mod:`libbe.storage.util.properties` : underlying property definitions """ import libbe from properties import Property, doc_property, local_property, \ defaulting_property, checked_property, fn_check...
"""Various tools used by MIME-reading or MIME-writing programs.""" import os import rfc822 import tempfile __all__ = ["Message","choose_boundary","encode","decode","copyliteral", "copybinary"] class Message(rfc822.Message): """A derived class of rfc822.Message that knows about MIME headers and contai...