content
stringlengths
4
20k
import pickle import unittest from paramiko.ssh_exception import NoValidConnectionsError class NoValidConnectionsErrorTest (unittest.TestCase): def test_pickling(self): # Regression test for https://github.com/paramiko/paramiko/issues/617 exc = NoValidConnectionsError({('127.0.0.1', '22'): Excep...
import pytest from opentrons.legacy_api.containers import load as containers_load from opentrons.legacy_api.containers.placeable import Container, Deck from opentrons.legacy_api.instruments import pipette # TODO: Modify all calls to get a Well to use the `wells` method @pytest.mark.api1_only def test_protocol_contai...
from __future__ import absolute_import, division, print_function import os import numpy as np from numpy.testing import assert_allclose from astropy.tests.helper import pytest from astropy.table import Table from fermipy.tests.utils import requires_dependency, requires_st_version from fermipy import spectrum try: ...
import os from avocado import Test from avocado.utils import process, archive, build from avocado.utils.software_manager import SoftwareManager class Ioping(Test): """ Disk I/O latency monitoring tool """ def setUp(self): ''' Build Ioping Test ''' # Check for basic...
""" This module is deprecated. Please use `airflow.providers.google.cloud.operators.cloud_storage_transfer_service`. """ import warnings warnings.warn( "This module is deprecated. " "Please use `airflow.providers.google.cloud.operators.cloud_storage_transfer_service`.", DeprecationWarning, stacklevel=...
""" The abstract :py:class:`Target` class. It is a central concept of Luigi and represents the state of the workflow. """ import abc import io import os import random import tempfile import logging from luigi import six logger = logging.getLogger('luigi-interface') @six.add_metaclass(abc.ABCMeta) class Target(objec...
#======================================================================= # # Python Lexical Analyser # # Classes for building NFAs and DFAs # #======================================================================= import sys from Transitions import TransitionMap LOWEST_PRIORITY = -sys.maxint class Machine(obje...
from __future__ import print_function try: from BaseHTTPServer import HTTPServer except ImportError: from http.server import HTTPServer try: from SimpleHTTPServer import SimpleHTTPRequestHandler except ImportError: from http.server import SimpleHTTPRequestHandler from datetime import datetime import ...
import BaseDomsHandler import ResultsStorage import string from cStringIO import StringIO import matplotlib.mlab as mlab from multiprocessing import Process, Manager import numpy as np import matplotlib.pyplot as plt import matplotlib matplotlib.use('Agg') PARAMETER_TO_FIELD = { "sst": "sea_water_temperature"...
import copy from nova import objects from nova.objects import base from nova.objects import fields from nova import utils from nova.virt import hardware @base.NovaObjectRegistry.register class ImageMeta(base.NovaObject): VERSION = '1.0' # These are driven by what the image client API returns # to Nova f...
""" Hong Kong specific Form helpers """ from __future__ import absolute_import, unicode_literals import re from django.core.validators import EMPTY_VALUES from django.forms import CharField from django.forms import ValidationError from django.utils.encoding import smart_text from django.utils.translation import ugett...
""" Tests for misc.py test directives. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['test_directives'] = [ ["""\ .. reStructuredText-test-directive:: Paragraph. """, """\ <document source="test da...
""" Many apps in the LMS maintain their own optimized data structures that they update whenever a course publish is detected. To do this, they listen for the SignalHandler.course_published signal. Sometimes we want to rebuild the data on these apps regardless of an actual change in course content, either to recover fro...
"""This contains the unit tests for treadmill.logcontext.""" import logging import unittest from treadmill import logcontext as lc class AdapterTest(unittest.TestCase): """Unit test for the Adapter class """ def setUp(self): self.appname = 'proid.app#003' def test_init_with_extra_attr(sel...
from django.utils.translation import ugettext_lazy as _ from openstack_auth import utils import horizon from django.conf import settings class Admin(horizon.Dashboard): name = _("Admin") slug = "admin" if getattr(settings, 'POLICY_CHECK_FUNCTION', None): policy_rules = (('identity', 'admin_req...
# -*- coding: utf-8 -*- """ pygments.lexers.console ~~~~~~~~~~~~~~~~~~~~~~~ Lexers for misc console output. :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.lexer import RegexLexer, include, bygroups from pygments.token i...
import re from django.conf import settings # We'll make assets named this be importable by Python code in the sandbox. PYTHON_LIB_ZIP = "python_lib.zip" def can_execute_unsafe_code(course_id): """ Determine if this course is allowed to run unsafe code. For use from the ModuleStore. Checks the `course_i...
import requests import time from prettytable import PrettyTable import sys, getopt from cmdopt import * from network import * from collections import namedtuple def PrintStat(array): print ("\n\n") t = PrettyTable(['Method', 'URL','# Request','MIN','MAX','AVG','RSD']) for i in array: i.statistics() ...
''' Name: mssim2eigen.py Date: 2014-8-25 Version: 1.01 Author: Young Description: Convert the output of MS simulation into eigenstrat format, only deal with 1 repeat siutation Input file: the output of MS simulation Output files: prefix.ind prefix.snp prefix.geno Arguments: -h --help print hel...
from odoo import api, models class AccountTax(models.Model): _inherit = 'account.tax' @api.multi def _get_move_line_vals( self, amount, journal_type, analytic_account_id, default=None, refund=False): if journal_type.endswith('_refund'): journal_type = journal_t...
import unittest from time import strptime from fs.memoryfs import MemoryFS from mock import Mock, patch from xmodule.modulestore.xml import ImportSystem, XMLModuleStore ORG = 'test_org' COURSE = 'test_course' START = '2013-01-01T01:00:00' from .test_course_module import DummySystem as DummyImportSystem class R...
""" A state machine for using TLS Lite with asynchronous I/O. """ class AsyncStateMachine: """ This is an abstract class that's used to integrate TLS Lite with asyncore and Twisted. This class signals wantsReadsEvent() and wantsWriteEvent(). When the underlying socket has become readable or write...
from __future__ import absolute_import import sys from nose import SkipTest from kombu import compression from .utils import TestCase from .utils import mask_modules class test_compression(TestCase): def setUp(self): try: import bz2 # noqa except ImportError: self.has...
""" Check that all of the certs on all EMR endpoints validate. """ import unittest from tests.integration import ServiceCertVerificationTest import boto.emr class EMRCertVerificationTest(unittest.TestCase, ServiceCertVerificationTest): emr = True regions = boto.emr.regions() def sample_service_call(sel...
#! /usr/bin/python import re import os import urlparse from bs4 import BeautifulSoup import html2text from . import builds, config class MilhouseBuildLinkExtractor(builds.BuildLinkExtractor): BUILD_RE = (r"{dist}-{arch}-(?:\d+\.\d+-|)" r"Milhouse-(\d+)-(?:r|%23)(\d+[a-z]*)-g[0-9a-z]+\.tar(|\.bz...
import pytest from electrumx.server.controller import Notifications @pytest.mark.asyncio async def test_simple_mempool(): n = Notifications() notified = [] async def notify(height, touched): notified.append((height, touched)) await n.start(5, notify) mtouched = {'a', 'b'} btouched = ...
"""Keras layers that implement explicit (approximate) kernel feature maps.""" import numpy as np from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.keras import initializers from tensorflow.python.keras...
""" This module houses the OGR & SRS Exception objects, and the check_err() routine which checks the status code returned by OGR methods. """ #### OGR & SRS Exceptions #### class GDALException(Exception): pass class OGRException(Exception): pass class SRSException(Exception): pass class OGRIndexE...
# SGD on linear regression aka least mean squares # Written by Duane Rich # Based on https://github.com/probml/pmtk3/blob/master/demos/LMSdemoSimple.m import numpy as np import matplotlib.pyplot as plt from pyprobml_utils import save_fig #from mpl_toolkits.mplot3d import Axes3D from scipy.optimize import minimize ...
from aqt.qt import * import os, time from aqt.utils import saveGeom, restoreGeom, maybeHideClose, showInfo, addCloseShortcut import aqt # Deck Stats ###################################################################### class DeckStats(QDialog): def __init__(self, mw): QDialog.__init__(self, mw, Qt.Windo...
""" Main module for interactive startup. """ from __future__ import generators import os,sys import glob import __builtin__ from error import * import utils def _probe_config_file(cf): cf_path = os.path.join(os.path.expanduser("~"), cf) try: os.stat(cf_path) except OSError: return Non...
import unittest, os, sys, re, threading, time myDirectory = os.path.realpath(sys.argv[0]) rootDirectory = re.sub("/testing/.*", "", myDirectory) sys.path.append(rootDirectory) from testing.lib import BaseTestSuite from hodlib.HodRing.hodRing import MRSystemDirectoryManager, createMRSystemDirectoryManager from hodl...
""" opcode module - potentially shared between dis and other modules which operate on bytecodes (e.g. peephole optimizers). """ __all__ = ["cmp_op", "hasconst", "hasname", "hasjrel", "hasjabs", "haslocal", "hascompare", "hasfree", "opname", "opmap", "HAVE_ARGUMENT", "EXTENDED_ARG"] cmp_...
from oslo_db import exception as db_exc from oslo_db.sqlalchemy import utils as oslodbutils from oslo_log import log as logging from sqlalchemy.exc import OperationalError from sqlalchemy.ext.compiler import compiles from sqlalchemy import MetaData from sqlalchemy.sql.expression import UpdateBase from sqlalchemy import...
from django.test import TestCase from django.conf import settings from restclients.canvas.roles import Roles from restclients.exceptions import DataFailureException class CanvasTestRoles(TestCase): def test_roles(self): with self.settings( RESTCLIENTS_CANVAS_DAO_CLASS='restclients.dao_imp...
''' Tests autoloading CDB capability of container ''' joe = 7*9 print "In acspyTestAutoLoad.py", joe
from __future__ import unicode_literals import frappe import re def execute(): # NOTE: sequence is important renamed_fields = get_all_renamed_fields() for dt, script_field, ref_dt_field in (("Custom Script", "script", "dt"), ("Print Format", "html", "doc_type")): cond1 = " or ".join("""{0} like "%%{1}%%" """.fo...
import os import saml2 from decouple import config DEBUG = config('DEBUG', cast=bool) SAML_DIR = os.path.dirname(__file__) LOGIN_URL = '/saml2/login/' LOGIN_REDIRECT_URL = '/admin/' SESSION_EXPIRE_AT_BROWSER_CLOSE = True AUTHENTICATION_BACKENDS = ( 'djangosaml2.backends.Saml2Backend', ) SAML_SSO_URL = config(...
{ "name": "Generate Docs of Modules", "version": "8.0.1.0.0", "category": "Tools", "summary": "Modules Technical Guides in RST and Relationship Graphs", "website": "https://odoo-community.org/", "author": "OpenERP SA,Odoo Community Association (OCA)", "contributors": [ "OpenERP SA <h...
import time import socket import xmlrpclib #import tiny_socket import re class RPCGateway(object): def __init__(self, host, port, protocol): self.protocol = protocol self.host = host self.port = port def get_url(self): """Get the url """ return "%s://%s:%s/"%(...
import doctest import pytest from insights.parsers import abrt_ccpp from insights.parsers.abrt_ccpp import AbrtCCppConf from insights.tests import context_wrap from insights.parsers import SkipException ABRT_CONF_CONTENT = """ # Configuration file for CCpp hook # CCpp hook writes its template to the "/proc/sys/kernel...
"""Rolls a git-svn dependency. It takes the path to a dep and a git commit hash or svn revision, and updates the parent repo's DEPS file with the corresponding git commit hash. Sample invocation: [chromium/src]$ roll-dep-svn third_party/WebKit 12345 After the script completes, the DEPS file will be dirty with the n...
import re import gdb.types import gdb.printing def lookup_function_lookup_test(val): class PrintFunctionLookup(object): def __init__(self, val): self.val = val def to_string(self): return ("x=<" + str(self.val["x"]) + "> y=<" + str(self.val["y"]) + ">")...
from __future__ import print_function from copy import copy, deepcopy import datetime import inspect import sys import traceback from django.core.management import call_command from django.core.management.commands import loaddata from django.db import models import south.db from south import exceptions from south.db...
# -*- coding: utf-8 -*- try: # Python 2.7 from collections import OrderedDict except: # Python 2.6 from gluon.contrib.simplejson.ordered_dict import OrderedDict from gluon import current from gluon.storage import Storage def config(settings): """ Template settings for RGIMS: Relie...
''' Provide a ``Theme`` class for specifying new default values for Bokeh :class:`~bokeh.model.Model` properties. ''' from __future__ import absolute_import, print_function import yaml from ..core.has_props import HasProps # whenever we cache that there's nothing themed for a class, we # use this same dict instance...
from __future__ import absolute_import from base64 import b64encode from ..packages.six import b, integer_types from ..exceptions import UnrewindableBodyError ACCEPT_ENCODING = 'gzip,deflate' _FAILEDTELL = object() def make_headers(keep_alive=None, accept_encoding=None, user_agent=None, basic_auth=...
"""DNS Message Flags.""" # Standard DNS flags QR = 0x8000 AA = 0x0400 TC = 0x0200 RD = 0x0100 RA = 0x0080 AD = 0x0020 CD = 0x0010 # EDNS flags DO = 0x8000 _by_text = { 'QR' : QR, 'AA' : AA, 'TC' : TC, 'RD' : RD, 'RA' : RA, 'AD' : AD, 'CD' : CD } _edns_by_text = { 'DO' : DO } # We...
__author__ = 'henar' from xml.etree.ElementTree import Element, SubElement, tostring class Attribute: def __init__(self, att_name, att_value): self.key = att_name self.value = att_value class ProductInstance: def __init__(self, hostname, status, ip, product_release): self.hostname = ...
import cancel_repair import make_invoice # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
"""Keras CategoryEncoding preprocessing layer.""" # pylint: disable=g-classes-have-attributes import numpy as np from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.framework import tensor_shape from te...
from setuptools import setup, find_packages setup( name='djangotribune', version=__import__('djangotribune').__version__, description=__import__('djangotribune').__doc__, long_description=open('README.rst').read(), author='David Thenon', author_email='<EMAIL>', url='http://pypi.python.org/p...
import numpy as np from numpy.testing import assert_array_almost_equal from sklearn.manifold import mds from sklearn.utils.testing import assert_raises def test_smacof(): # test metric smacof using the data of "Modern Multidimensional Scaling", # Borg & Groenen, p 154 sim = np.array([[0, 5, 3, 4], ...
from __future__ import absolute_import import sys import os import logging import inspect import simopt from simopt import MULTI, MA from . import core from .converters import atom, atoms, Link from .ForceFields.forcefield import FORCE_FIELD_COLLECTION, JSONForceField # Option list OPTIONS = simopt.Options([ #...
EXAMPLES = r""" - name: insert/update "Match User" configuation block in /etc/ssh/sshd_config blockinfile: dest: /etc/ssh/sshd_config block: | Match User ansible-agent PasswordAuthentication no - name: insert/update eth0 configuration stanza in /etc/network/interfaces (it might be better ...
# Functions for reading the generated binding JSON data import os, sys import zipfile android_dir = os.path.dirname(sys._getframe(0).f_code.co_filename) common_dir = os.path.abspath(os.path.join(android_dir, "..", "common")) sys.path.append(common_dir) try: import simplejson as json except ImportError, e: import js...
"""This module supports common functions.""" import json import re import logging import webapp2 from google.appengine.api import memcache from hashlib import md5 from appengine_config import runtime_config class CORSRequestHandler(webapp2.RequestHandler): def options(self): """Options to support CORS...
#!/usr/bin/env python # encoding: utf-8 # Thomas Nagy, 2005 (ita) """ Utilities, the stable ones are the following: * h_file: compute a unique value for a file (hash), it uses the module fnv if it is installed (see waf/utils/fnv & http://code.google.com/p/waf/wiki/FAQ) else, md5 (see the python docs) For large...
import os from PIL import Image, ImageFont, ImageDraw import numpy as np import cv2 import pickle import extractFeatures import classifier # Static Config FONT_SIZE = 24 PADDING_TOP_BOTTOM = 8 TRAIN_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789ÄÖÜäöü!"()[]?ß.,+-' # Get list of all fonts for...
""" ID3iconv is a Java based ID3 encoding convertor, here's the Python version. """ import sys import locale import mutagen import mutagen.id3 from mutagen._senf import argv, print_, fsnative from ._util import SignalHandler, OptionParser VERSION = (0, 3) _sig = SignalHandler() def getpreferredencoding(): re...
import subprocess from ansible import utils, errors class LookupModule(object): def __init__(self, basedir=None, **kwargs): self.basedir = basedir def run(self, terms, inject=None, **kwargs): terms = utils.listify_lookup_plugin_terms(terms, self.basedir, inject) if isinstance(terms...
#!/usr/bin/python # -*- coding: utf-8 -*- """ ================================================================================ mingus - Music theory Python package, containers package Copyright (C) 2008-2009, Bart Spaans This program is free software: you can redistribute it and/or modify it under th...
from oslo_concurrency import processutils from oslo_config import cfg from oslo_log import log as logging from nova.i18n import _LE, _LW from nova import paths from nova import utils from nova.virt.libvirt import utils as libvirt_utils from nova.virt.libvirt.volume import fs LOG = logging.getLogger(__name__) volume_...
import logging import sys import tempfile import traceback from asgiref.sync import sync_to_async from django.conf import settings from django.core import signals from django.core.exceptions import RequestAborted, RequestDataTooBig from django.core.handlers import base from django.http import ( FileResponse, Http...
import os import sys import re import catalog import build_tools import converters import base_spec class ext_function_from_specs(object): def __init__(self,name,code_block,arg_specs): self.name = name self.arg_specs = base_spec.arg_spec_list(arg_specs) self.code_block = code_block ...
""" Provides XML I{special character} encoder classes. """ import re class Encoder: """ An XML special character encoder/decoder. @cvar encodings: A mapping of special characters encoding. @type encodings: [(str,str)] @cvar decodings: A mapping of special characters decoding. @type decodings: ...
{ 'name': 'Bill Time on Tasks', 'version': '1.0', 'category': 'Project Management', 'description': """ Synchronization of project task work entries with timesheet entries. ==================================================================== This module lets you transfer the entries under tasks defined ...
import os import shutil from ..utils import temporary_directory class workspace_factory(temporary_directory): def __init__(self, source_space='src', prefix=''): super(workspace_factory, self).__init__(prefix=prefix) self.source_space = source_space def __enter__(self): self.temporar...
"""extra_dhcp_options IPv6 support Revision ID: 16cdf118d31d Revises: 14be42f3d0a5 Create Date: 2014-10-23 17:04:19.796731 """ # revision identifiers, used by Alembic. revision = '16cdf118d31d' down_revision = '14be42f3d0a5' from alembic import op import sqlalchemy as sa from neutron.db import migration CONSTRAIN...
from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from .fields import HexIntegerField, UUIDField # Compatibility with custom user models, while keeping backwards-compatibility with <1.5 AUTH_USER_MODEL = getattr(settings, "AUTH_USER_MODEL", "auth.Use...
# -*- coding: utf-8 -*- """ pygments.filters ~~~~~~~~~~~~~~~~ Module containing filter lookup functions and default filters. :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.token import String, Comment, Ke...
import re _ident_re = re.compile('^[a-zA-Z_-][.a-zA-Z0-9_-]*$') def ident(x): if _ident_re.match(x): return x raise TypeError class Matcher(object): def __init__(self): self._patterns = {} self._dirty = True def __setitem__(self, path, value): assert path not in se...
#!/usr/bin/env python # interactive = False import sys, os datadir = os.path.join(os.path.dirname(__file__), "../data") sys.path.insert(0, datadir) here = os.path.dirname(__file__) import unittest, warnings import numpy as np, histogram.hdf as hh, histogram as H from multiphonon.backward import sqe2dos from dos imp...
import json import requests from odoo import api, fields, models from odoo.exceptions import AccessDenied, UserError from odoo.addons.auth_signup.models.res_users import SignupError from odoo.addons import base base.models.res_users.USER_PRIVATE_FIELDS.append('oauth_access_token') class ResUsers(models.Model): ...
# stdlib from contextlib import contextmanager from random import random, randrange import os import subprocess import sys import time import unittest import urllib as url # 3p from mock import patch from nose.plugins.attrib import attr # project # needed because of the subprocess calls sys.path.append(os.getcwd()) f...
from django.conf.urls import url from .views import UserCriteriaCreateView from .views import UserCriteriaDeleteView from .views import UserCriteriaListView from .views import UserCriteriaUpdateView from .views import FlatAdDetailView from .views import FlatAdListView from .views import review from .views import inter...
""" FLV video parser. Documentation: - FLV File format: http://osflash.org/flv - libavformat from ffmpeg project - flashticle: Python project to read Flash (SWF and FLV with AMF metadata) http://undefined.org/python/#flashticle Author: Victor Stinner Creation date: 4 november 2006 """ from hachoir_parser impo...
from __future__ import unicode_literals import sys from django.utils import six from django.utils.encoding import force_str from django.utils.six.moves import http_cookies # http://bugs.python.org/issue2193 is fixed in Python 3.3+. _cookie_allows_colon_in_names = six.PY3 # Cookie pickling bug is fixed in Python 2.7...
""" Tests for class dashboard (Metrics tab in instructor dashboard) """ import json from django.core.urlresolvers import reverse from django.test.client import RequestFactory from mock import patch from nose.plugins.attrib import attr from capa.tests.response_xml_factory import StringResponseXMLFactory from coursewa...
import sys sys.path.append('..') import time import pygame from pygame import Rect, Color from pathfinder import PathFinder from gridmap import GridMap class Visualizer(object): def __init__(self, screen, field, message_func): self.screen = screen self.field = field self.message_func = m...
""" Tests for pylearn2.utils.general functions. """ from pylearn2.utils import contains_nan, contains_inf, isfinite import numpy as np def test_contains_nan(): """ Tests that pylearn2.utils.contains_nan correctly identifies `np.nan` values in an array. """ arr = np.random.random(100) assert no...
#!/usr/bin/env python from nose.tools import * import networkx as nx class TestDistanceRegular: def test_is_distance_regular(self): assert_true(nx.is_distance_regular(nx.icosahedral_graph())) assert_true(nx.is_distance_regular(nx.petersen_graph())) assert_true(nx.is_distance_regular(nx.cub...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import pytest import sys if sys.version_info < (2, 7): pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7") from ansible.module_utils.basic import AnsibleModule try: from librar...
from twilio.rest.base import TwilioClient from twilio.rest.resources import UNSET_TIMEOUT from twilio.rest.resources.pricing import ( PhoneNumbers, Voice, ) class TwilioPricingClient(TwilioClient): """ A client for accessing the Twilio Pricing API. :param str account: Your Account SID from `your ...
D=16 # number of dimensions for representations N=100 # number of neurons per dimension import nef.nef_theano as nef import nps import nef.convolution import hrr import math import random # semantic pointers do not work well with small numbers of dimensions. # To keep this example model small enough to be easily ...
"""Url for Gstudio User Dashboard""" from django.conf.urls.defaults import url from django.conf.urls.defaults import patterns urlpatterns = patterns('gstudio.views.userdashboard', url(r'^$', 'userdashboard', name='gstudio_userdashboard'), )
import os import sys from telemetry.page import block_page_measurement_results from telemetry.page import buildbot_page_measurement_results from telemetry.page import csv_page_measurement_results from telemetry.page import html_page_measurement_results from telemetry.page import page_measurement_results from telemetry...
# -*- encoding: utf-8 -*- from __future__ import unicode_literals import re from unittest import skipUnless from django.core.management import call_command from django.db import connection from django.test import TestCase, skipUnlessDBFeature from django.utils.six import PY3, StringIO from .models import ColumnTypes...
#!/usr/bin/env python """Tests for time-related utilities.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from absl import app from absl.testing import absltest from grr_response_core.lib import rdfvalue from grr_response_core.lib import time_utils fr...
"""Abstract Base Classes (ABCs) according to PEP 3119.""" from _weakrefset import WeakSet def abstractmethod(funcobj): """A decorator indicating abstract methods. Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unles...
import base64 import hashlib import logging import time from anyjson import simplejson CLOCK_SKEW_SECS = 300 # 5 minutes in seconds AUTH_TOKEN_LIFETIME_SECS = 300 # 5 minutes in seconds MAX_TOKEN_LIFETIME_SECS = 86400 # 1 day in seconds logger = logging.getLogger(__name__) class AppIdentityError(Exception): ...
from django.test import SimpleTestCase from django.utils import translation from ...utils import setup class I18nGetLanguageInfoTagTests(SimpleTestCase): libraries = { 'custom': 'template_tests.templatetags.custom', 'i18n': 'django.templatetags.i18n', } # retrieving language information ...
DEFAULT_PAGE_SIZE = 10 class AjaxModelLoader(object): """ Ajax related model loader. Override this to implement custom loading behavior. """ def __init__(self, name, options): """ Constructor. :param name: Field name """ self.name = ...
import getpass import logging import os import platform import re import shlex import subprocess import sys import webbrowser from webkitpy.common.system.executive import Executive from webkitpy.common.system.platforminfo import PlatformInfo _log = logging.getLogger(__name__) try: import readline except Import...
from django.conf.urls import url from . import views import diag_app from django.views.generic import TemplateView urlpatterns = [ url((r'^$'), views.main_page, name='main'), url((r'^problem_list/([A-Za-z0-9]+)/([0-9]+)'), views.problem_list, name='problem_list'), url((r'^model_detail/([0-9]+)'), views.mo...
# coding=utf-8 """ set_fake_passwords.py Reset all user passwords to a common value. Useful for testing in a development environment. As such, this command is only available when setting.DEBUG is True. """ from django.conf import settings from django.core.management.base import CommandError from django_e...
"""WebLinkback - Handling Linkbacks""" from invenio.config import CFG_SITE_URL, \ CFG_SITE_RECORD, \ CFG_SITE_ADMIN_EMAIL, \ CFG_SITE_LANG from invenio.legacy.weblinkback.config import CFG_WEBLINKBACK_TYPE, \ ...
# coding=utf-8 """ Collect IO Stats Note: You may need to artificially generate some IO load on a disk/partition before graphite will generate the metrics. * http://www.kernel.org/doc/Documentation/iostats.txt #### Dependencies * /proc/diskstats """ import diamond.collector import diamond.convertor import time...
import argparse import base64 from pymongo import MongoClient import uuid import logging from ..hooks import get_mongodb_uri from .utils import do_db_auth from arctic.arctic import Arctic logger = logging.getLogger(__name__) def main(): usage = """arctic_create_user --host research [--db mongoose_user] [--write...
from spack import * class BuildError(Package): """This package has an install method that fails in a build script.""" homepage = "http://www.example.com/trivial_install" url = "http://www.unit-test-should-replace-this-url/trivial_install-1.0.tar.gz" version('1.0', 'foobarbaz') def install(...