content
stringlengths
4
20k
from os.path import abspath from io import BytesIO import copy import unittest # Local imports. from .common import get_example_data # Enthought library imports from mayavi.core.null_engine import NullEngine from mayavi.sources.plot3d_reader import PLOT3DReader from mayavi.filters.select_output import SelectOutput fr...
"""Tests that run_steps is handling recipe failures correctly.""" from PB.recipe_engine import result as result_pb2 from PB.go.chromium.org.luci.buildbucket.proto import common as common_pb2 from recipe_engine import post_process DEPS = [ 'step', 'json' ] def RunSteps(api): raw_result = result_pb2.RawResult...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Here is a wrapper for the *unreleased* electric objects API. Built by • Harper Reed (<EMAIL>) - @harper • Gary Boone (<EMAIL>) - github.com/GaryBoone The Electric Objects API is not yet supported by Electric Objects. It may change or stop workin...
import json import base64 lax_article_versions_response_data = [ { "status": "poa", "version": 1, "published": "2015-11-26T00:00:00Z", ...
import os import re import sys import glob from volk_arch_defs import archs remove_after_underscore = re.compile("_.*"); space_remove = re.compile(" "); leading_space_remove = re.compile("^ *"); replace_arch = re.compile(", const char\* arch"); replace_bracket = re.compile(" {"); replace_volk = re.compile("volk"); d...
""" A registry module for registration of searches. This is based on the registry modules from django_autocomplete_light """ from django.db import models from search_base import SearchBase class SearchRegistry(dict): """ Dict with methods for handling search registration. """ def __init__(self): ...
''' Arithmetic implemented using Python builtin functions instead of logic gates ''' '''----------------------------- Imports -----------------------------''' # Hack computer from ._x__components import * '''----------------------------- Helpers -----------------------------''' largestInt_ = 2 ** ( N_BITS - 1 ) -...
# -*- coding: utf-8 -*- """ PE-specific Form helpers. """ from __future__ import absolute_import, unicode_literals from django.contrib.localflavor.pe.pe_region import REGION_CHOICES from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import RegexField, Cha...
""" Functions for creating and restoring url-safe signed JSON objects. The format used looks like this: >>> signing.dumps("hello") 'ImhlbGxvIg:1QaUZC:YIye-ze3TTx7gtSv422nZA4sgmk' There are two components here, separated by a ':'. The first component is a URLsafe base64 encoded JSON of the object passed to dumps(). T...
import logging logger = logging.getLogger('dad.util') TYPE_DESCRIPTOR = { 'V': 'void', 'Z': 'boolean', 'B': 'byte', 'S': 'short', 'C': 'char', 'I': 'int', 'J': 'long', 'F': 'float', 'D': 'double', } ACCESS_FLAGS_CLASSES = { 0x1: 'public', 0x2: 'private', 0x4: 'protecte...
from runtests.mpi import MPITest from nbodykit.io.binary import BinaryFile import os import numpy import tempfile import pickle import pytest @MPITest([1]) def test_data(comm): tmpfile = tempfile.mktemp() with open(tmpfile, 'wb') as ff: # generate data pos = numpy.random.random(si...
import unittest from omrdatasettools.ExportPath import ExportPath class ExportPathTest(unittest.TestCase): def test_get_full_path_without_stroke_thickness(self): # Arrange export_path = ExportPath("data/images", "3-4-Time", "1-13", "png") # Act full_path = export_path.get_full_pa...
"""General utilities around wrappers.""" import importlib import os import sys import pypowervm.wrappers.entry_wrapper as ewrap _wrappers_pkg = ('pypowervm', 'wrappers') _imports = None _this_module = sys.modules[__name__] def _get_imports(): """Imports all modules in pypowervm.wrappers and returns them as a...
from django.http import HttpResponse from django.template import loader, Context, RequestContext from django.utils import six class ContentNotRenderedError(Exception): pass class SimpleTemplateResponse(HttpResponse): rendering_attrs = ['template_name', 'context_data', '_post_render_callbacks'] def __in...
from django.test import TestCase from django.test.client import RequestFactory from django.contrib.auth.models import AnonymousUser from oscar.apps.basket import middleware class TestBasketMiddleware(TestCase): def setUp(self): self.middleware = middleware.BasketMiddleware() self.request = Reque...
import abc from oslo_log import log as logging import six from nova import keymgr LOG = logging.getLogger(__name__) @six.add_metaclass(abc.ABCMeta) class VolumeEncryptor(object): """Base class to support encrypted volumes. A VolumeEncryptor provides hooks for attaching and detaching volumes, which are...
#!/usr/bin/env python3.6 #cython: language_level=3, boundscheck=False, wraparound=False, cdivision=True, profile=False, c_string_type=bytes import os from sys import exit from time import sleep import concurrent.futures class TestClass: def __init__(self): self.executor = concurrent.futures.ThreadPoolExec...
from utils.exceptions import * from utils.scraper import Scraper class Xkcd(Scraper): def __init__(self, base_dir, url_header, log_file): super().__init__(log_file) self._base_dir = base_dir self._url_header = url_header def get_latest(self): """ Uses xkcd's api at ht...
""" This module houses the ctypes function prototypes for OGR DataSource related data structures. OGR_Dr_*, OGR_DS_*, OGR_L_*, OGR_F_*, OGR_Fld_* routines are relevant here. """ from ctypes import c_char_p, c_double, c_int, c_long, c_void_p, POINTER from django.contrib.gis.gdal.envelope import OGREnvelope from djang...
""" Copyright (c) 2006 Jan-Klaas Kollhof This file is part of jsonrpc. jsonrpc 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 ...
""" Tests for volume backup to IBM Tivoli Storage Manager (TSM). """ import json import os import posix from oslo_concurrency import processutils as putils from oslo_utils import timeutils from cinder.backup.drivers import tsm from cinder import context from cinder import db from cinder import exception from cinder ...
from Screens.Screen import Screen from Components.ActionMap import NumberActionMap from Components.SystemInfo import SystemInfo from Components.Label import Label from Components.config import config # this is not so great. MAX_X = 720 MAX_Y = 576 MAX_W = MAX_X * 3 / 4 MAX_H = MAX_Y * 3 / 4 MIN_W = MAX_X / 8 MIN_H = M...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = r''' --- module: vmware_resource_pool_facts short_description: Gathers facts about resource pool inform...
"""Kerberos command""" import daemon from daemon.pidfile import TimeoutPIDLockFile from airflow import settings from airflow.security import kerberos as krb from airflow.utils import cli as cli_utils from airflow.utils.cli import setup_locations @cli_utils.action_logging def kerberos(args): """Start a kerberos t...
from pokemongo_bot.human_behaviour import sleep from pokemongo_bot.base_task import BaseTask class IncubateEggs(BaseTask): SUPPORTED_TASK_API_VERSION = 1 last_km_walked = 0 def initialize(self): self.ready_incubators = [] self.used_incubators = [] self.eggs = [] self.km_w...
import unittest import os from os.path import isfile from coala_utils.ContextManagers import make_temp from coalib.results.Diff import Diff from coalib.results.Result import Result from coalib.results.result_actions.ApplyPatchAction import ApplyPatchAction from coalib.settings.Section import Section class ApplyPatch...
""" ============ Rank filters ============ Rank filters are non-linear filters using the local gray-level ordering to compute the filtered value. This ensemble of filters share a common base: the local gray-level histogram is computed on the neighborhood of a pixel (defined by a 2-D structuring element). If the filter...
# -*- encoding: utf-8 -*- from insights.ui.base import Base, UINoSuchElementError from insights.ui.locators import locators, common_locators from insights.ui.navigator import Navigator import time class Login(Base): """Implements login, logout functions for Foreman UI""" def login(self, username, password, o...
"""Support for Google Maps location sharing.""" from datetime import timedelta import logging from locationsharinglib import Service from locationsharinglib.locationsharinglibexceptions import InvalidCookies import voluptuous as vol from homeassistant.components.device_tracker import PLATFORM_SCHEMA, SOURCE_TYPE_GPS ...
# -*- coding: utf-8 -*- from openerp import models, fields, api, _ from openerp.exceptions import UserError class ResPartner(models.Model): _inherit = "res.partner" firstname = fields.Char('First Name') lastname = fields.Char('Last Name') subscriber = fields.Boolean(string="Subscriber") ...
"""Custom API throttles.""" from django.core.cache import InvalidCacheBackendError, caches from rest_framework.throttling import UserRateThrottle from course_discovery.apps.core.models import UserThrottleRate from course_discovery.apps.publisher.utils import is_publisher_user def throttling_cache(): """ Retu...
(S'51406fe7f36f29042c4a2062e042ee03' p1 (ihappydoclib.parseinfo.moduleinfo ModuleInfo p2 (dp3 S'_namespaces' p4 ((dp5 (dp6 S'compute_equiv_class' p7 (ihappydoclib.parseinfo.functioninfo FunctionInfo p8 (dp9 g4 ((dp10 (dp11 tp12 sS'_exception_info' p13 (dp14 S'ValueError, "Can\'t compute number from atom.number %s atom....
""" If the arbitrary constant class from issue 1336 is ever implemented, this should serve as a set of test cases. """ from sympy import sin, exp, Function, Symbol, S, Pow, Eq, I, sinh, cosh, acos,\ cos, log, Rational, sqrt, Integral from sympy.solvers.ode import constantsimp, constant_renumber from sympy.utilities.py...
# -*- coding:utf-8 -*- from __future__ import unicode_literals from .common import InfoExtractor import re class ToypicsIE(InfoExtractor): IE_DESC = 'Toypics user profile' _VALID_URL = r'https?://videos\.toypics\.net/view/(?P<id>[0-9]+)/.*' _TEST = { 'url': 'http://videos.toypics.net/view/514/cha...
"""Calibration of predicted probabilities.""" # Balazs Kegl <<EMAIL>> # Jan Hendrik Metzen <<EMAIL>> # Mathieu Blondel <<EMAIL>> # # License: BSD 3 clause from __future__ import division import warnings from math import log import numpy as np from scipy.optimize import fmin_bfgs from .base ...
#!/usr/bin env python from tests.unit import unittest from httpretty import HTTPretty from mock import MagicMock import json from boto.cloudsearch.document import DocumentServiceConnection from boto.cloudsearch.document import CommitMismatchError, EncodingError, \ ContentTooLongError, DocumentServiceConnecti...
class AbstractEventListener(object): """ Event listener must subclass and implement this fully or partially """ def before_navigate_to(self, url, driver): pass def after_navigate_to(self, url, driver): pass def before_navigate_back(self, driver): pass def after_na...
from __future__ import unicode_literals from frappe import _ import frappe from erpnext.hr.doctype.daily_work_summary.daily_work_summary import get_user_emails_from_group def execute(filters=None): if not filters.group: return [], [] columns, data = get_columns(), get_data(filters) return columns, data def get_col...
from engine import Update; # --------------------------------------------------- *\ # Background Behaviour # --------------------------------------------------- */ currentPlayer = None; currentBackground = None; # --------------------------------------------------- *\ # [function] setActive() # # * Active the bac...
"""Model ops python wrappers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.tensor_forest.python.ops import gen_model_ops # pylint: disable=unused-import from tensorflow.contrib.tensor_forest.python.ops.gen_model_ops import feat...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_u...
import datetime import pytest from fittrackee import db from fittrackee.workouts.models import Sport, Workout, WorkoutSegment @pytest.fixture() def sport_1_cycling() -> Sport: sport = Sport(label='Cycling') db.session.add(sport) db.session.commit() return sport @pytest.fixture() def sport_1_cyclin...
"""Uploads the results to the flakiness dashboard server.""" # pylint: disable=E1002,R0201 import logging import os import shutil import tempfile import xml from devil.utils import cmd_helper from pylib.constants import host_paths from pylib.results.flakiness_dashboard import json_results_generator from pylib.utils ...
import sys, os import numpy as np import matplotlib.pyplot as plt import theano import theano.tensor as T import lasagne from load_dataset import * from deep import DeepAutoEncoder from sparse_autoencoder import SparseAutoEncoder def main(): X_train, y_train, X_val, y_val, X_test, y_test = load_dataset()...
# -*- encoding: utf-8 -*- """ ** CartoDBClient ** A simple CartoDB client to perform requests against the CartoDB API. Internally it uses OAuth * Requirements: python 2.5 pip install oauth2 pip install simplejson # if you're running python < 2.6 * Example use: user = '<EMAIL>'...
from django.db.backends.base.features import BaseDatabaseFeatures from django.db.utils import InterfaceError from django.utils.functional import cached_property class DatabaseFeatures(BaseDatabaseFeatures): allows_group_by_selected_pks = True can_return_id_from_insert = True can_return_ids_from_bulk_inser...
"""This module provides functions to register AWSAccessKeyIds and AWSSecretKeys. """ import argparse from xml.dom.minidom import parseString as xmlparse import requests def _generate_args(description): """ Generates the base application with required parameters. @param description: Description of the c...
""" Script for exporting all courseware from Mongo to a directory and listing the courses which failed to export """ from django.core.management.base import BaseCommand, CommandError from xmodule.modulestore.xml_exporter import export_course_to_xml from xmodule.modulestore.django import modulestore from xmodule.content...
"""Support for Tellstick Net/Telstick Live sensors.""" import logging from homeassistant.components import sensor, tellduslive from homeassistant.const import ( DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_ILLUMINANCE, DEVICE_CLASS_TEMPERATURE, POWER_WATT, TEMP_CELSIUS, ) from homeassistant.helpers.dispatch...
from openerp.osv import fields, osv from openerp.tools.translate import _ import difflib from openerp import tools class document_page(osv.osv): _name = "document.page" _description = "Document Page" _order = 'name' def _get_page_index(self, cr, uid, page, link=True): index = [] for su...
# Django settings for layla project. import os PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', '<EMAIL>'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'post...
"""Some utility functions for working with headline of Markdown. Terminologies - Headline :: The headline entity OR the text of the headline - Content :: The content under the current headline. It stops after encountering a headline with the same or higher level OR EOF. """ import re import sublime try: from ....
""" A HTML logger. """ import time import cgi import os from . import _Logger from .. import strformat, configuration # ss=1 enables show source validate_html = "http://validator.w3.org/check?ss=1&amp;uri=%(uri)s" # options are the default validate_css = "http://jigsaw.w3.org/css-validator/validator?" \ ...
import py from py.path import SvnAuth import time import sys svnbin = py.path.local.sysfind('svn') def make_repo_auth(repo, userdata): """ write config to repo user information in userdata is used for auth userdata has user names as keys, and a tuple (password, readwrite) as values, wher...
"""Basic neural network layers.""" from ..block import Block, HybridBlock from ..utils import _indent class Sequential(Block): """Stacks `Block`s sequentially. Example:: net = nn.Sequential() # use net's name_scope to give child Blocks appropriate names. with net.name_scope(): ...
import os import unittest from mako import compat from mako import exceptions from mako import lookup from mako import runtime from mako.template import Template from mako.util import FastEncodingBuffer from test import assert_raises_message from test import eq_ from test import template_base from test.util import res...
import os import posixpath import shutil import subprocess import sys def SplitArgsIntoSections(args): sections = [] while len(args) > 0: if not '--' in args: # If there is no '--' left, everything remaining is an entire section. dashes = len(args) else: das...
import argparse import os from common import _utils def main(argv=None): parser = argparse.ArgumentParser(description='ML Analyzer') parser.add_argument('--project', type=str, help='Google Cloud project ID to use.') parser.add_argument('--region', type=str, help='Which zone to run the analyzer.') parser.add_...
class ModuleDocFragment(object): DOCUMENTATION = ''' options: nsip: description: - The ip address of the netscaler appliance where the nitro API calls will be made. - "The port can be specified with the colon (:). E.g. 192.168.1.1:555." required: True nitro_user: ...
#!/usr/bin/env python ''' Run this script inside of src/ and it will look for all the files that were changed this year that still have the last year in the copyright headers, and it will fix the headers on that file using a perl regex one liner. For example: if it finds something like this and we're in 2014 // Copyr...
""" Django settings for LunarLight project. Generated by 'django-admin startproject' using Django 1.10.2. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import...
from thumbor.handlers import ContextHandler from thumbor.context import RequestParameters from thumbor.crypto import Cryptor from thumbor.utils import logger from thumbor.url import Url import tornado.gen as gen import tornado.web class ImagingHandler(ContextHandler): def compute_etag(self): if self.cont...
"""Tests for SavedModel utils.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.core.framework import types_pb2 from tensorflow.core.protobuf import struct_pb2 from tensorflow.python.eager import context from tensorflow.python.eager import...
# -*- coding: utf-8 -*- from __future__ import unicode_literals ''' ======================== Feedback Exception Logic ======================== Scenario "consume" all the Input in the Executable, then: +-----------------------------------------------------------+----------+ | Executable | Scenario | Feed...
""" Base test classes for LMS instructor-initiated background tasks """ import json from uuid import uuid4 from mock import Mock from celery.states import SUCCESS, FAILURE from django.test.testcases import TestCase from django.contrib.auth.models import User from django.test.utils import override_settings from capa...
# FIXME: this should all be confirmed against what a DTD says # (probably in a test; this may not match the DTD exactly, but we # should document just how it differs). # Data taken from http://www.w3.org/TR/html401/index/elements.html try: frozenset except NameError: from sets import Set as frozenset empty_...
import dns.exception import dns.rdata import dns.tokenizer class NSAP(dns.rdata.Rdata): """NSAP record. @ivar address: a NASP @type address: string @see: RFC 1706""" __slots__ = ['address'] def __init__(self, rdclass, rdtype, address): super(NSAP, self).__init__(rdclass, rdtype) ...
"""Utility for opening a file using the default application in a cross-platform manner. Modified from http://code.activestate.com/recipes/511443/. """ __version__ = '1.1x' __all__ = ['open'] import os import sys import webbrowser import subprocess _controllers = {} _open = None class BaseController(object): ''...
import logging import os import sys from Debug import Debug from Config import config class PluginManager: def __init__(self): self.log = logging.getLogger("PluginManager") self.plugin_path = "plugins" # Plugin directory self.plugins = {} # Registered plugins (key: class name, value: l...
import sys, os from twisted.trial import unittest testModule = """ from twisted.trial import unittest class FooTest(unittest.TestCase): def testFoo(self): pass """ dosModule = testModule.replace('\n', '\r\n') testSample = """ '''This module is used by test_loader to test the Trial test loading function...
import os.path as osp import sys import os import six import platform BASEDIR = osp.abspath(osp.dirname(__file__)) if platform.system() == "Windows": DLLNAME = 'cambdll.dll' else: DLLNAME = 'camblib.so' CAMBL = osp.join(BASEDIR, DLLNAME) mock_load = os.environ.get('READTHEDOCS', None) if not mock_load: i...
"""Sigmoid bijector.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn_ops from tensorflow.python.ops.distributions import bijector from tensorflow.python.util import deprecati...
""" Check that all of the certs on all service endpoints validate. """ import unittest from tests.integration import ServiceCertVerificationTest import boto.ec2 class EC2CertVerificationTest(unittest.TestCase, ServiceCertVerificationTest): ec2 = True regions = boto.ec2.regions() def sample_service_call...
from __future__ import print_function import sys try: from metakernel import MetaKernel from metakernel.display import HTML except ImportError: raise Exception("Error: package metakernel not found.(install it running 'pip install metakernel')") import ROOT from JupyROOT.helpers.utils import setStyle, in...
#!/usr/bin/env python import os, sys from daversy import VERSION from daversy.command import Command def main(): cmd = os.path.basename(sys.argv[0]) if len(sys.argv) == 1: print "Type '%s help' for usage." % (cmd) return if sys.argv[1] == 'help' and len(sys.argv) > 2: com...
import logging from openerp.osv import fields, osv from openerp import pooler from openerp.tools.translate import _ _logger = logging.getLogger(__name__) class sale_configuration(osv.osv_memory): _inherit = 'sale.config.settings' _columns = { 'group_invoice_so_lines': fields.boolean('Generate invoic...
ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} # COMMON CODE FOR MIGRATION import re import ansible.module_utils.nxos from ansible.module_utils.basic import get_exception from ansible.module_utils.netcfg import NetworkConfig, ConfigLin...
import espeak4py import time print('Testing espeak4py\n') mySpeaker = espeak4py.Speaker() mySpeaker.say('', wait4prev=True) print('Testing wait4prev') mySpeaker.say('Hello, World!') time.sleep(1) mySpeaker.say('Interrupted!') time.sleep(3) mySpeaker.say('Hello, World!') time.sleep(1) mySpeaker.say('Not Interrupte...
import sys import re from miasm.arch.ia32_arch import * from miasm.core import asmbloc from miasm.core.bin_stream import bin_stream def clean_assembly(instr): ''' just clean the useless space in the instruction string ''' id_1, id_2 = -1, -1 for i in range(len(instr)): if instr[i] == ' ':...
import httplib2 from oslotest import mockpatch from tempest.common import negative_rest_client from tempest import config from tempest.tests import base from tempest.tests import fake_auth_provider from tempest.tests import fake_config from tempest.tests import fake_http class TestNegativeRestClient(base.TestCase): ...
import sys from _lsprof import Profiler, profiler_entry __all__ = ['profile', 'Stats'] def profile(f, *args, **kwds): """XXX docstring""" p = Profiler() p.enable(subcalls=True, builtins=True) try: f(*args, **kwds) finally: p.disable() return Stats(p.getstats()) class Stats(ob...
from __future__ import print_function import sys import re import time import mido from mido import Message def test_midi_in(port): expected_messages_count=0 while expected_messages_count < 7: for message in port.iter_pending(): if message.type in ('note_on', 'note_off', 'program_change', 'sysex'): yield m...
from __future__ import absolute_import, division, unicode_literals from gettext import gettext _ = gettext from . import _base from ..constants import cdataElements, rcdataElements, voidElements from ..constants import spaceCharacters spaceCharacters = "".join(spaceCharacters) class LintError(Exception): pass ...
# 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 'Project.build_pdf' db.add_column('projects_project', 'build_pdf', self.gf('django.db.models.fields...
import copy import warnings import unittest from test.test_support import run_unittest, TestFailed # Fake a number that implements numeric methods through __coerce__ class CoerceNumber: def __init__(self, arg): self.arg = arg def __repr__(self): return '<CoerceNumber %s>' % repr(self.arg) ...
""" Sets up the terminal color scheme. """ import os import sys from django.utils import lru_cache, termcolors def supports_color(): """ Returns True if the running system's terminal supports color, and False otherwise. """ plat = sys.platform supported_platform = plat != 'Pocket PC' and (pl...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import multiprocessing import os import stat import tempfile import time import warnings import random from ansible import constants as C from ansible.errors import AnsibleError from ansible.module_utils.six import text_type from ...
""" receivers of course_published and library_updated events in order to trigger indexing task """ from datetime import datetime from functools import wraps import logging from django.core.cache import cache from django.dispatch import receiver from pytz import UTC from contentstore.courseware_index import Coursewar...
"""Fetch one URL and write its content to stdout. This version adds a Request object. """ import sys import urllib.parse from http.client import BadStatusLine from asyncio import * class Request: def __init__(self, url, verbose=True): self.url = url self.verbose = verbose self.parts = ...
try: import sys, os import errno import signal configdir = '../' testdir = os.path.dirname(__file__) sys.path.insert(0, os.path.dirname(__file__)) sys.path.insert(0, os.path.abspath(os.path.join(testdir, configdir))) import os.path from selenium import webdriver from selenium.web...
import sys import time import os import string import re import array import platform import datetime import struct class FTraceLine: time = 0.0 length = 0.0 fcall = False freturn = False fevent = False depth = 0 name = "" def __init__(self, t, m, d): self.time = float(t) if(d == 'traceevent'): self.nam...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import os.path import tempfile import re from ansible.plugins.action import ActionBase from ansible.utils.boolean import boolean from ansible.utils.hashing import checksum_s class ActionModule(ActionBase): TRANSFE...
"""Tests for db.task layer.""" import datetime import json import ddt import jsonschema import mock from rally.common import objects from rally import consts from rally import exceptions from tests.unit import test @ddt.ddt class TaskTestCase(test.TestCase): def setUp(self): super(TaskTestCase, self).s...
# coding=utf-8 """ Collect Uptime metrics #### Dependencies * /proc/uptime """ from diamond.collector import Collector from diamond import convertor import os class UptimeCollector(Collector): PROC = '/proc/uptime' def get_default_config(self): config = super(UptimeCollector, self).get_defa...
# -*- coding: utf-8 -*- import re from urllib import unquote from module.plugins.Crypter import Crypter from module.plugins.internal.SimpleHoster import _isDirectLink, set_cookies class SimpleDereferer(Crypter): __name__ = "SimpleDereferer" __type__ = "crypter" __version__ = "0.02" __pattern...
from openerp import models, fields, api, _ import openerp.addons.decimal_precision as dp class StockInformation(models.Model): _inherit = 'stock.information' @api.multi def _compute_week(self): super(StockInformation, self)._compute_week() p_obj = self.env['procurement.order'] mov...
#by mamat and tsaylor on djangosnippets.org import re from django.conf.urls.defaults import patterns, url from django.contrib import admin from django.http import HttpResponseRedirect from django.utils.functional import update_wrapper class Button(object): def __init__(self, func): self.func_name = func.fun...
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.cloudstack import ( AnsibleCloudStack, cs_argument_spec, cs_required_together ) class ...
""" Covariance estimators using shrinkage. Shrinkage corresponds to regularising `cov` using a convex combination: shrunk_cov = (1-shrinkage)*cov + shrinkage*structured_estimate. """ # Gael Varoquaux <<EMAIL>> # Virgile Fritsch <<EMAIL>> # # License: BSD Style. # avoid division truncation from __fut...
""" Async DNS server Future plans: - Better config file format maybe - Make sure to differentiate between different classes - notice truncation bit Important: No additional processing is done on some of the record types. This violates the most basic RFC and is just plain annoying for resolvers to deal wit...