content stringlengths 4 20k |
|---|
from __future__ import unicode_literals
from io import BytesIO
from xml.dom import minidom
import zipfile
from django.conf import settings
from django.contrib.gis.geos import HAS_GEOS
from django.contrib.sites.models import Site
from django.test import (
TestCase, ignore_warnings, modify_settings, override_settin... |
import aiohttp, asyncio, io, logging, os, re, urllib.request, urllib.error
from bs4 import BeautifulSoup
import plugins
logger = logging.getLogger(__name__)
def _initialise(bot):
plugins.register_handler(_watch_xkcd_link, type="message")
@asyncio.coroutine
def _watch_xkcd_link(bot, event, command):
if event.user.... |
from __future__ import division, print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import numpy as np
from numpy import array, nanmin, nanmax
from sympy import Symbol
from pysces import ModelMap, Scanner, ParScanner
from numpy import NaN, abs
from ...utils.model_graph impor... |
"""
PostgreSQL database backend for Django.
Requires psycopg 2: http://initd.org/projects/psycopg2
"""
import sys
from django.db import utils
from django.db.backends import *
from django.db.backends.signals import connection_created
from django.db.backends.postgresql.operations import DatabaseOperations as Postgresq... |
"""
Safe version of tarfile.extractall which does not extract any files that would
be, or symlink to a file that is, outside of the directory extracted in.
Adapted from:
http://stackoverflow.com/questions/10060069/safely-extract-zip-or-tar-using-python
"""
from os.path import abspath, realpath, dirname, join as joinpa... |
import pickle
import pytest
from praw.models import Subreddit, WikiPage
from ... import UnitTest
class TestSubreddit(UnitTest):
def test_equality(self):
subreddit1 = Subreddit(self.reddit,
_data={'display_name': 'dummy1', 'n': 1})
subreddit2 = Subreddit(self.reddit... |
from rml2txt import parseString, parseNode
""" This engine is the minimalistic renderer of RML documents into text files,
using spaces and newlines to format.
It was needed in some special applications, where legal reports need to be
printed in special (dot-matrix) printers.
"""
# vim:expandtab:smartind... |
from _emerge.BinpkgFetcher import BinpkgFetcher
from _emerge.CompositeTask import CompositeTask
from _emerge.BinpkgVerifier import BinpkgVerifier
from portage import os
class BinpkgPrefetcher(CompositeTask):
__slots__ = ("pkg",) + \
("pkg_path", "_bintree",)
def _start(self):
self._bintree = self.pkg.root_conf... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import (
compat_HTTPError,
compat_str,
compat_urllib_parse_urlencode,
compat_urllib_parse_urlparse,
)
from ..utils import (
ExtractorError,
qualities,
)
class AddAnimeIE(InfoExtractor):
_VAL... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Ui_Wizard.ui'
#
# by: PyQt4 UI code generator 4.9.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s:... |
import netdb,os,random
'''
def test_inspect():
netdb.inspect()
'''
def test_sha256():
assert('d2f4e10adac32aeb600c2f57ba2bac1019a5c76baa65042714ed2678844320d0' == netdb.netdb.sha256('i2p is cool', raw=False))
def test_address_valid():
invalid = netdb.netdb.Address()
valid = netdb.netdb.Address()
valid.cost = 10... |
"""Tests for qutebrowser.utils.error."""
import logging
import pytest
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QMessageBox
from qutebrowser.utils import error, utils
from qutebrowser.misc import ipc
class Error(Exception):
pass
@pytest.mark.parametrize('exc, name, exc_text', [
# "buil... |
"""Discrete BCQ learner implementation.
As described in https://arxiv.org/pdf/1910.01708.pdf.
"""
import copy
from typing import Dict, List, Optional
from acme import core
from acme import types
from acme.adders import reverb as adders
from acme.agents.tf import bc
from acme.tf import losses
from acme.tf import save... |
import hr_salary_employee_bymonth
import hr_yearly_salary_detail
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
"""
Eigenvalue spectrum of graphs.
"""
# Copyright (C) 2004-2015 by
# Aric Hagberg <<EMAIL>>
# Dan Schult <<EMAIL>>
# Pieter Swart <<EMAIL>>
# All rights reserved.
# BSD license.
import networkx as nx
__author__ = "\n".join(['Aric Hagberg <<EMAIL>>',
'Pieter Swart (<EMAIL>)',
... |
import functools
import unittest.case
from oslo_db.sqlalchemy import test_base
import testtools.testcase
from neutron.common import constants as n_const
from neutron.tests import base
from neutron.tests import tools
def create_resource(prefix, creation_func, *args, **kwargs):
"""Create a new resource that does ... |
import theano
from theano import tensor
import numpy
from pylearn2.linear.conv2d import Conv2D, make_random_conv2D
from pylearn2.space import Conv2DSpace
from pylearn2.utils import sharedX
import unittest
try:
scipy_available = True
import scipy.ndimage
except ImportError:
scipy_available = False
class Te... |
try:
from cs import CloudStack, CloudStackException, read_config
has_lib_cs = True
except ImportError:
has_lib_cs = False
# import cloudstack common
from ansible.module_utils.cloudstack import *
class AnsibleCloudStackAffinityGroup(AnsibleCloudStack):
def __init__(self, module):
super(Ansibl... |
from ansible.compat.tests import mock
from ansible.compat.tests import unittest
from ansible.modules.packaging.os import apk
class TestApkQueryLatest(unittest.TestCase):
def setUp(self):
self.module_names = [
'bash',
'g++',
]
@mock.patch('ansible.modules.packaging.os... |
import ansiterm
import os, re, logging, traceback, sys
from Constants import *
zones = ''
verbose = 0
colors_lst = {
'USE' : True,
'BOLD' :'\x1b[01;1m',
'RED' :'\x1b[01;31m',
'GREEN' :'\x1b[32m',
'YELLOW':'\x1b[33m',
'PINK' :'\x1b[35m',
'BLUE' :'\x1b[01;34m',
'CYAN' :'\x1b[36m',
'NORMAL':'\x1b[0m',
'cursor_on' ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from six import PY2
from yaml.scanner import ScannerError
from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, mock_open
from ansible.errors import AnsibleParserError
from ansible.parsing import ... |
"""Request Handler that updates the Expectation version."""
import webapp2
import ispy_api
from common import constants
import gs_bucket
class RebaselineHandler(webapp2.RequestHandler):
"""Request handler to allow test mask updates."""
def post(self):
"""Accepts post requests.
Expects a test_run as a... |
"""
Support for Orvibo S20 Wifi Smart Switches.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.orvibo/
"""
import logging
import voluptuous as vol
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
from homeassistant.con... |
from gi.repository import GObject, Gio, Gtk, Notify # pylint: disable=E0611
import locale
from locale import gettext as _
locale.textdomain('melodius')
import logging
logger = logging.getLogger('melodius')
from melodius_lib.PreferencesDialog import PreferencesDialog
from . import MelodiusLibrary
class PreferencesM... |
import os
import urllib
import urllib2
import shutil
import zipfile
import time
import xbmc
import xbmcgui
import xbmcaddon
import xbmcplugin
import plugintools, scrapertools
import sys,traceback,urllib2,re
addonName = xbmcaddon.Addon().getAddonInfo("name")
addonVersion = xbmcaddon.Addon().getAddon... |
import re
from django.views.decorators.cache import cache_page
from commonware.response.decorators import xframe_allow
from bs4 import BeautifulSoup
from lib import l10n_utils
from bedrock.legal_docs.views import LegalDocView, load_legal_doc
HN_PATTERN = re.compile(r'^h(\d)$')
HREF_PATTERN = re.compile(r'^https?\... |
"""Matcher classes to be used inside of the testtools assertThat framework."""
import pprint
import StringIO
from lxml import etree
from testtools import content
class DictKeysMismatch(object):
def __init__(self, d1only, d2only):
self.d1only = d1only
self.d2only = d2only
def describe(self):... |
"""
Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
RockStor is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2 of the License,
or (at your option) any la... |
import os
from sys import platform as os_name
import logging
###############################################################################
# [Constants]
LOGGER = logging.getLogger("[ENV]")
OS = os_name
SRC_NAME = "PAPARAZZI_SRC"
HERE_TO_SRC = "../../../.."
CONF_NAME = "PAPARAZZI_CONF"
HOME_TO_CONF = "conf"
HOME_N... |
""" Tests for the linecache module """
import linecache
import unittest
import os.path
from test import test_support as support
FILENAME = linecache.__file__
INVALID_NAME = '!@$)(!@#_1'
EMPTY = ''
TESTS = 'inspect_fodder inspect_fodder2 mapping_tests'
TESTS = TESTS.split()
TEST_PATH = os.path.dirname(support.__file_... |
# -*- coding: utf-8 -*-
import copy
from contextlib import contextmanager
import django
from django.db.models import Q
from django.db import models
from django.utils.functional import cached_property
from . import utils
from .cache import CachedTranslation
from .helpers import prefetch_translations
if django.VERSI... |
from mox3 import mox
import six
from nova import context
from nova import test
from nova.tests.unit.virt.xenapi import stubs
from nova.virt.xenapi import driver as xenapi_conn
from nova.virt.xenapi import fake
from nova.virt.xenapi.image import bittorrent
from nova.virt.xenapi import vm_utils
class TestBittorrentSto... |
"""pkgdata is a simple, extensible way for a package to acquire data file
resources.
The getResource function is equivalent to the standard idioms, such as
the following minimal implementation::
import sys, os
def getResource(identifier, pkgname=__name__):
pkgpath = os.path.dirname(sys.modules[p... |
from template.stash import list_op
@list_op("contains")
def list_contains(l, x):
return x in l
import sys
import re
import os
import codecs
from os.path import join, exists, abspath
from template import Template
import w3ctestlib
from Utils import listfiles, escapeToNamedASCII
from OutputFormats import ExtensionMap
... |
import argparse
import os
import re
import sys
parser = argparse.ArgumentParser(
description="""
Take the file at <path> and write it to multiple files, switching to a new file
every time an annotation of the form "// BEGIN file1.swift" is encountered. If
<dir> is specified, place the files in <dir>; otherwise, pu... |
# -*- encoding: utf-8 -*-
import unittest
import tkinter
from tkinter import ttk
class MockTkApp:
def splitlist(self, arg):
if isinstance(arg, tuple):
return arg
return arg.split(':')
def wantobjects(self):
return True
class MockTclObj(object):
typename = 'test'
... |
"""
@author: Andrew Case
@license: GNU General Public License 2.0
@contact: <EMAIL>
@organization:
"""
import datetime
import volatility.obj as obj
import volatility.plugins.mac.common as common
class mac_route(common.AbstractMacCommand):
""" Prints the routing table """
def _get_table(self, ... |
"""Build a sentiment analysis / polarity model
Sentiment analysis can be casted as a binary text classification problem,
that is fitting a linear classifier on features extracted from the text
of the user messages so as to guess wether the opinion of the author is
positive or negative.
In this examples we will use a ... |
import os
import re
import subprocess
import sys
import urlparse
from wptrunner.update.sync import LoadManifest
from wptrunner.update.tree import get_unique_name
from wptrunner.update.base import Step, StepRunner, exit_clean, exit_unclean
from .tree import Commit, GitTree, Patch
import github
from .github import GitH... |
import requests
from flask import current_app
from compair.core import abort
from . import KalturaCore
class Media(object):
@classmethod
def generate_media_entry(cls, ks, upload_token_id, media_type):
entry = cls._api_add(ks, media_type)
entry = cls._api_add_content(ks, entry.get('id'), upload... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
from nose.tools import assert_equal
import matplotlib.dviread as dr
import os.path
original_find_tex_file = dr.find_tex_file
def setup():
dr.find_tex_file = lambda x: x
def teardown():
dr... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
QGISAlgorithmProvider.py
---------------------
Date : December 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
***************... |
""" Regroup variables for deprecated features.
To keep the OpenERP server backward compatible with older modules, some
additional code is needed throughout the core library. This module keeps
track of those specific measures by providing variables that can be unset
by the user to check if her code is future proof.
""... |
from openerp import models, api
class AccountInvoice(models.Model):
_inherit = 'account.invoice'
@api.model
def _get_invoice_key_cols(self):
return super(AccountInvoice, self)._get_invoice_key_cols() + [
'payment_mode_id',
]
@api.model
def _get_first_invoice_fields(se... |
"""Supports webkitpy logging."""
# FIXME: Move this file to webkitpy/python24 since logging needs to
# be configured prior to running version-checking code.
import logging
import os
import sys
import webkitpy
_log = logging.getLogger(__name__)
# We set these directory paths lazily in get_logger() below.
_s... |
import os
curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
import cherrypy
from cherrypy.test import helper
import nose
class RoutesDispatchTest(helper.CPWebCase):
def setup_server():
try:
import routes
except ImportError:
raise nose.SkipTest('Install route... |
import os
from .file_system_service import FileSystemService
from logging import Logger
class TempFolderScope(object):
def __init__(self, file_system, logger):
"""
:type file_system: FileSystemService
:type logger: Logger
"""
self.file_system = file_system
self.logg... |
import nose
from nose.plugins.base import Plugin
class ExtensionPlugin(Plugin):
name = "ExtensionPlugin"
def options(self, parser, env):
Plugin.options(self, parser, env)
def configure(self, options, config):
Plugin.configure(self, options, config)
self.enabled = True
def w... |
"""
Storing actual strings instead of their md5 value appears to
be about 10 times faster.
>>> md5_speed.run(200,50000)
md5 build(len,sec): 50000 0.870999932289
md5 retrv(len,sec): 50000 0.680999994278
std build(len,sec): 50000 0.259999990463
std retrv(len,sec): 50000 0.0599999427795
This test actually takes several ... |
import code
import datetime
import os
import socket
import sys
__all__ = [ 'options', 'arguments', 'main' ]
usage="%prog [gem5 options] script.py [script options]"
version="%prog 2.0"
brief_copyright=\
"gem5 is copyrighted software; use the --copyright option for details."
def parse_options():
import config
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import socket
import uuid
import logging
try:
import logstash
HAS_LOGSTASH = True
except ImportError:
HAS_LOGSTASH = False
from ansible.plugins.callback import CallbackBase
class CallbackModul... |
"""
Module for commands that are DCA specific
"""
import os
from gppylib.gplog import get_default_logger
from base import Command, LOCAL, REMOTE
logger = get_default_logger()
# NOTE THIS IS A CHECK FOR 1040 or later appliance
def is_dca_appliance():
try:
if os.path.isfile('/opt/dca/bin/dca_gpdb_initiali... |
from __future__ import print_function
from itertools import izip
from math import fabs
import operator
from random import shuffle
try:
from scipy.stats.stats import betai
except ImportError:
betai = None
from nltk.util import LazyConcatenation, LazyMap
def accuracy(reference, test):
"""
Given a list ... |
from openerp.addons.mail.tests.common import TestMail
class test_message_compose(TestMail):
def test_OO_mail_mail_tracking(self):
""" Tests designed for mail_mail tracking (opened, replied, bounced) """
pass |
from __future__ import unicode_literals
import frappe
def remove_empty_permissions():
permissions_cache_to_be_cleared = frappe.db.sql_list("""select distinct user
from `tabWebsite Route Permission`
where ifnull(`read`, 0)=0 and ifnull(`write`, 0)=0 and ifnull(`admin`, 0)=0""")
frappe.db.sql("""delete from `tabW... |
"""
Various exceptions that are specific to the SES module.
"""
from boto.exception import BotoServerError
class SESError(BotoServerError):
"""
Sub-class all SES-related errors from here. Don't raise this error
directly from anywhere. The only thing this gets us is the ability to
catch SESErrors separ... |
"""Import a notebook into a Databricks workspace and submit a job run to execute it in a cluster.
Notebook will accept some parameters and access a file in DBFS and some secrets in a secret scope.
"""
from pathlib import Path
import base64
import kfp.dsl as dsl
import kfp.compiler as compiler
import databricks
def cre... |
import os
import re
from itertools import chain
from vistrails.core import debug
from vistrails.core.configuration import get_vistrails_configuration
from vistrails.core.modules.vistrails_module import Module, ModuleError
from vistrails.core.modules.sub_module import read_vistrail, new_abstraction, \
get_abstracti... |
#!/usr/bin/env python
"""Standalone script to check FAUCET configuration, return 0 if provided config OK."""
# Copyright (C) 2015 Brad Cowie, Christopher Lorier and Joe Stringer.
# Copyright (C) 2015 Research and Education Advanced Network New Zealand Ltd.
# Copyright (C) 2015--2019 The Contributors
#
# Licensed unde... |
import os
import requests
from django.template.defaultfilters import slugify
from booktype.utils import config
class AssetCollection(object):
def __init__(self, base_path):
self.base_path = base_path
self.files = {}
def add_files(self, files):
for (asset_id, file_path) in files.ite... |
"""IPv6 address generation with account identifier embedded."""
import hashlib
import netaddr
from nova.i18n import _
def to_global(prefix, mac, project_id):
project_hash = netaddr.IPAddress(
int(hashlib.sha1(project_id).hexdigest()[:8], 16) << 32)
static_num = netaddr.IPAddress(0xff << ... |
from flask import Flask
import eventlet
eventlet.monkey_patch()
from flask import render_template
from sniffer import Sniffer
from flask_socketio import SocketIO, emit
import argparse
PORT = 8000
app = Flask(__name__)
app.config['SECRET_KEY'] = 'kmh_floascope'
socketio = SocketIO(app, async_mode="eventlet")
app.debug ... |
"""The Extended Status Admin API extension."""
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
ALIAS = "os-extended-status"
authorize = extensions.os_compute_soft_authorizer(ALIAS)
class ExtendedStatusController(wsgi.Controller):
def __init__(self, *args, **kwargs):
super(E... |
import product_category_code |
""" Module events
Defines the events and a timer class.
"""
import sys
import time
import traceback
import weakref
class CallableObject:
""" CallableObject(callable)
A class to hold a callable using weak references.
It can distinguish between functions and methods.
"""
def __init__(... |
# -*- coding: utf-8 -*-
"""
flask.signals
~~~~~~~~~~~~~
Implements signals based on blinker if available, otherwise
falls silently back to a noop.
:copyright: (c) 2018 Fulfil.IO Inc.
The blinker fallback code is inspired by Armin's implementation
on Flask.
:copyright: (c) 2015 by Armin... |
"""Deprecation utilities."""
__docformat__ = "restructuredtext en"
import sys
from warnings import warn
from logilab.common.changelog import Version
class DeprecationWrapper(object):
"""proxy to print a warning on access to any attribute of the wrapped object
"""
def __init__(self, proxied, msg=None):
... |
"""DNS TSIG support."""
import hmac
import struct
import dns.exception
import dns.rdataclass
import dns.name
class BadTime(dns.exception.DNSException):
"""Raised if the current time is not within the TSIG's validity time."""
pass
class BadSignature(dns.exception.DNSException):
"""Raised if the TSIG sign... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
import time
from ansible.module_utils.dellos10 import run_commands
from ansible.module_utils.dellos10 import dellos10_argument_spec, check_args
from ansible.module_utils.basic im... |
import itertools
'''
An `accumulator` adds some push-based stream semantics to Python iterators,
which are pull-based (they do stuff when you ask for values, not when data is
available). To do this we define an accumulator as a function from iterators to
iterators, where the output iterator will make exactly one reque... |
from superdesk.utils import get_random_string
from elasticsearch.helpers import reindex
from eve_elastic import get_es, get_indices
import elasticsearch
import superdesk
class RebuildElasticIndex(superdesk.Command):
"""
Rebuild the elastic index from existing data by creating a new index with
the same ali... |
"""
Tests for L{twisted.conch.openssh_compat}.
"""
import os
from twisted.trial.unittest import TestCase
from twisted.python.filepath import FilePath
from twisted.python.compat import set
try:
import Crypto.Cipher.DES3
import pyasn1
except ImportError:
OpenSSHFactory = None
else:
from twisted.conch.o... |
#!/usr/bin/python
from NodeGraphQt import QtWidgets, QtCore, QtGui, QtCompat
from NodeGraphQt.widgets.properties import NodePropWidget
class PropertiesDelegate(QtWidgets.QStyledItemDelegate):
def paint(self, painter, option, index):
"""
Args:
painter (QtGui.QPainter):
opt... |
import warnings
import unittest
import sys
from nose.tools import assert_raises
from sklearn.utils.testing import (
_assert_less,
_assert_greater,
assert_less_equal,
assert_greater_equal,
assert_warns,
assert_no_warnings,
assert_equal,
set_random_state,
assert_raise_message,
ig... |
"""
Utilities for instructor unit tests
"""
import datetime
import json
import random
from django.utils.timezone import utc
from util.date_utils import get_default_time_display
class FakeInfo(object):
"""Parent class for faking objects used in tests"""
FEATURES = []
def __init__(self):
for featur... |
"""
Define common steps for instructor dashboard acceptance tests.
"""
# pylint: disable=missing-docstring
# pylint: disable=redefined-outer-name
from __future__ import absolute_import
from lettuce import world, step
from mock import patch
from nose.tools import assert_in # pylint: disable=no-name-in-module
from c... |
from spack import *
class RDesolve(RPackage):
"""Functions that solve initial value problems of a system of first-order
ordinary differential equations ('ODE'), of partial differential
equations ('PDE'), of differential algebraic equations ('DAE'), and of
delay differential equations."""
... |
import unittest2
from unittest2.test.support import LoggingResult
class Test_FunctionTestCase(unittest2.TestCase):
# "Return the number of tests represented by the this test object. For
# unittest2.TestCase instances, this will always be 1"
def test_countTestCases(self):
test = unittest2.Functio... |
import sys
import subprocess
import datetime
'''
http://nomads.ncep.noaa.gov/cgi-bin/filter_gfs_1p00.pl?dir=%2Fgfs.2015051406
http://www.nco.ncep.noaa.gov/pmb/products/gfs/gfs.t00z.pgrbf00.grib2.shtml
'''
import os
base_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(base_dir)
i = (datetime.datetime.now() - ... |
import numpy
import rasterio
import subprocess
with rasterio.drivers(CPL_DEBUG=True):
# Read raster bands directly to Numpy arrays.
with rasterio.open('tests/data/RGB.byte.tif') as src:
r, g, b = src.read()
# Combine arrays using the 'iadd' ufunc. Expecting that the sum will
# exceed the 8-bi... |
from collections import Iterable, OrderedDict
import re
from coalib.misc import Constants
from coalib.parsing.StringProcessing import (unescaped_split,
unescaped_strip,
unescape)
class StringConverter:
"""
Converts strin... |
'''using scipy signal and numpy correlate to calculate some time series
statistics
original developer notes
see also scikits.timeseries (movstat is partially inspired by it)
added 2009-08-29
timeseries moving stats are in c, autocorrelation similar to here
I thought I saw moving stats somewhere in python, maybe not)... |
from mediadrop.lib.filetypes import VIDEO
from mediadrop.lib.players import FileSupportMixin, RTMP
from mediadrop.lib.test.pythonic_testcase import *
from mediadrop.lib.uri import StorageURI
from mediadrop.model import MediaFile
class FileSupportMixinTest(PythonicTestCase):
def test_can_play_ignores_empty_contain... |
"""This module implements a string formatter based on the standard PEP
292 string.Template class extended with function calls. Variables, as
with string.Template, are indicated with $ and functions are delimited
with %.
This module assumes that everything is Unicode: the template and the
substitution values. Bytestrin... |
# coding=utf-8
"""InaSAFE Disaster risk tool by Australian Aid - Volcano Point on Building
Impact Function.
Contact : <EMAIL>
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; eith... |
"""Filter and decorator to wave enable django sites.
If you want to require wave authentication for every handler, just add
WaveOAuthMiddleware to your middleware. If you only want to require
authentication for specific handlers, decorate those with @waveoauth.
In any wave authenticated handler the request object sho... |
"""Extracts a single file from a CAB archive."""
import os
import shutil
import subprocess
import sys
import tempfile
def run_quiet(*args):
"""Run 'expand' supressing noisy output. Returns returncode from process."""
popen = subprocess.Popen(args, stdout=subprocess.PIPE)
out, _ = popen.communicate()
if popen.... |
import mock
import pytest
from waffle.testutils import override_switch
from osf import features
from api.base.settings.defaults import API_BASE
from osf_tests.factories import (
AuthUserFactory,
PreprintProviderFactory,
)
@pytest.fixture(params=['/{}preprint_providers/?version=2.2&', '/{}providers/preprints/?... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
import six
import os
try:
import unittest2 as unittest
except ImportError:
import unittest
from agate import csv_py3
from agate.exceptions import FieldSizeLimitError
@unittest.skipIf(six.PY2, "Not supported in Python 2.")
class TestReader(unittest.Te... |
import datetime
import pan.test
class TestModule(pan.test.TestCase):
def setup_method(self, method):
self.provider = pan.Provider("hsl")
self.month = datetime.datetime.today().month
def test_list_networks(self):
if not 5 <= self.month <= 10: return
networks = self.provider.li... |
import render
import rml2pdf
import rml2html as htmlizer
import rml2txt as txtizer
import odt2odt as odt
import html2html as html
import makohtml2html as makohtml
class rml(render.render):
def __init__(self, rml, localcontext = None, datas=None, path='.', title=None):
render.render.__init__(self, datas, p... |
import site
import logging
from six import StringIO
from azure.cli.core.util import CLIError
from azure.cli.core._config import az_config
import azure.cli.core.azlogging as azlogging
logger = azlogging.get_az_logger(__name__)
CLI_PACKAGE_NAME = 'azure-cli'
COMPONENT_PREFIX = 'azure-cli-'
def _deprecate_warning():
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.callback import CallbackBase
from ansible import constants as C
class CallbackModule(CallbackBase):
'''
This is the default callback interface, which simply prints messages
to stdout when new cal... |
"""Offline dump analyzer of TensorFlow Debugger (tfdbg)."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import sys
# Google-internal import(s).
from tensorflow.python.debug import debug_data
from tensorflow.python.debug.cli import analy... |
"""Tests for tensorflow.ops.stack_ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
from tensorflow.python.framework import errors
from tensorflow.python.framework import tensor_shape
from tensorflow.python.o... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from itertools import chain
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.module_utils._text import to_native, to_text
from ansible.module_utils.common._collections_compat import Mapping, ... |
import json
import tempfile
from preggy import expect
from thumbor import __version__
from thumbor.error_handlers.file import ErrorHandler
from thumbor.config import Config
from thumbor.context import ServerParameters
from tests.base import TestCase
class FakeRequest(object):
def __init__(self):
self.h... |
from django import template
from django.contrib.admin.utils import quote
from django.core.urlresolvers import Resolver404, get_script_prefix, resolve
from django.utils.http import urlencode
from django.utils.six.moves.urllib.parse import parse_qsl, urlparse, urlunparse
register = template.Library()
@register.filter
... |
"""(Extremely) low-level import machinery bits as used by importlib and imp."""
class __loader__(object):pass
def _fix_co_filename(*args,**kw):
raise NotImplementedError("%s:not implemented" % ('_imp.py:_fix_co_filename'))
def acquire_lock(*args,**kw):
"""acquire_lock() -> None Acquires the interpreter's... |
# mode: run
# tag: forin
import sys
import cython
try:
from builtins import next
except ImportError:
def next(it):
return it.next()
def for_in_pyiter_pass(it):
"""
>>> it = Iterable(5)
>>> for_in_pyiter_pass(it)
>>> next(it)
Traceback (most recent call last):
StopIteration
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.