content stringlengths 4 20k |
|---|
# -*- coding: utf-8 -*-
"""
***************************************************************************
RasterLayerStatistics.py
---------------------
Date : January 2013
Copyright : (C) 2013 by Victor Olaya
Email : volayaf at gmail dot com
****************... |
"""Class for parsing ASN.1"""
from compat import *
from codec import *
#Takes a byte array which has a DER TLV field at its head
class ASN1Parser:
def __init__(self, bytes):
p = Parser(bytes)
p.get(1) #skip Type
#Get Length
self.length = self._getASN1Length(p)
#Get Value
... |
"""
=========================
Multilabel classification
=========================
This example simulates a multi-label document classification problem. The
dataset is generated randomly based on the following process:
- pick the number of labels: n ~ Poisson(n_labels)
- n times, choose a class c: c ~ Multinom... |
from itertools import islice, repeat, izip, cycle
# If PEP 3102 is accepted, the signature would be
#def iterCombinations(*iterables, blocksize=1):
def iterCombinations(*iterables, **kwds):
'''Generates the combinations of the given iterables.
@returns: An iterator over all combinations of the C{iterables... |
from __future__ import absolute_import, division
import time
import os
try:
unicode
except NameError:
unicode = str
from . import LockBase, NotLocked, NotMyLock, LockTimeout, AlreadyLocked
class SQLiteLockFile(LockBase):
"Demonstrate SQL-based locking."
testdb = None
def __init__(self, path, ... |
from ducktape.mark import matrix, ignore
from ducktape.mark.resource import cluster
from kafkatest.services.zookeeper import ZookeeperService
from kafkatest.services.kafka import KafkaService
from kafkatest.services.verifiable_producer import VerifiableProducer
from kafkatest.services.console_consumer import ConsoleCo... |
from sympy.core import *
def test_rational():
a = Rational(1, 5)
assert a**Rational(1, 2) == a**Rational(1, 2)
assert 2 * a**Rational(1, 2) == 2 * a**Rational(1, 2)
assert a**Rational(3, 2) == a * a**Rational(1, 2)
assert 2 * a**Rational(3, 2) == 2*a * a**Rational(1, 2)
assert a**Rational(17... |
"""
Server-mode SFTP support.
"""
import os
import errno
from Crypto.Hash import MD5, SHA
from paramiko.common import *
from paramiko.server import SubsystemHandler
from paramiko.sftp import *
from paramiko.sftp_si import *
from paramiko.sftp_attr import *
# known hash algorithms for the "check-file" extension
_has... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import re
INCLUDE_PARSER = re.compile(r'^\s*include\s+"([^"]+)"\s*([\/\/|\#].*)*$')
def find_includes(basedirs, source, log=None):
"""Finds all thrift ... |
"""Tests for learn.dataframe.transforms.reader_source."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import tensorflow.contrib.learn.python.learn.dataframe.transforms.reader_source as rs
class ReaderSourceTestCase(tf.test.Tes... |
import urllib.request, urllib.parse, urllib.error
try:
import json as simplejson
except ImportError:
try:
import simplejson
except ImportError:
from django.utils import simplejson
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.test.client ... |
"""
This plugin installs a DEPRECATED error class for the :class:`DeprecatedTest`
exception. When :class:`DeprecatedTest` is raised, the exception will be logged
in the deprecated attribute of the result, ``D`` or ``DEPRECATED`` (verbose)
will be output, and the exception will not be counted as an error or failure.
It ... |
import dbus
import dbus.glib
import gobject
import sys
from glib import GError
import pygst
pygst.require("0.10")
import gst
import tpfarstream
import farstream
from util import *
import gc
from telepathy.client.channel import Channel
from telepathy.constants import (
CONNECTION_HANDLE_TYPE_NONE, CONNECTION_HAND... |
import traceback
from couchpotato.core.helpers.encoding import toUnicode, tryUrlencode
from couchpotato.core.logger import CPLog
from couchpotato.core.notifications.base import Notification
log = CPLog(__name__)
autoload = 'Toasty'
class Toasty(Notification):
urls = {
'api': 'http://api.supertoasty.c... |
from PIL import Image
from six.moves.urllib.parse import urlparse
from resizeimage import resizeimage
from .settings import DEFAULT_METHOD
def get_resize_arguments(**kwargs):
width = kwargs.get('w')
height = kwargs.get('h')
method = kwargs.get('t')
if not method:
if width:
metho... |
from datetime import datetime, tzinfo
import pytz
from django.template import Library, Node, TemplateSyntaxError
from django.utils import timezone
register = Library()
# HACK: datetime instances cannot be assigned new attributes. Define a subclass
# in order to define new attributes in do_timezone().
class datetim... |
import os
import socket
import sys
import threading
import time
import traceback
import urlparse
import uuid
from .base import (ExecutorException,
Protocol,
RefTestExecutor,
RefTestImplementation,
TestExecutor,
TestharnessEx... |
# This tests small int range for 32-bit machine
# Small ints are variable-length encoded in MicroPython, so first
# test that encoding works as expected.
print(0)
print(1)
print(-1)
# Value is split in 7-bit "subwords", and taking into account that all
# ints in Python are signed, there're 6 bits of magnitude. So, ar... |
# coding: utf-8
import sys
import logging
import math
from functools import partial
import OCC.TopoDS
import OCC.Display.SimpleGui
import aocutils.display.topology
import aocutils.display.backends
import aocxchange.step
import aocxchange.utils
from XcMath import utils
from point2d import point2d
fro... |
import gtk
from zim.gui.widgets import Dialog
class PropertiesDialog(Dialog):
def __init__(self, ui):
Dialog.__init__(self, ui, _('Properties'), help='Help:Properties') # T: Dialog title
label = gtk.Label()
label.set_markup('<b>' + _('Notebook Properties') + '</b>')
# T: Section in notebook dialog
label.s... |
from gerritclient.tests.utils import fake_account
def get_fake_group(name="fake-group", group_id=1, is_single_item=True):
"""Creates a fake group
Returns the serialized and parametrized representation of a dumped
Gerrit Code Review environment.
"""
fake_group = {
"id": "6a1e70e1a88782771... |
from taskflow import flow
from taskflow.types import graph as gr
class Flow(flow.Flow):
"""Linear flow pattern.
A linear (potentially nested) flow of *tasks/flows* that can be
applied in order as one unit and rolled back as one unit using
the reverse order that the *tasks/flows* have been applied in.... |
from openerp.osv import fields, osv
class hr_attendance_config_settings(osv.osv_memory):
_inherit = 'hr.config.settings'
_columns = {
'group_hr_attendance': fields.boolean('Track attendances for all employees',
implied_group='base.group_hr_attendance',
help="Allocates attendanc... |
# -*- coding: utf-8 -*-
"""
SerienJunkies-eXtended Browser
Copyright (C) 2009 mkaay <<EMAIL>>
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, either version 3 of the License, or
... |
"""Functions to provide simpler and prettier logging."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tens... |
def subjective_graph_nodes(nodes):
rv = []
for node in nodes:
print node.keys()
rv.append(dict(index=node[u'index'],
id=node[u'id'],
truth=node.get(u'truth', False),
self_cause_weird=node.get(u'self_cause_weird', '3'),
... |
import espressomd
from espressomd import assert_features, electrostatics
import numpy
assert_features(["ELECTROSTATICS", "MASS", "LENNARD_JONES"])
system = espressomd.System(box_l=[1.0, 1.0, 1.0])
system.seed = system.cell_system.get_state()['n_nodes'] * [1234]
numpy.random.seed(system.seed)
print("\n--->Setup syste... |
"""
==================
Prediction Latency
==================
This is an example showing the prediction latency of various scikit-learn
estimators.
The goal is to measure the latency one can expect when doing predictions
either in bulk or atomic (i.e. one by one) mode.
The plots represent the distribution of the pred... |
microcode = '''
def macroop PSLLW_MMX_MMX {
msll mmx, mmx, mmxm, size=2, ext=0
};
def macroop PSLLW_MMX_M {
ldfp ufp1, seg, sib, disp, dataSize=8
msll mmx, mmx, ufp1, size=2, ext=0
};
def macroop PSLLW_MMX_P {
rdip t7
ldfp ufp1, seg, riprel, disp, dataSize=8
msll mmx, mmx, ufp1, size=2, ext=0
... |
# -*- 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):
# Deleting field 'Rates.google_data'
db.delete_column('frespo_currencies_rates', 'google_data')
def ba... |
#!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... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
try:
import shade
HAS_SHADE = True
except ImportError:
HAS_SHADE = False
from distutils.version import StrictVersion
def _choose_id_value(module):
if module.params['uuid'... |
import time
from openerp.osv import osv
from openerp.report import report_sxw
from common_report_header import common_report_header
class general_ledger(report_sxw.rml_parse, common_report_header):
_name = 'report.account.general.ledger'
def set_context(self, objects, data, ids, report_type=None):
ne... |
from mms.arg_parser import ArgParser
from mms.log import get_logger
from mms.serving_frontend import ServingFrontend
from mms.client_sdk_generator import ClientSDKGenerator
logger = get_logger(__name__)
class MMS(object):
'''MXNet Model Serving
'''
def __init__(self, app_name='mms'):
# Initializ... |
"""
Unit tests for email feature flag in student dashboard. Additionally tests
that bulk email is always disabled for non-Mongo backed courses, regardless
of email feature flag, and that the view is conditionally available when
Course Auth is turned on.
"""
from django.test.utils import override_settings
from django.c... |
"""
41. Tests for select_related()
``select_related()`` follows all relationships and pre-caches any foreign key
values so that complex trees can be fetched in a single query. However, this
isn't always a good idea, so the ``depth`` argument control how many "levels"
the select-related behavior will traverse.
"""
fro... |
import re
from plone import api
from plone.app.layout.viewlets.common import ViewletBase
from plone.app.layout.navigation.root import getNavigationRoot
#from ftw.subsite.interfaces import ISubsite
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from ..behaviors import ISubSite
from ..utils impo... |
from paddle.trainer_config_helpers import *
settings(learning_rate=1e-4, batch_size=1000)
seq_in = data_layer(name='input', size=200)
labels = data_layer(name='labels', size=5000)
probs = data_layer(name='probs', size=10)
xe_label = data_layer(name='xe-label', size=10)
hidden = fc_layer(input=seq_in, size=4)
output... |
#!/usr/bin/env python
import os
import pygame
from pygame import surfarray
from pygame.locals import *
main_dir = os.path.split(os.path.abspath(__file__))[0]
def surfdemo_show(array_img, name):
"displays a surface, waits for user to continue"
screen = pygame.display.set_mode(array_img.shape[:2], 0, 32)
... |
"""
Unit tests for `dirichlet` module.
"""
import numpy as np
from scipy import special
from bayespy.nodes import Dirichlet
from bayespy.utils import utils
from bayespy.utils import random
from bayespy.utils.utils import TestCase
class TestDirichlet(TestCase):
"""
Unit tests for Dirichlet node
"""
... |
"""
Tests for views/tools.py.
"""
import datetime
import mock
import json
import unittest
from django.utils.timezone import utc
from django.test.utils import override_settings
from nose.plugins.attrib import attr
from courseware.field_overrides import OverrideFieldData # pylint: disable=import-error
from student.te... |
"""Test running bitcoind with the -rpcbind and -rpcallowip options."""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.netutil import *
class RPCBindTest(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.setup_... |
from __future__ import unicode_literals
import os
import time
from django.contrib.auth.models import User
from django.utils.datetime_safe import datetime
from django.core.files.storage import FileSystemStorage
from django.db import models
def user_project_directory_path(instance):
"""
File will be uploaded ... |
# Scan <Drag.h>, generating draggen.py.
import sys
from bgenlocations import TOOLBOXDIR, BGENDIR, INCLUDEDIR
sys.path.append(BGENDIR)
from scantools import Scanner
MISSING_DEFINES="""
kDragHasLeftSenderWindow = (1 << 0)
kDragInsideSenderApplication = (1 << 1)
kDragInsideSenderWindow = (1 << 2)
kDragReg... |
import os
import sys
import traceback
__all__ = ['IgnoreException', 'importall',]
DEBUG=0
if sys.platform == 'cli':
get_frame = None
else:
get_frame = sys._getframe
class IgnoreException(Exception):
"Ignoring this exception due to disabled feature"
def output_exception(printstream = sys.stdout):
tr... |
"""
Content negotiation deals with selecting an appropriate renderer given the
incoming request. Typically this will be based on the request's Accept header.
"""
from __future__ import unicode_literals
from django.http import Http404
from rest_framework import exceptions
from rest_framework.settings import api_setting... |
import unittest
import __builtin__
import exceptions
import warnings
from test.test_support import run_unittest, check_warnings
import os
import sys
from platform import system as platform_system
DEPRECATION_WARNINGS = ["BaseException.message has been deprecated"]
if sys.py3kwarning:
DEPRECATION_WARNINGS.extend(
... |
# pylint: disable=missing-docstring
# pylint: disable=redefined-outer-name
# pylint: disable=unused-argument
from lettuce import world, step
from nose.tools import assert_equal, assert_in
CSS_FOR_TAB_ELEMENT = "li[data-tab-id='{0}'] input.toggle-checkbox"
@step(u'I go to the pages page$')
def go_to_static(step):
... |
"""Tests for the pylint checker in :mod:`pylint.extensions.overlapping_exceptions
"""
from sys import version_info
from os.path import join, dirname
from pylint.extensions.overlapping_exceptions import OverlappingExceptionsChecker
import pytest
@pytest.fixture(scope='module')
def checker(checker):
return Overl... |
# TODO: Let pyinstaller take care of this
#os.chdir(hotspotter_root)
import os, sys
from hotspotter.helpers import check_path, ensure_path, vd, copy_all, copy
from os.path import join
import types
import textwrap
__HOME__ = os.path.expanduser("~")
__CODE__ = os.path.expanduser("~")+'/code'
hotspotter_r... |
"""Custom message type for SQS messages."""
import pickle
from boto.sqs import message
from kale import crypt
from kale import exceptions
from kale import settings
from kale import utils
_compressor = settings.COMPRESSOR
_decompressor = settings.DECOMPRESSOR
_task_size_limit = settings.SQS_TASK_SIZE_LIMIT
_get_curr... |
from configuration import Configuration
# GCC compiler-specific configuration
class GccConfiguration(Configuration):
def __init__(self, context):
Configuration.__init__(self, context)
# ------------------------------------------------------------
# Return test program to be used when checking for ... |
"""Unit tests for :class:`iris.fileformats.pp._LBProc`."""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
# Import iris.tests first so that some things can be initialised before
# importing anything else.
import iris.tests as tests
fr... |
import sys
import unittest
from mock import Mock
from libcloud.common.base import LibcloudConnection
from libcloud.common.openstack import OpenStackBaseConnection
class OpenStackBaseConnectionTest(unittest.TestCase):
def setUp(self):
self.timeout = 10
OpenStackBaseConnection.conn_class = Mock()
... |
"""
Wrapper for loading templates from "templates" directories in INSTALLED_APPS
packages.
"""
import os
import sys
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.template.base import TemplateDoesNotExist
from django.template.loader import BaseLoader
from django.u... |
"""
Middleware decorator for removing headers.
"""
from functools import wraps
from openedx.core.djangoapps.header_control import force_header_for_response, remove_headers_from_response
def remove_headers(*headers):
"""
Decorator that removes specific headers from the response.
Usage:
@remove_h... |
import itertools
import os
import re
from testrunner.local import testsuite
from testrunner.objects import testcase
FLAGS_PATTERN = re.compile(r"//\s+Flags:(.*)")
FILES_PATTERN = re.compile(r"//\s+Files:(.*)")
SELF_SCRIPT_PATTERN = re.compile(r"//\s+Env: TEST_FILE_NAME")
# TODO (machenbach): Share commonalities wit... |
class ModuleDocFragment(object):
# Azure doc fragment
DOCUMENTATION = '''
options:
tags:
description:
- >
Dictionary of string:string pairs to assign as metadata to the object.
Metadata tags on the object will be updated with any provided values. To remove ta... |
import time
import numpy
import unittest2 as unittest
from nupic.support.unittesthelpers.algorithm_test_helpers \
import CreateSP
from nupic.bindings.math import GetNTAReal
uintType = "uint32"
# set a single seed for running both implementations
SEED = int((time.time()%10000)*10)
def _computeOverlap(x, y):
"... |
import os
import yaml
CONFIG_FILE = 'settings.yaml'
class Config(object):
def __init__(self):
# get settings from settings.yaml
config_file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, CONFIG_FILE))
with open(config_file_path, 'r') as yml:
self.co... |
#! /usr/bin/env python
"""Compression/decompression utility using the Brotli algorithm."""
from __future__ import print_function
import argparse
import sys
import os
import platform
import brotli
# default values of encoder parameters
DEFAULT_PARAMS = {
'mode': brotli.MODE_GENERIC,
'quality': 11,
'lgwin'... |
__revision__ = "$Id: test_Acspy_Servants_ContainerServices.py,v 1.2 2010/06/08 01:55:25 agrimstrup Exp $"
#--REGULAR IMPORTS-------------------------------------------------------------
import sys
import unittest
import mock
import new
import CDB
#--ACS IMPORTS-----------------------------------------------------------... |
# pylint: disable=I0011,W0613,W0201,W0212,E1101,E1103
from __future__ import absolute_import, division, print_function
import pytest
import numpy as np
from glue.core import ComponentID, Data, Component, DataCollection
from .. import link_helpers as lh
from ..link_helpers import (LinkTwoWay, multi_link,
... |
from __future__ import unicode_literals
import frappe
from frappe.utils import flt, cstr, nowdate, nowtime
from erpnext.stock.utils import update_bin
from erpnext.stock.stock_ledger import update_entries_after
from erpnext.accounts.utils import get_fiscal_year
def repost(allow_negative_stock=False):
"""
Repost ever... |
"""
Paint smooth weights tool in Maya using the weights of neighbouring vertices.
Installation
============
* Extract the content of the .rar file anywhere on disk.
* Drag the skinningTools.mel file in Maya to permanently install the script.
Note
====
The paint tool calls a script that find the surrounding vertice... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
from tensorflow.python.framework import ops
from tensorflow.python.platform import test
from tensorflow.python.summary import plugin_asset
from tensorflow.python.summary.writer import writer
fro... |
from __future__ import unicode_literals
import frappe
from frappe.utils import flt, getdate
from frappe import _
from frappe.model.mapper import get_mapped_doc
from frappe.model.document import Document
from erpnext.hr.utils import set_employee_name
class Appraisal(Document):
def validate(self):
if not self.statu... |
from __future__ import absolute_import
import pytest
from yaclifw.framework import parsers
from scc.git import FilteredPullRequestsCommand
from scc.git import Merge
from scc.git import SetCommitStatus
from scc.git import TravisMerge
from scc.git import get_default_filters
from .Mock import MoxTestBase, MockTest
defaul... |
"""
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 ... |
"""convert OpenDocument (ODF) files to Gettext PO localization files"""
import cStringIO
import zipfile
import re
import lxml.etree as etree
from translate.storage import factory
from translate.storage.xml_extract import unit_tree
from translate.storage.xml_extract import extract
from translate.storage.xml_extract i... |
"""PipelineRunner, an abstract base runner object."""
from __future__ import absolute_import
import logging
import os
import shelve
import shutil
import tempfile
def _get_runner_map(runner_names, module_path):
"""Create a map of runner name in lower case to full import path to the
runner class.
"""
return {... |
"""Invenio utilities to perform a REST like authentication."""
try:
from uuid import uuid4
except ImportError:
import random
def uuid4():
"""Get a fake UUID4."""
return "%x" % random.getrandbits(16 * 8)
from functools import wraps
from flask import request, abort
def create_new_web_api_... |
from tools.docco.rl_doc_utils import *
from reportlab.lib.codecharts import SingleByteEncodingChart
from reportlab.platypus import Image
import reportlab
heading1("Fonts and encodings")
disc("""
This chapter covers fonts, encodings and Asian language capabilities.
If you are purely concerned with generating PDFs for ... |
from __future__ import unicode_literals
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.select import Select
from selenium.webdriver.support import expected... |
{
'name': 'Employee Directory',
'version': '1.1',
'author': 'OpenERP SA',
'category': 'Human Resources',
'sequence': 21,
'website': 'https://www.odoo.com',
'summary': 'Jobs, Departments, Employees Details',
'description': """
Human Resources Management
==========================
This ap... |
"""Wrappers for candidate sampling operations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import random_seed
from tensorflow.python.ops import array_ops # pylint: disable=unused-import
from tensorflow.python.ops imp... |
#!/usr/bin/env python
#
import sys, math, operator, json, ast
#
"""
Masses are correct for the 'free' aminoacids.
Protonated forms should have +1 in mass, but that is irrelevant.
All pKa's taken from Evers_2012_Langmuir_28_11843.
Except the pKa for O-phospho-L-serine (pSE), taken from Zachariou_1996_JPC_100_12680.
"""... |
"""
Verify the settings that cause a set of programs to be created in
a specific build directory, and that no intermediate built files
get created outside of that build directory hierarchy even when
referred to with deeply-nested ../../.. paths.
"""
import TestGyp
# TODO(mmoss): Make only supports (theoretically) a s... |
import os
import sys
import tempfile
import unittest
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PARENT_DIR = os.path.dirname(SCRIPT_DIR)
DATA_DIR = os.path.join(SCRIPT_DIR, 'data')
CHROME_SRC = os.path.dirname(os.path.dirname(os.path.dirname(PARENT_DIR)))
MOCK_DIR = os.path.join(CHROME_SRC, "third_party",... |
import atexit
import os
import socket
import subprocess
import time
import urllib2
class Server(object):
"""A running ChromeDriver server."""
def __init__(self, exe_path, log_path=None):
"""Starts the ChromeDriver server and waits for it to be ready.
Args:
exe_path: path to the ChromeDriver execut... |
# ---------------------------------------------------------------------
# JSON normalization routines
import copy
from collections import defaultdict
import numpy as np
from pandas._libs.lib import convert_json_to_lines
from pandas import compat, DataFrame
def _convert_to_line_delimits(s):
"""Helper function th... |
import datetime
import json
import validate_jsonp
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.syndication.views import Feed
from django.shortcuts import get_object_or_404
from django.utils.feedgenerator import (Atom1Feed, SyndicationFeed,
... |
"""report.py - Utilities for reporting statistics about benchmark results
"""
import os
import re
import copy
class BenchmarkColor(object):
def __init__(self, name, code):
self.name = name
self.code = code
def __repr__(self):
return '%s%r' % (self.__class__.__name__,
... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
try:
import boto.ec2
from boto.ec2.blockdevicemapping import BlockDeviceType, BlockDeviceMapping
HAS_BOTO=True
except ImportError:
HAS_BOTO=False
import json
def... |
import logging
import requests
from django.utils.cache import patch_response_headers
from django.shortcuts import render
from allauth.socialaccount.models import (SocialLogin,
SocialToken)
from allauth.socialaccount.helpers import complete_social_login
from allauth.socialacc... |
#!/usr/bin/env python
"""Original NetworkX graph tests"""
from nose.tools import *
import networkx
import networkx as nx
from historical_tests import HistoricalTests
class TestDiGraphHistorical(HistoricalTests):
def setUp(self):
HistoricalTests.setUp(self)
self.G=nx.DiGraph
def test_in_degr... |
from . import fixtures
from . import profiling
from .. import util
import types
from collections import deque
import contextlib
from . import config
from sqlalchemy import MetaData
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
class ReplayFixtureTest(fixtures.TestBase):
@contextlib.cont... |
from ConfigParser import ConfigParser
from optparse import OptionParser
import marvin
from marvin import configGenerator
from marvin import sshClient
from time import sleep as delay
import telnetlib
import socket
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("-c", "--config", action="sto... |
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
pipe2py.modules.pipefilter
~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides methods for filtering (including or excluding) items from a feed.
http://pipes.yahoo.com/pipes/docs?doc=operators#Filter
"""
import re
from datetime import datetime as dt
from decima... |
'''OpenGL extension ARB.tessellation_shader
This module customises the behaviour of the
OpenGL.raw.GL.ARB.tessellation_shader to provide a more
Python-friendly API
Overview (from the spec)
This extension introduces new tessellation stages and two new shader types
to the OpenGL primitive processing pipeline. Th... |
from django.utils.translation import ugettext_lazy as _ # noqa
import horizon
from openstack_dashboard.dashboards.project import dashboard
class NetworkTopology(horizon.Panel):
name = _("Network Topology")
slug = 'network_topology'
permissions = ('openstack.services.network', )
dashboard.Project.regi... |
from __future__ import division
import numpy as np
from .mesh import MeshVisual
from ..geometry import MeshData
class SurfacePlotVisual(MeshVisual):
"""Displays a surface plot on a regular x,y grid
Parameters
----------
x : ndarray | None
1D array of values specifying the x positions of ver... |
from twisted.internet.defer import inlineCallbacks
from Tribler.Core.CacheDB.SqliteCacheDBHandler import VoteCastDBHandler, ChannelCastDBHandler
from Tribler.Test.Core.test_sqlitecachedbhandler import AbstractDB
class TestVotecastDBHandler(AbstractDB):
@inlineCallbacks
def setUp(self):
yield super(T... |
import sys
from TranslationDataRC import *
def UpdatePO(filename):
translationDataOld = TranslationDataRC()
translationDataOld.loadFromPO('PO\\' + filename, 'po')
translationData = TranslationDataRC()
translationData.loadFromPO(r'PO\mpc-hc', 'pot')
translationData.translate(translationDataOld)
... |
from django.core.exceptions import ValidationError
from django.core.validators import EMPTY_VALUES
from django.test.utils import get_warnings_state, restore_warnings_state
from django.utils.unittest import TestCase
class LocalFlavorTestCase(TestCase):
# NOTE: These are copied from the TestCase Django uses for tes... |
__revision__ = "$Id$"
## import interesting modules:
from invenio.config import \
CFG_ACCESS_CONTROL_LEVEL_SITE, \
CFG_SITE_LANG, \
CFG_SITE_NAME, \
CFG_SITE_SECURE_URL
from invenio.legacy.dbquery import run_sql, Error
from invenio.modules.access.engine import acc_authorize_action
from invenio.mod... |
import itertools
import numpy as np
import sys
import six
from six import BytesIO, StringIO, string_types as py_string
PY26 = sys.version_info[0] == 2 and sys.version_info[1] == 6
PY3 = (sys.version_info[0] >= 3)
PY2 = sys.version_info[0] == 2
if PY26:
import unittest2 as unittest
else:
import unittest
i... |
from datetime import date, timedelta
from django.contrib import admin
from django.utils.formats import localize
from django.utils.html import format_html
from members.models import CorporateMember, DeveloperMember, Invoice
@admin.register(DeveloperMember)
class DeveloperMemberAdmin(admin.ModelAdmin):
list_displ... |
import datetime
import json
import mongoengine as me
import requests
import course
import rmc.shared.secrets as s
import section
from rmc.shared import util
class BaseCourseAlert(me.Document):
"""An abstract base class for notifying when a seat opens in a course.
Subclasses must define the behaviour for se... |
"""
Verifies that bundles that have no 'sources' (pure resource containers) work.
"""
import TestGyp
import sys
if sys.platform == 'darwin':
test = TestGyp.TestGyp(formats=['ninja', 'make', 'xcode'])
test.run_gyp('test.gyp', chdir='sourceless-module')
# Just needs to build without errors.
test.build('test.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.