content string |
|---|
"""
Tests for the IBM FlashSystem iSCSI volume driver.
"""
import mock
import six
import random
from cinder import context
from cinder import exception
from cinder import test
from cinder.tests.unit import test_ibm_flashsystem as fscommon
from cinder import utils
from cinder.volume import configuration as conf
from ... |
class Inlet(object):
def __init__(self):
self._handle = None
return
def impose(self):
import Snac.pyre.Exchanger as Exchanger
Exchanger.Inlet_impose(self._handle)
return
def recv(self):
import Snac.pyre.Exchanger as Exchanger
Exchanger.Inlet_recv(... |
from django.contrib.gis.db import models
from django.contrib.gis.tests.utils import mysql, spatialite
from django.utils.encoding import python_2_unicode_compatible
# MySQL spatial indices can't handle NULL geometries.
null_flag = not mysql
@python_2_unicode_compatible
class Country(models.Model):
name = models.Ch... |
import os
import os.path
import numpy
from numpy.distutils.misc_util import Configuration
from sklearn._build_utils import get_blas_info
def configuration(parent_package="", top_path=None):
config = Configuration("metrics", parent_package, top_path)
cblas_libs, blas_info = get_blas_info()
if os.name ==... |
'''
Allison Lewko, Amit Sahai and Brent Waters (Pairing-based)
| From: "Revocation Systems with Very Small Private Keys"
| Published in: IEEE S&P 2010
| Available from: http://eprint.iacr.org/2008/309.pdf
| Notes: fully secure IBE Construction with revocable keys.
* type: identity-based encryption (public ... |
#!python
"""Bootstrap setuptools installation
If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::
from ez_setup import use_setuptools
use_setuptools()
If you want to require a specific version of setuptools... |
#!/usr/bin/env python
# coding=utf8
caOpensslConf = '''
#http://www.phildev.net/ssl/opensslconf.html
[ ca ]
default_ca = CA_default
[CA_default]
caroot = %(caroot)s
certs = $caroot/certsdb
new_certs_dir = $certs
database = $caroot/index.txt
certificate = $caroot/%(cn)s.cer
private_key = $caro... |
import time
import datetime
import sqlite3
conn = sqlite3.connect('diary.db')
c = conn.cursor()
c.execute('''CREATE TABLE executive (unid INTEGER PRIMARY KEY,name text,designation text, abs text)''')
no_of_exec = input() #enter the total number of executives
while(no_of_exec):
no_of_exec = no... |
from tests.compat import OrderedDict
from tests.unit import unittest
from tests.unit import AWSMockServiceTestCase
from boto.vpc import VPCConnection, Subnet
class TestDescribeSubnets(AWSMockServiceTestCase):
connection_class = VPCConnection
def default_body(self):
return b"""
<Describe... |
#!/usr/bin/env python
import jumeg
import os.path
raw_fname = "109925_CAU01A_100715_0842_2_c,rfDC-raw.fif"
if not os.path.isfile(raw_fname):
print("Please find the test file at the below location on the meg_store2 network drive - \
cp /data/meg_store2/fif_data/jumeg_test_data/109925_CAU01A_100715_0842_... |
import logging
import sys
class StdHandler(object):
indent = 0
def __init__(self, oldStream, logger):
self.oldStream = oldStream
self.encoding = oldStream.encoding
self.buf = ""
self.logger = logger
# the following is a workaround for colorama (0.3.6),
# which ... |
# -*- coding: utf-8 -*-
r'''
werkzeug.script
~~~~~~~~~~~~~~~
.. admonition:: Deprecated Functionality
``werkzeug.script`` is deprecated without replacement functionality.
Python's command line support improved greatly with :mod:`argparse`
and a bunch of alternative modules.
Most ... |
#!/usr/bin/env python3
import lief
import sys
import termcolor as tc
def get_typeval_as_str(lief_type):
return str(lief_type).split('.')[1]
def show_name(binary):
print(tc.colored("[::] Name", "blue"))
print(binary.name)
def enum_header(header):
def get_ident_props():
identity = "\n{0:18... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import yaml
from stat import *
try:
from __main__ import display
except ImportError:
from ansible.utils.display import Display
display = Display()
class GalaxyToken(object):
''' Class to storing and ret... |
"""The tests for the folder_watcher component."""
import os
from homeassistant.components import folder_watcher
from homeassistant.setup import async_setup_component
from tests.async_mock import Mock, patch
async def test_invalid_path_setup(hass):
"""Test that an invalid path is not set up."""
assert not aw... |
"""
The POX Messenger system.
The Messenger system is a way to build services in POX that can be
consumed by external clients.
Sometimes a controller might need to interact with the outside world.
Sometimes you need to integrate with an existing piece of software and
maybe you don't get to choose how you communica... |
import os
import time
import numpy
import functools
import sys
import codecs
import types
import gdal
import osr
from invest_natcap import raster_utils
GLOBAL_UPPER_LEFT_ROW = 2602195.7925872812047601
GLOBAL_UPPER_LEFT_COL = -11429693.3490753173828125
def average_layers():
base_table_uri = "C:/Users/rich/Desk... |
# coding=utf-8
from PyMimircache.cache.lru import LRU
from PyMimircache.cache.abstractCache import Cache
class SLRU(Cache):
def __init__(self, cache_size=1000, ratio=1, **kwargs):
"""
:param cache_size: size of cache
:param args: raio: the ratio of protected/probationary
:return:
... |
import numpy as np
from sklearn.svm import SVC
from sklearn.model_selection import KFold
from sklearn.metrics import accuracy_score
def svm_backward(X, y, n_selected_features):
"""
This function implements the backward feature selection algorithm based on SVM
Input
-----
X: {numpy arr... |
#!/usr/local/fbcode/gcc-4.8.1-glibc-2.17-fb/bin/python2.7
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import commands
import subprocess
import sys
import re
import os
import time
#
# Simple logger... |
"""Utility functions."""
import sys
import os
import base64
import json
import hashlib
try:
from collections import OrderedDict
except ImportError:
OrderedDict = dict
__all__ = ['urlsafe_b64encode', 'urlsafe_b64decode', 'utf8',
'to_json', 'from_json', 'matches_requirement']
def urlsafe_b64encode(d... |
# This module is designed to handle all multi-threading processes in
# Gourmet. Separate threads are limited to doing the following things
# with respect to the GUI:
#
# 1. Start a notification dialog with a progress bar
# 2. Update the progress bar
# 3. Finish successfully
# 4. Stop with an error.
#
# If you n... |
# Luhn algorithm check
# From https://en.wikipedia.org/wiki/Luhn_algorithm
def luhn_checksum(card_number):
def digits_of(n):
return [int(d) for d in str(n)]
digits = digits_of(card_number)
odd_digits = digits[-1::-2]
even_digits = digits[-2::-2]
checksum = 0
checksum += sum(odd_digits)
... |
import time
from importlib import import_module
from django.conf import settings
from django.utils.cache import patch_vary_headers
from django.utils.http import cookie_date
class SessionMiddleware(object):
def __init__(self):
engine = import_module(settings.SESSION_ENGINE)
self.SessionStore = eng... |
tailbone_CORS = True
tailbone_CORS_RESTRICTED_DOMAINS = ["http://localhost"]
## modify the below functions to change how users are identified
# tailbone_is_current_user_admin =
# tailbone_get_current_user =
# tailbone_create_login_url =
# tailbone_create_logout_url =
## Use cloud store instead of blobstore
# tailbone... |
#!/usr/bin/env python
from __future__ import unicode_literals
# Allow direct execution
import os
import sys
import unittest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from test.helper import FakeYDL
from youtube_dl.extractor.common import InfoExtractor
from youtube_dl.extractor i... |
"""
Make sure overwriting read-only files works as expected (via win-tool).
"""
import TestGyp
import filecmp
import os
import stat
import sys
if sys.platform == 'win32':
test = TestGyp.TestGyp(formats=['ninja'])
# First, create the source files.
os.makedirs('subdir')
read_only_files = ['read-only-file', 's... |
from math import log
from ._registry import register
from vectorizer_output import VectorizerOutput
from .bag_of_words import _count_words_in_docs
def _count_document_occurences(doc_counts, total_words):
return {word_id: sum(1 for doc in doc_counts.values() if word_id in doc)
for word_id in range(tota... |
import os
from oslo_concurrency import processutils
from oslo_log import log as logging
from oslo_utils import excutils
from nova.i18n import _LE
from nova.virt.libvirt import utils
LOG = logging.getLogger(__name__)
_dmcrypt_suffix = '-dmcrypt'
def volume_name(base):
"""Returns the suffixed dmcrypt volume na... |
import time
import pytest
import numpy as np
from lucid.misc.io.saving import save, CaptureSaveContext, batch_save
from lucid.misc.io.loading import load
from lucid.misc.io.scoping import io_scope, current_io_scopes
from concurrent.futures import ThreadPoolExecutor
import os.path
import io
import tensorflow as tf
dic... |
class Interface(object):
def __init__(self):
self.functions = []
def Func(self, name, return_type):
f = Function(self, len(self.functions), name, return_type)
self.functions.append(f)
return f
def Finalize(self):
for f in self.functions:
f.Finalize()
class Function(object):
def __in... |
import os
from mercurial import ui, hg, hook, error, encoding, templater, util, repoview
from mercurial.templatefilters import websub
from mercurial.i18n import _
from common import get_stat, ErrorResponse, permhooks, caching
from common import HTTP_OK, HTTP_NOT_MODIFIED, HTTP_BAD_REQUEST
from common import HTTP_NOT_FO... |
import asyncio
import io
import re
import sys
# The display classes deal with output from subprocesses. The FancyDisplay
# gives a multi-line, real-time view of each running process that looks nice in
# the terminal. The VerboseDisplay collects output from each job and prints it
# all when the job is finished, in a wa... |
from feature_extraction.post_processing.regex.regex_lib import RegexLib
import re
import datetime
import time
import unicodedata
from util.log import Log
import math
class EntityExtraction:
regex_bin = None
one_month = 86400 * 30 # unix time for 1 month
month_dict = {
'janvier': 1,
'fevri... |
"""
Main program for 2to3.
"""
from __future__ import with_statement
import sys
import os
import difflib
import logging
import shutil
import optparse
from . import refactor
def diff_texts(a, b, filename):
"""Return a unified diff of two strings."""
a = a.splitlines()
b = b.splitlines()
return diffl... |
"""Internal functions for working with frame-filters."""
import gdb
from gdb.FrameIterator import FrameIterator
from gdb.FrameDecorator import FrameDecorator
import itertools
import collections
def get_priority(filter_item):
""" Internal worker function to return the frame-filter's priority
from a frame filte... |
import os
import re
from flask import Flask
from datetime import timedelta
def interval_to_timedelta(interval):
if isinstance(interval, int):
interval = "%ds" % interval
ratios = {
's': 'seconds',
'm': 'minutes',
'h': 'hours',
'd': 'days',
'w': 'weeks'
}
... |
"""Tests for self-paced course due date overrides."""
# pylint: disable=missing-docstring
import datetime
import pytz
from django.test.utils import override_settings
from mock import patch
from courseware.tests.factories import BetaTesterFactory
from courseware.access import has_access
from lms.djangoapps.ccx.tests.t... |
import sys, unittest, re, os.path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', 'src'))
from tempfile import NamedTemporaryFile
import Exscript.util.interact
from Exscript.util.interact import InputHistory
class InputHistoryTest(unittest.TestCase):
CORRELATE = InputHistory
def ... |
import httplib
import json
import os
import socket
import zlib
from cinder.openstack.common import log as logging
from swiftclient import client as swift
LOG = logging.getLogger(__name__)
class FakeSwiftClient(object):
"""Logs calls instead of executing."""
def __init__(self, *args, **kwargs):
pass
... |
#!/usr/bin/env python
"""
HTML Tidy Extension for Python-Markdown
=======================================
Runs [HTML Tidy][] on the output of Python-Markdown using the [uTidylib][]
Python wrapper. Both libtidy and uTidylib must be installed on your system.
Note than any Tidy [options][] can be passed in as extensio... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase
from ansible.module_utils.urls import open_url, ConnectionError, SSLValidationError
from ansible.module_utils._text import to_native... |
from .mbcharsetprober import MultiByteCharSetProber
from .codingstatemachine import CodingStateMachine
from .chardistribution import EUCKRDistributionAnalysis
from .mbcssm import EUCKRSMModel
class EUCKRProber(MultiByteCharSetProber):
def __init__(self):
MultiByteCharSetProber.__init__(self)
self.... |
import binascii
import obfsproxy.common.rand as rand
def int_to_bytes(lvalue, width):
fmt = '%%.%dx' % (2*width)
return binascii.unhexlify(fmt % (lvalue & ((1L<<8*width)-1)))
class UniformDH:
"""
This is a class that implements a DH handshake that uses public
keys that are indistinguishable from ... |
from datetime import date
from django.conf import settings
from django.utils.http import int_to_base36, base36_to_int
from django.utils.crypto import constant_time_compare, salted_hmac
from django.utils import six
class PasswordResetTokenGenerator(object):
"""
Strategy object used to generate and check tokens... |
import time
from requests import request, ConnectionError
from ..utils import SSLHttpAdapter, module_member, parse_qs, user_agent
from ..exceptions import AuthFailed
class BaseAuth(object):
"""A authentication backend that authenticates the user based on
the provider response"""
name = '' # provider na... |
"""Wrapper to the POSIX crypt library call and associated functionality."""
import _crypt
import string as _string
from random import SystemRandom as _SystemRandom
from collections import namedtuple as _namedtuple
_saltchars = _string.ascii_letters + _string.digits + './'
_sr = _SystemRandom()
class _Method(_named... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import sys
from setuptools.command.test import test as TestCommand
class Tox(TestCommand):
user_options = [('tox-args=', 'a', 'Arguments to pass to tox')]
def initial... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import pytest
from ansible.module_utils.common.parameters import list_no_log_values
@pytest.fixture
def params():
return {
'secret': 'undercookwovennativity',
'other_secret': 'cautious-slate-makeshift',
... |
#!/usr/bin/env python
# encoding: utf-8
from .request import ICAPRequestFactory
from .response import ICAPResponseFactory
from .header import ICAPResponseHeaderFactory
class ICAPParser (object):
ICAPResponseHeaderFactory = ICAPResponseHeaderFactory
ICAPRequestFactory = ICAPRequestFactory
ICAPResponseFactory = ICAPR... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
import json
# COMMON CODE FOR MIGRATION
import re
from ansible.module_utils.basic import get_exception
from ansible.module_utils.netcfg import NetworkConfig, ConfigLine
from ansible.modul... |
"""Utilities for sampling techniques"""
# License: BSD Style.
import numpy as np
from ..utils import check_random_state
from math import ceil
class SplitSampling(object):
""" Random Split Sampling the dataset into two sets.
Parameters
----------
n : int
Total number of elements in the datas... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_urlparse
from ..utils import (
determine_ext,
dict_get,
ExtractorError,
float_or_none,
int_or_none,
remove_end,
try_get,
xpath_text,
)
from .periscope import PeriscopeIE
class Twi... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.cloudstack imp... |
from openerp.osv import fields, osv
class account_move_line_unreconcile_select(osv.osv_memory):
_name = "account.move.line.unreconcile.select"
_description = "Unreconciliation"
_columns ={
'account_id': fields.many2one('account.account','Account',required=True),
}
def action_open_window(self... |
class InspectorConsole(object):
def __init__(self, inspector_backend):
self._inspector_backend = inspector_backend
self._inspector_backend.RegisterDomain(
'Console',
self._OnNotification,
self._OnClose)
self._message_output_stream = None
self._last_message = None
self._cons... |
"""Helper script to perform actions as a super-user on ChromeOS.
Needs to be run with superuser privileges, typically using the
suid_python binary.
Usage:
sudo python suid_actions.py --action=CleanFlimflamDirs
"""
import optparse
import os
import shutil
import subprocess
import sys
import time
sys.path.append('/u... |
import boilerplate
import unittest
import StringIO
import os
import sys
class TestBoilerplate(unittest.TestCase):
"""
Note: run this test from the hack/boilerplate directory.
$ python -m unittest boilerplate_test
"""
def test_boilerplate(self):
os.chdir("test/")
class Args(object):
def __ini... |
import datetime
import re
import requests
from sentry_sdk import capture_exception
from django.conf import settings
from django.utils.timezone import make_aware, utc
def get_articles_data(count=8):
payload = {
'consumer_key': settings.POCKET_CONSUMER_KEY,
'access_token': settings.POCKET_ACCESS_T... |
"""Utilities for writing unit tests that involve course embargos. """
import contextlib
import mock
from django.core.cache import cache
from django.urls import reverse
import pygeoip
from .models import Country, CountryAccessRule, RestrictedCourse
@contextlib.contextmanager
def restrict_course(course_key, access_p... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'SoftwareSecurePhotoVerification.window'
db.add_column('verify_student_softwaresecurephotover... |
import numpy as np
import statsmodels.api as sm
from numpy.testing import dec
from statsmodels.graphics.regressionplots import (plot_fit, plot_ccpr,
plot_partregress, plot_regress_exog, abline_plot,
plot_partregress_grid, plot_ccpr_grid, add_lowess,
plot_added_vari... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import re
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six... |
import types
import unittest
import mozlog
from mozdevice import devicemanager
from mozdevice import devicemanagerSUT
ip = ''
port = 0
heartbeat_port = 0
log_level = mozlog.ERROR
class DeviceManagerTestCase(unittest.TestCase):
"""DeviceManager tests should subclass this.
"""
"""Set to False in your der... |
"""
Epytext (and general Python docstring) wrapper
==============================================
Utility for wrapping docstrings in Python; specifically, docstrings in U{Epytext
<http://epydoc.sourceforge.net/manual-epytext.html>} format, or those that are
close enough.
The wrapping herein generally adheres to all t... |
import unittest
from airflow.contrib.operators.dataflow_operator import \
DataFlowPythonOperator, DataFlowJavaOperator, \
DataflowTemplateOperator, GoogleCloudBucketHelper
from airflow.version import version
from tests.compat import mock
TASK_ID = 'test-dataflow-operator'
JOB_NAME = 'test-dataflow-pipeline'... |
import datetime
from yatt import BASE_CURRENCY
from yatt.ticker import aapl, agg, amzn, goog, msft, spy, eurusd, eurgbp, eurchf
from yatt.ticker import Ticker, Stock, Index, Future, Fx
from yatt.ticker import Tickers
timestamp = datetime.datetime(2000, 0o1, 0o1)
def test_ticker():
ticker = Ticker(symbol='AAPL',... |
from werkzeug import exceptions as ex
import simplejson as json
import flask
import wtforms_me
import wtforms.fields
import model.commit
import config
"""api used for submitting commits"""
blueprint = flask.Blueprint("commits", __name__, url_prefix="/commit")
MatchForm = wtforms_me.model_form(model.commit.MatchComm... |
#!/usr/bin/env python
import speech_recognition as sr
import sys
import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
import subprocess
import s... |
"""
Unit tests for Ecommerce feature flag in new instructor dashboard.
"""
from django.test.utils import override_settings
from django.core.urlresolvers import reverse
from courseware.tests.tests import TEST_DATA_MONGO_MODULESTORE
from student.tests.factories import AdminFactory
from xmodule.modulestore.tests.django_... |
import logging
from collections import defaultdict
from django.core.management.base import BaseCommand, CommandError
from treeherder.autoclassify import matchers
from treeherder.model.models import FailureLine, Matcher, FailureMatch
logger = logging.getLogger(__name__)
# The minimum goodness of match we need to mar... |
import os
_next_file_id = 0
class FileHandle(object):
def __init__(self, temp_file=None, absolute_path=None):
"""Constructs a FileHandle object.
This constructor should not be used by the user; rather it is preferred to
use the module-level GetAbsPath and FromTempFile functions.
Args:
temp... |
import logging
import pkgutil
from collections import OrderedDict
from functools import lru_cache
from socket import AF_INET, AF_INET6
import requests
import requests.packages.urllib3.util.connection as urllib3_connection
from requests.packages.urllib3.util.connection import allowed_gai_family
from streamlink import ... |
"""Test longpolling with getblocktemplate."""
from test_framework.test_framework import StatusquoTestFramework
from test_framework.util import *
import threading
class LongpollThread(threading.Thread):
def __init__(self, node):
threading.Thread.__init__(self)
# query current longpollid
te... |
from django.db.utils import OperationalError
from django.contrib.contenttypes.models import ContentType
PLUGIN_NAME = 'Carousel'
DESCRIPTION = 'This is a homepage element that renders a carousel.'
AUTHOR = 'Martin Paul Eve'
def install():
import core.models as core_models
import journal.models as journal_mod... |
"""View to accept incoming websocket connection."""
from __future__ import annotations
import asyncio
from collections.abc import Callable
from contextlib import suppress
import datetime as dt
import logging
from typing import Any, Final
from aiohttp import WSMsgType, web
import async_timeout
from homeassistant.comp... |
from os import path
from SCons.Builder import Builder
def scons_env(env, add=''):
opath = path.dirname(path.abspath('$TARGET'))
lstr = 'thrift --gen cpp -o ' + opath + ' ' + add + ' $SOURCE'
cppbuild = Builder(action=lstr)
env.Append(BUILDERS={'ThriftCpp': cppbuild})
def gen_cpp(env, dir, file):
scons_env... |
"""curses.wrapper
Contains one function, wrapper(), which runs another function which
should be the rest of your curses-based application. If the
application raises an exception, wrapper() will restore the terminal
to a sane state so you can read the resulting traceback.
"""
import sys, curses
def wrapper(func, *a... |
import Queue
import copy
import interface
import random
import statistics
import sys
import threading
# call the interface
################################################################################
def utility(counts_v, data, bin_options):
"""Call the binning library."""
events = len(counts_v)
... |
"""distutils.bcppcompiler
Contains BorlandCCompiler, an implementation of the abstract CCompiler class
for the Borland C++ compiler.
"""
# This implementation by Lyle Johnson, based on the original msvccompiler.py
# module and using the directions originally published by Gordon Williams.
# XXX looks like there's a L... |
"""
Tests for wiki views.
"""
from django.conf import settings
from django.test.client import RequestFactory
from courseware.tabs import get_course_tab_list
from student.tests.factories import AdminFactory, UserFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tes... |
#!/bin/env python
#encoding:utf-8
from pymongo import MongoClient
import datetime
# Settings
mongopath = "localhost" # 数据库地址
startDate = "20150104" # 检索数据开始日期
endDate = "20150529" # 检索数据结束日期
#endDate = "20150227" # 检索数据结束日期(三个月预留)
nowDate = datetime.datetime.now().strftime("%Y%m%d") # 当前日期
# Functions
def isN... |
from selenium import selenium
import unittest
import time
class TestPrompts(unittest.TestCase):
def setUp(self):
self.selenium = selenium("localhost", \
4444, "*firefoxproxy", "http://www.w3schools.com")
self.selenium.start()
def test_alert(self):
sel = self.selenium
... |
"""Tools for helping with testing capa."""
import gettext
import os
import os.path
import fs.osfs
from capa.capa_problem import LoncapaProblem, LoncapaSystem
from mock import Mock, MagicMock
import xml.sax.saxutils as saxutils
TEST_DIR = os.path.dirname(os.path.realpath(__file__))
def tst_render_template(templat... |
# -*- coding: utf-8 -*-
"""
Parse, stream, create, sign and verify Bitcoin transactions as Tx structures.
The MIT License (MIT)
Copyright (c) 2015 by Richard Kiss
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to dea... |
"""Affinity Propagation clustering algorithm."""
# Gael Varoquaux <EMAIL>
# License: BSD 3 clause
import numpy as np
from ..base import BaseEstimator, ClusterMixin
from ..utils import as_float_array, check_array
from ..utils.validation import check_is_fitted
from ..metrics import euclidean_distances
from ..m... |
"""Support classes and functions for testing the cmdlib module.
"""
from cmdlib.testsupport.cmdlib_testcase import CmdlibTestCase, \
withLockedLU
from cmdlib.testsupport.config_mock import ConfigMock
from cmdlib.testsupport.iallocator_mock import patchIAllocator
from cmdlib.testsupport.utils_mock import patchUtils
... |
"""
Middleware to check for obedience to the WSGI specification.
Some of the things this checks:
* Signature of the application and start_response (including that
keyword arguments are not used).
* Environment checks:
- Environment is a dictionary (and not a subclass).
- That all the required keys are in the... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Invoice.is_valid'
db.add_column('shoppingcart_invoice', 'is_valid',
se... |
#from django.db.models import Model, TextField
#from djangotoolbox.fields import ListField, EmbeddedModelField, DictField
from django.contrib.auth.models import User
from django.db import connections
from bson.objectid import ObjectId
from pymongo.errors import InvalidId
import csv, re, json, datetime, random
from col... |
#!/usr/bin/env python
"""
This script is used to run tests, create a coverage report and output the
statistics at the end of the tox run.
To run this script just execute ``tox``
"""
import re
from fabric.api import local, warn
from fabric.colors import green, red
if __name__ == '__main__':
local('flake8 --ignore... |
# -*- coding: utf-8 -*-
# -*- Channel Blog de Pelis -*-
# -*- Created for Alfa-addon -*-
# -*- By the Alfa Develop Group -*-
from builtins import range
import sys
PY3 = False
if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int
import re
from channelselector import get_thumb
fr... |
#!/usr/bin/env python3
from setuptools import setup, find_packages
import alot
setup(
name='alot',
version=alot.__version__,
description=alot.__description__,
author=alot.__author__,
author_email=alot.__author_email__,
url=alot.__url__,
license=alot.__copyright__,
classifiers=[
... |
"""Tests for third_party.tensorflow.contrib.ffmpeg.encode_audio_op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
import tensorflow as tf
from tensorflow.contrib import ffmpeg
from tensorflow.python.platform import resource_loader
cl... |
"""y not?"""
import os
import argv
argv.add_options([
('delete', 'delete python compiled files as well', False),
('wipe', 'remove known garbage', False),
('stat', 'run svn stat', False),
('tags', 'refresh the tags file', True),
('verbose', 'run ptags verbosely', False),
])
from ls import ly
fr... |
# -*- coding: utf-8 -*-
from django.http import HttpRequest
from django.template import (
Context, Engine, RequestContext, Template, Variable, VariableDoesNotExist,
)
from django.template.context import RenderContext
from django.test import RequestFactory, SimpleTestCase
class ContextTests(SimpleTestCase):
... |
from django.core.mail import send_mail
def send_email_to_all_because_project_icon_was_marked_as_wrong(project__pk, project__name, project_icon_url):
# links you to the project page
# links you to the secret, wrong project icon
# TODO:figure out if we should be worried about project icons getting deleted
... |
data = (
'You ', # 0x00
'Yang ', # 0x01
'Lu ', # 0x02
'Si ', # 0x03
'Jie ', # 0x04
'Ying ', # 0x05
'Du ', # 0x06
'Wang ', # 0x07
'Hui ', # 0x08
'Xie ', # 0x09
'Pan ', # 0x0a
'Shen ', # 0x0b
'Biao ', # 0x0c
'Chan ', # 0x0d
'Mo ', # 0x0e
'Liu ', # 0x0f
'Jian ', # 0x10
'P... |
from datetime import timedelta
import pytz
from openerp import models, fields, api, _
from openerp.exceptions import AccessError, Warning
class event_type(models.Model):
""" Event Type """
_name = 'event.type'
_description = 'Event Type'
name = fields.Char(string='Event Type', required=True)
def... |
"""
Created on Jan 30, 2011
@author: Mark V Systems Limited
(c) Copyright 2011 Mark V Systems Limited, All rights reserved.
"""
import sys
import os
import datetime
from distutils.command.build_py import build_py as _build_py
def get_version():
"""
Utility function to return the current version of the librar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.