content stringlengths 4 20k |
|---|
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import os.path
import TestSCons
test = TestSCons.TestSCons()
test.subdir('repository', ['repository', 'subdir'], 'work')
repository_aaa_in = test.workpath('repository', 'aaa.in')
repository_aaa_mid = test.workpath('repository', 'aaa.mid')
repository_aaa... |
from migrate.changeset.constraint import ForeignKeyConstraint
from sqlalchemy import MetaData, Table
def upgrade(migrate_engine):
"""Add missing foreign key constraint on pci_devices.compute_node_id."""
meta = MetaData(bind=migrate_engine)
pci_devices = Table('pci_devices', meta, autoload=True)
compu... |
from django.contrib.gis.geos import prototypes as capi
from django.contrib.gis.geos.coordseq import GEOSCoordSeq
from django.contrib.gis.geos.error import GEOSException
from django.contrib.gis.geos.geometry import (
GEOSGeometry, ProjectInterpolateMixin,
)
from django.contrib.gis.geos.point import Point
from django... |
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.mininode import CTransaction, NetworkThread
from test_framework.blocktools import create_coinbase, create_block, add_witness_commitment
from test_framework.script import CScript
from io import BytesIO
im... |
import itertools
import re
from ..Constants import ADVANCED_PARAM_TAB
from ..utils import to_list
from ..Messages import send_warning
from .block import Block
from ._flags import Flags
from ._templates import MakoTemplates
def build(id, label='', category='', flags='', documentation='',
value=None, assert... |
def __del__(self):
try:
for cb,opaque in self.domainEventCallbacks.items():
del self.domainEventCallbacks[cb]
del self.domainEventCallbacks
libvirtmod.virConnectDomainEventDeregister(self._o, self)
except AttributeError:
pass
if self._o... |
"""
Run the Rez GUI application.
"""
def setup_parser(parser, completions=False):
parser.add_argument(
"--diff", nargs=2, metavar=("RXT1", "RXT2"),
help="open in diff mode with the given contexts")
FILE_action = parser.add_argument(
"FILE", type=str, nargs='*',
help="context fi... |
from openerp import tools
from openerp.addons.crm import crm
from openerp.osv import fields, osv
AVAILABLE_STATES = [
('draft', 'Draft'),
('open', 'Todo'),
('cancel', 'Cancelled'),
('done', 'Held'),
('pending', 'Pending')
]
class crm_phonecall_report(osv.osv):
""" Phone calls by user and sect... |
"""
A small collection of useful user-agent header strings. These should be
kept reasonably current to reflect common usage.
"""
# pylint: line-too-long
# A collection of (name, shortcut, string) tuples.
UASTRINGS = [
("android",
"a",
"Mozilla/5.0 (Linux; U; Android 4.1.1; en-gb; Nexus 7 Build/... |
'''
This file is part of GEAR.
GEAR is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distrib... |
#!/usr/bin/env python
# android-build.py
# Build android
import sys
import os, os.path
CPP_SAMPLES = ['cpp-empty-test', 'cpp-tests', 'game-controller-test']
LUA_SAMPLES = ['lua-empty-test', 'lua-tests', 'lua-game-controller-test']
JS_SAMPLES = ['js-tests']
ALL_SAMPLES = CPP_SAMPLES + LUA_SAMPLES + JS_SAMPLES
def c... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
def find_vswitch_by_name(host, vswitch_name):
for vss in host.config.net... |
from __future__ import print_function
__docformat__ = 'restructuredtext'
import os
import sys
import traceback
try:
from sphinx.application import Sphinx
except ImportError:
print("#################################")
print("Dependency missing: Python Sphinx")
print("#################################")... |
import logging
from rdflib import URIRef
from oldman.vocabulary import HYDRA_SUPPORTED_OPERATION, HYDRA_METHOD, HYDRA_EXCEPTS
from oldman.vocabulary import HYDRA_RETURNS, OLDM_SHORTNAME
from oldman.model.operation import Operation
def get_operation_function(operation_functions, class_iri, ancestry, method):
# T... |
#coding: utf8
#pylint: skip-file
from iris.etl.parser import parse_blocks, parse_user
def test_empty_string():
assert [] == parse_blocks('')
def test_multi_attrs():
content = '''
D: System
M: Markus
M: Mickey
'''
assert parse_blocks(content) == [
('D', {'D': ['System'], 'M': ['Ma... |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/stable/config
import os
import sys
from unittest.mock import MagicMock
import importlib
# ... |
__all__ = ['BaseDumper', 'SafeDumper', 'Dumper']
from emitter import *
from serializer import *
from representer import *
from resolver import *
class BaseDumper(Emitter, Serializer, BaseRepresenter, BaseResolver):
def __init__(self, stream,
default_style=None, default_flow_style=None,
ca... |
from numpy import *
import time, sys, os
import mypaintlib, helpers
import math
TILE_SIZE = N = mypaintlib.TILE_SIZE
MAX_MIPMAP_LEVEL = mypaintlib.MAX_MIPMAP_LEVEL
use_gegl = True if os.environ.get('MYPAINT_ENABLE_GEGL', 0) else False
from layer import DEFAULT_COMPOSITE_OP
# Avoid pulling in PyGTK+ when using GI
if... |
#! /usr/bin/env python3
# Variant of "which".
# On stderr, near and total misses are reported.
# '-l<flags>' argument adds ls -l<flags> of each file found.
import sys
if sys.path[0] in (".", ""): del sys.path[0]
import sys, os
from stat import *
def msg(str):
sys.stderr.write(str + '\n')
def main():
pathli... |
"""Tests NeuTra."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
from absl.testing import parameterized
import tensorflow.compat.v1 as tf
import tensorflow_probability as tfp
from discussion import neutra
from tensorflow_probabilit... |
""" logger.py - Terminator Plugin to log 'content' of individual
terminals """
import os
import sys
import gtk
import terminatorlib.plugin as plugin
from terminatorlib.translation import _
AVAILABLE = ['Logger']
class Logger(plugin.MenuItem):
""" Add custom command to the terminal menu"""
capabilities = ['te... |
"""This module represents the N'Ko language.
.. seealso:: http://en.wikipedia.org/wiki/N'Ko_language
"""
import re
from translate.lang import common
def reverse_quotes(text):
def convertquotation(match):
return u"”%s“" % match.group(1)
return re.sub(u'“([^”]+)”', convertquotation, text)
class nqo... |
from openerp.tests import common
from .common import ChangesetMixin
class TestChangesetFieldType(ChangesetMixin, common.TransactionCase):
""" Check that changeset changes are stored expectingly to their types """
def _setup_rules(self):
ChangesetFieldRule = self.env['changeset.field.rule']
Ch... |
""" Tests of specific tabs. """
from mock import patch, Mock
from nose.plugins.attrib import attr
from unittest import TestCase
import xmodule.tabs as xmodule_tabs
from openedx.core.lib.course_tabs import CourseTabPluginManager
@attr(shard=2)
class CourseTabPluginManagerTestCase(TestCase):
"""Test cases for Co... |
""" Defines a profit maximisation task.
"""
import logging
from scipy import power
from pybrain.rl.environments import Task
logger = logging.getLogger(__name__)
class ProfitTask(Task):
""" Defines a task with discrete observations of the clearing price.
"""
def __init__(self, environment, maxSteps=24... |
import os
import time
from string import Template
from panoptes.pocs import dome
from panoptes.utils import error
from panoptes.pocs.utils import theskyx
from panoptes.utils.serializers import from_json
class Dome(dome.AbstractDome):
"""docstring for Dome"""
def __init__(self, *args, **kwargs):
"""... |
#!/usr/bin/env python
# Taken from https://github.com/jacobsalmela/tccutil
##############################
######### IMPORTS ############
import sqlite3
import sys
import getopt
import os
from platform import mac_ver
from distutils.version import StrictVersion as version
##############################
######## VARI... |
from jsonschema import Draft4Validator, ValidationError, cli
from jsonschema.compat import StringIO
from jsonschema.exceptions import SchemaError
from jsonschema.tests.compat import mock, unittest
def fake_validator(*errors):
errors = list(reversed(errors))
class FakeValidator(object):
def __init__(s... |
"""Sphinx extension to link to source code on GitHub.
This links to source code for modules, classes, etc. to the correct line on
GitHub. This prevents having to bundle the source code along with the
documentation, and better ties everything together.
Setup
=====
To use this, you'll need to import the module and de... |
import copy
import multiprocessing
import os
import sys
from crossrunner.util import merge_dict
def domain_socket_path(port):
return '/tmp/ThriftTest.thrift.%d' % port
class TestProgram(object):
def __init__(self, kind, name, protocol, transport, socket, workdir, command, env=None,
extra_args=[]... |
import asyncio
import logging
import pathlib
import jinja2
import aiohttp_jinja2
from aiohttp import web
from aiohttpdemo_polls.db import init_postgres
from aiohttpdemo_polls.middlewares import setup_middlewares
from aiohttpdemo_polls.routes import setup_routes
from aiohttpdemo_polls.utils import load_config
PROJ_RO... |
# -*- coding: utf-8 -*-
"""
pygments.lexers.ambient
~~~~~~~~~~~~~~~~~~~~~~~
Lexers for AmbientTalk language.
:copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, include, words
from pygment... |
import logging
import os
from lxml import etree
from django.core import management
from django.core.management.base import NoArgsCommand
from django.utils.translation import ugettext as _
from hadoop import cluster
from desktop.models import Document
from liboozie.submittion import create_directories
from oozie.conf... |
from django.test.runner import DiscoverRunner
from zerver.lib.cache import bounce_key_prefix_for_testing
from zerver.views.messages import get_sqlalchemy_connection
import os
import time
import unittest
def slow(expected_run_time, slowness_reason):
'''
This is a decorate that annotates a test as being "know... |
"""
"""
from base import *
import pytest
import requests
product = End('product')
imports = End('import')
exports = End('export')
warning_product = End('warning_product')
TEST_PRODUCT_SNUM = "prodcut_123"
def setup_module():
imports.clear();
exports.clear();
product.clear()
def test_main():
produc... |
from setuptools import setup, find_packages
NAME = "autorestreportservice"
VERSION = "1.0.0"
# To install the library, run the following
#
# python setup.py install
#
# prerequisite: setuptools
# http://pypi.python.org/pypi/setuptools
REQUIRES = ["msrest>=0.2.0"]
setup(
name=NAME,
version=VERSION,
descr... |
import os
import shutil
import time
from unittest import main
from uuid import uuid4
from swiftclient import client
from swift.common import direct_client
from swift.obj.diskfile import get_data_dir
from swift.common.exceptions import ClientException
from test.probe.common import (
kill_server, ReplProbeTest, st... |
"""Fixtures for cloud tests."""
from unittest.mock import patch
import jwt
import pytest
from homeassistant.components.cloud import const, prefs
from . import mock_cloud, mock_cloud_prefs
@pytest.fixture(autouse=True)
def mock_user_data():
"""Mock os module."""
with patch("hass_nabucasa.Cloud.write_user_in... |
# -*- coding: utf-8 -*-
import time
from module.network.HTTPRequest import BadHeader
from module.network.RequestFactory import getURL as get_url
from ..internal.Account import Account
from ..internal.misc import json
class TenluaVn(Account):
__name__ = "TenluaVn"
__type__ = "account"
__version__ = "0.01... |
"""Compute global objects.
Global objects are defined by interfaces with [Global] or [PrimaryGlobal] on
their definition: http://heycam.github.io/webidl/#Global
Design document: http://www.chromium.org/developers/design-documents/idl-build
"""
import optparse
import os
import cPickle as pickle
import sys
from utili... |
import string
import re
###$ event <<expand-word>>
###$ win <Alt-slash>
###$ unix <Alt-slash>
class AutoExpand:
menudefs = [
('edit', [
('E_xpand Word', '<<expand-word>>'),
]),
]
wordchars = string.ascii_letters + string.digits + "_"
def __init__(self, editwin):
... |
from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import Index
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import String
from sqlalchemy import Table
table_name = 'bm_pxe_ips'
def upgrade(migrate_engine):
meta = MetaDa... |
from __future__ import unicode_literals
import json
import logging
log = logging.getLogger(__file__)
def write_to_xls(workbook, molecules):
""""
Given an array of JSON objects, write them out to an upload ready XLSX
File. Column headers will have the full attribute path of the data,
on record will b... |
import time
from openerp.osv import osv
from openerp.report import report_sxw
class analytic_account_budget_report(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(analytic_account_budget_report, self).__init__(cr, uid, name, context=context)
self.localcontext.update( {
... |
import sys
import unittest
from celery.contrib.testing.worker import start_worker
from airflow.executors.celery_executor import CeleryExecutor
from airflow.executors.celery_executor import app
from airflow.utils.state import State
# leave this it is used by the test worker
import celery.contrib.testing.tasks
class C... |
import yaml
from datetime import datetime
from uuid import uuid4
from collections import defaultdict
from sqlalchemy import Column, String, DateTime, ForeignKey, Integer, Text
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.orm import relationship, joinedload
from sqlalchemy.schema impor... |
#-*- coding: utf-8 -*-
from django import forms
from django.utils.translation import ugettext as _
from filer import settings as filer_settings, settings
from filer.admin.fileadmin import FileAdmin
from filer.models import Image
class ImageAdminForm(forms.ModelForm):
subject_location = forms.CharField(
... |
"""Internationalization for the tests."""
from __future__ import absolute_import, unicode_literals
__metaclass__ = type
__all__ = [
'TestingStrategy',
'initialize',
]
from contextlib import closing
from flufl.i18n import registry
from gettext import GNUTranslations, NullTranslations
from pkg_resources i... |
'''Rendering contexts for various GUI libraries, scene graph
geometry objects, and PyOpenGL testing code
The OpenGLContext project provides a simplified environment
for writing OpenGL code with PyOpenGL. This simplified
environment abstracts the GUI library interfaces for a
large number of GUI libraries to allow the ... |
import requests
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView)
from .provider import FirefoxAccountsProvider
class FirefoxAccountsOAuth2Ad... |
"""
Copyright 2012 Joe Friedl
See LICENSE for licensing details.
"""
import pyglet
class Cursor(object):
def __init__(self, game):
self.game = game
self.batch = game.sprites
self.group = game.cursor_group
self.x = 0
self.y = 90
self.width = 70
self.height ... |
# -*- coding: utf-8 -*-
from copy import deepcopy
from django.contrib import admin
from django.contrib.admin import site
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext as _
from cms.admin.forms import GlobalPagePermissionAdmi... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
import re
import itertools
from ansible.module_utils.netcli import CommandRunner
from ansible.module_utils.network import NetworkModule
import ansible.module_utils.dellos9
class FactsBas... |
from __future__ import absolute_import
from __future__ import print_function
import json
from mock import Mock
from twisted.trial import unittest
from buildbot.test.util import www
from buildbot.util import bytes2NativeString
from buildbot.www import ws
class WsResource(www.WwwTestMixin, unittest.TestCase):
... |
# coding: utf-8
# Jabok @ 10th May
from simplegame import Sprite, Loader, Game, Vector, Clear
from rotation import Rotatable
#from main import destroy
import pygame
import math
class Upgrade(Sprite):
def __init__(self, parent, name, relpos, imagefile, description,
centered=False):
self.layer = ... |
import errno
import os
import re
import subprocess
import sys
"""
Copies the given "win tool" (which the toolchain uses to wrap compiler
invocations) and the environment blocks for the 32-bit and 64-bit builds on
Windows to the build directory.
The arguments are the visual studio install location and the location of ... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import inspect
from abc import abstractmethod
from collections import defaultdict
import six
from pants.base.build_file_target_factory import BuildFileTargetFactory
... |
from __future__ import division, print_function, absolute_import
import glob
import os.path
import shutil
import tempfile
import warnings
import numpy as np
from numpy.ma.testutils import assert_mask_equal
from numpy.testing import (assert_equal, dec, decorate_methods,
TestCase, run_module_... |
"""CIFAR100 small image classification dataset.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import numpy as np
from tensorflow.contrib.keras.python.keras import backend as K
from tensorflow.contrib.keras.python.keras.datasets.cifar import... |
########################################################################
# $Header: /var/local/cvsroot/4Suite/Ft/Lib/DistExt/__init__.py,v 1.19.2.5 2006/10/30 20:39:16 jkloth Exp $
"""
Extensions to distutils to support building, installing, packaging 4Suite
Copyright 2005 Fourthought, Inc. (USA).
Detailed license and... |
"""Argument-less script to select what to run on the buildbots."""
import os
import shutil
import subprocess
import sys
if sys.platform in ['win32', 'cygwin']:
EXE_SUFFIX = '.exe'
else:
EXE_SUFFIX = ''
BUILDBOT_DIR = os.path.dirname(os.path.abspath(__file__))
TRUNK_DIR = os.path.dirname(BUILDBOT_DIR)
ROOT_DIR... |
from optparse import OptionParser
import os
import sys
import traceback
import unittest2 as unittest
from nupic.frameworks.opf.experiment_runner import (
runExperiment, initExperimentPrng)
# Globals
EXCLUDED_EXPERIMENTS = [] # none for now
PREDICTION_DIR = os.path.join(os.environ['NTA'], 'share', 'opf')
RUN_ALL... |
#!/usr/bin/env python
#by <EMAIL>
import logging
import sys,os
import SocketServer
from array import array
import sqlite3
from datetime import datetime
import re
import time
import cStringIO
from subprocess import call
import threading
from config_note import Config
import base64
OVERRIDE_NO_ACTIONS = True
config_n... |
#! /usr/bin/env python
"""Consolidate a bunch of CVS or RCS logs read from stdin.
Input should be the output of a CVS or RCS logging command, e.g.
cvs log -rrelease14:
which dumps all log messages from release1.4 upwards (assuming that
release 1.4 was tagged with tag 'release14'). Note the trailing
colon!
Thi... |
from flask import session
from indico.modules.designer.models.templates import DesignerTemplate
from indico.modules.events import EventLogKind, EventLogRealm
def update_template(template, title, data, is_clonable, backside_template_id=None, clear_background=False):
"""Update an existing template.
:param tem... |
# =============================================================================
# Description: UVa Online Judge - 486
# =============================================================================
words = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', \
'eleven', 'twe... |
from __future__ import unicode_literals
from django.conf import settings
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.db.transaction import atomic
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext as _
from django.views.generic im... |
from __future__ import division
from .base import Layout
from .. import utils
class Tile(Layout):
defaults = [
("border_focus", "#0000ff", "Border colour for the focused window."),
("border_normal", "#000000", "Border colour for un-focused winows."),
("border_width", 1, "Border width."),
... |
# coding: utf-8
"""
A compact text based alternative to pyui
layout_text
- specifies position and size of each ui elemement
- lines represent rows in grid and each character represents a grid cell
- '*' represenrs blank cell
- ui elements represented by a single character
'b': ('button', ui.Bu... |
import unittest, time, sys, random
sys.path.extend(['.','..','py'])
import h2o, h2o_cmd, h2o_hosts, h2o_import as h2i, h2o_browse as h2b
def write_syn_dataset(csvPathname, rowCount, headerData, rList):
dsf = open(csvPathname, "w+")
dsf.write(headerData + "\n")
for i in range(rowCount):
# two c... |
"""
Implementation of an SSH2 "message".
"""
import struct
from paramiko import util
from paramiko.common import zero_byte, max_byte, one_byte, asbytes
from paramiko.py3compat import long, BytesIO, u, integer_types
class Message (object):
"""
An SSH2 message is a stream of bytes that encodes some combinatio... |
"""A simple script for inspect checkpoint files."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import sys
import numpy as np
from tensorflow.python import pywrap_tensorflow
from tensorflow.python.platform import app
from tensorflow.pyt... |
# coding: utf-8
# pylint: disable=invalid-name, no-member
"""ctypes library of mxnet and helper functions."""
from __future__ import absolute_import
import sys
import ctypes
import atexit
import warnings
import inspect
import numpy as np
from . import libinfo
warnings.filterwarnings('default', category=DeprecationWarn... |
"""Resource management library."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
def open_file(path):
"""Opens the file at given path, where path is relative to tensorflowjs/.
Args:
path: a string resource path relative to tensorflowj... |
from nova.compute import api as compute_api
from nova.compute import manager as compute_manager
from nova import context
from nova import db
from nova import objects
from nova.tests.api.openstack import fakes
from nova.tests import fake_block_device
from nova.tests import fake_instance
from nova.tests.integrated.v3 imp... |
"""Setup for pip package."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = ['six', 'absl-py', 'numpy', 'wrapt', 'dm-tree']
EXTRA_PACKAGES = {
'tensorflow': [
... |
"""Simple graph matching functions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six import string_types
from tensorflow.contrib.graph_editor import select
from tensorflow.python.framework import ops as tf_ops
__all__ = [
"op_type",
"Op... |
""" Built-in codes
This is code generation for built-in references, and some built-ins like range,
bin, etc.
"""
from nuitka import Builtins
from .ConstantCodes import getConstantCode
from .ErrorCodes import getAssertionCode, getErrorExitCode, getReleaseCodes
from .Helpers import generateChildExpressionsCode
from .Py... |
"""
A common module for postgres like databases, such as postgres or redshift
"""
import abc
import logging
import luigi
import luigi.task
logger = logging.getLogger('luigi-interface')
class CopyToTable(luigi.task.MixinNaiveBulkComplete, luigi.Task):
"""
An abstract task for inserting a data set into RDBMS... |
from HTMLComponent import HTMLComponent
from GUIComponent import GUIComponent
from enigma import eListboxPythonStringContent, eListbox
class MenuList(HTMLComponent, GUIComponent):
def __init__(self, list, enableWrapAround=True, content=eListboxPythonStringContent):
GUIComponent.__init__(self)
self.list = list
... |
from keystoneclient import exceptions as kc_exceptions
from heat.common import exception
from heat.common import short_id
from heat.common import template_format
from heat.db import api as db_api
from heat.engine import resource
from heat.engine import scheduler
from heat.engine import stack_user
from heat.tests.commo... |
from __future__ import absolute_import
import logging
import re
import pip
from pip.req import InstallRequirement
from pip.req.req_file import COMMENT_RE
from pip.utils import get_installed_distributions
from pip._vendor import pkg_resources
from pip._vendor.packaging.utils import canonicalize_name
from pip._vendor.p... |
"""
A custom AdminSite for AdminViewPermissionsTest.test_login_has_permission().
"""
from __future__ import unicode_literals
from django.contrib import admin
from django.contrib.auth import get_permission_codename
from django.contrib.auth.forms import AuthenticationForm
from . import admin as base_admin, models
PERM... |
"""
Make sure macro expansion of $(TargetFileName) is handled.
"""
import TestGyp
import os
import sys
if sys.platform == 'win32':
test = TestGyp.TestGyp(formats=['msvs', 'ninja'])
if not (test.format == 'msvs' and
int(os.environ.get('GYP_MSVS_VERSION', 0)) == 2013):
CHDIR = 'vs-macros'
test.ru... |
"""Dispatch WebSocket request.
"""
import logging
import os
import re
from mod_pywebsocket import common
from mod_pywebsocket import handshake
from mod_pywebsocket import msgutil
from mod_pywebsocket import mux
from mod_pywebsocket import stream
from mod_pywebsocket import util
_SOURCE_PATH_PATTERN = re.compile(r'... |
import contextlib
import mock
from neutron.services.loadbalancer.drivers.haproxy import cfg
from neutron.tests import base
class TestHaproxyCfg(base.BaseTestCase):
def test_save_config(self):
with contextlib.nested(
mock.patch('neutron.services.loadbalancer.'
'... |
"""Script to test TF-TensorRT integration."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.compiler.tensorrt.test import tf_trt_integration_test_base as trt_test
from tensorflow.python.framework import constant_op
from tensorflow.p... |
#!/usr/bin/env dls-python2.6
"""Test viewer for TMC-1405 etc """
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import socket, struct, time, traceback, sys, threading, sys, numpy
# lib = ctypes.CDLL("./gvsp.so")
from Queue import Queue, Full
from xml.dom import minidom
from PIL import Image
regs = {}
geni... |
import re
import logging
import time
from campus_factory.Parsers import AvailableGlideins
from campus_factory.Parsers import IdleGlideins
from campus_factory.Parsers import IdleJobs
from campus_factory.Parsers import FactoryID
from campus_factory.Parsers import RunningGlideinsJobs
from campus_factory.Parsers import Ru... |
import sys
import html5lib
import re
if len(sys.argv) != 3:
print """! html2xhtml requires two arguments: the filename to read, and the filename to write"""
exit()
#######################################################################
# Parse HTML and output XHTML
f = open(sys.argv[1])
p = html5lib.HTMLParser()... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
sys.path.append("python")
import os
import openchange
import openchange.mapistore as mapistore
from openchange import mapi
dirname = "/tmp/mapistore"
if not os.path.exists(dirname):
os.mkdir("/tmp/mapistore")
mapistore.set_mapping_path("/tmp/mapistore")
MAPI... |
#!/usr/bin/env python
import numpy as np
def convert_to_x4_q7_weights(weights):
[r, h, w, c] = weights.shape
weights = np.reshape(weights, (r, h*w*c))
num_of_rows = r
num_of_cols = h*w*c
new_weights = np.copy(weights)
new_weights = np.reshape(new_weights, (r*h*w*c))
counter = 0
for i i... |
from .. import constants, logger
from . import base_classes, api
class Object(base_classes.BaseNode):
"""Class that wraps an object node"""
def __init__(self, node, parent=None, type=None):
logger.debug("Object().__init__(%s)", node)
base_classes.BaseNode.__init__(self, node, parent=parent, ty... |
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.openstack im... |
from __future__ import unicode_literals
from django.test import SimpleTestCase
from localflavor.is_.forms import ISIdNumberField, ISPhoneNumberField, ISPostalCodeSelect
class ISLocalFlavorTests(SimpleTestCase):
def test_ISPostalCodeSelect(self):
f = ISPostalCodeSelect()
out = '''<select name="fo... |
# -*- coding: utf-8 -*-
"""
gspread.utils
~~~~~~~~~~~~~
This module contains utility functions.
"""
from xml.etree import ElementTree
def finditem(func, seq):
"""Finds and returns first item in iterable for which func(item) is True.
"""
return next((item for item in seq if func(item)))
# http://sta... |
# -*- coding: utf-8 -*-
from django.contrib.auth import get_user_model
from django.contrib.sites.models import Site
from django.core.cache import cache
from cms.admin import forms
from cms.admin.forms import (PagePermissionInlineAdminForm,
ViewRestrictionInlineAdminForm, GlobalPagePermissi... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
import time
import datetime
import parsedatetime as pdt
from parsedatetime.pdt_locales import get_icu
from . import utils
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
pdtLocale_en = get_icu('en_US')... |
"""
Views and functions for serving static files. These are only to be used
during development, and SHOULD NOT be used in a production setting.
"""
from __future__ import unicode_literals
import mimetypes
import os
import posixpath
import re
import stat
from django.http import (
FileResponse, Http404, HttpRespons... |
from abc import abstractmethod
from collections import defaultdict
def registry_metaclass_factory(base_type):
class RegisterMetaClass(base_type):
def __init__(cls, name, bases, newattrs):
super().__init__(name, bases, newattrs)
if not hasattr(cls, 'registry'):
c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.