content string |
|---|
from knack.arguments import CLIArgumentType
from azure.cli.core.commands.parameters import (name_type, get_enum_type)
from .custom import (
AzureSkuName
)
def load_arguments(self, _):
# Kusto clusters
sku_arg_type = CLIArgumentType(help='The name of the sku.',
arg_typ... |
"""This file must not depend on any module specific to the WebSocket protocol.
"""
from mod_pywebsocket import http_header_util
# Additional log level definitions.
LOGLEVEL_FINE = 9
# Constants indicating WebSocket protocol version.
VERSION_HIXIE75 = -1
VERSION_HYBI00 = 0
VERSION_HYBI01 = 1
VERSION_HYBI02 = 2
VERS... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
###############################################################################
# conkyEmail.py is a simple python script to gather
# details of google reader subscriptions for use in conky.
#
#
# 18/05/2009 Updated to expand ~ based template paths
# 14/12/2009 ... |
from subprocess import Popen,PIPE
import sys
import json
result = {}
result['all'] = {}
pipe = Popen(['virsh', '-q', '-c', 'lxc:///', 'list', '--name', '--all'], stdout=PIPE, universal_newlines=True)
result['all']['hosts'] = [x[:-1] for x in pipe.stdout.readlines()]
result['all']['vars'] = {}
result['all']['vars']['a... |
%pylab inline
import warnings
import numpy as np
import matplotlib.pyplot as plt
import rayopt as ro
# Lens used 12.5mm Dia. x 90mm FL, VIS-NIR, Inked, Achromatic Lens from Edmund Optics
# LINK: http://www.edmundoptics.com/document/download/391099
filename='zmax_49332ink.zmx'
with open(filename) as file:
data=f... |
'''
'''
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License");... |
# base class for tk common dialogues
#
# this module provides a base class for accessing the common
# dialogues available in Tk 4.2 and newer. use tkFileDialog,
# tkColorChooser, and tkMessageBox to access the individual
# dialogs.
#
# written by Fredrik Lundh, May 1997
#
from Tkinter import *
class Dialog:
com... |
from kivy.uix.widget import Widget
class TreeException(Exception):
pass
class TreeNode(object):
'''TreeNode class for representing information of Widgets
'''
def __init__(self):
super(TreeNode, self).__init__()
self.parent_node = None
self.list_children = []
self.cl... |
"""
cclib (http://cclib.sf.net) is (c) 2006, the cclib development team
and licensed under the LGPL (http://www.gnu.org/copyleft/lgpl.html).
"""
__revision__ = "$Revision: 837 $"
import random
import numpy
from population import Population
class LPA(Population):
"""The Lowdin population analysis"""
def __... |
"""
The FilterScheduler is for creating instances locally.
You can customize this scheduler by specifying your own Host Filters and
Weighing Functions.
"""
import operator
from nova import exception
from nova import flags
from nova import log as logging
from nova.notifier import api as notifier
from nova.scheduler im... |
"""Creates a new instance with default configuration files
this script creates a new instance with the default configuration files from
the ``demo/config`` directory, asking the user for MySQL credentials, and
also creating a temporary password that has to be used for first login
"""
import sys, ConfigParser, os, os.... |
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
class MyFileField(models.FileField):
pass
@python_2_unicode_compatible
class Member(models.Model):
name = models.CharField(max_lengt... |
#! /usr/bin/env python
# encoding: utf-8
import os,re
import TaskGen,Utils,Runner,Task,Build,Options,Logs
import cc
from Logs import error
from TaskGen import taskgen,before,after,feature
n1_regexp=re.compile('<refentrytitle>(.*)</refentrytitle>',re.M)
n2_regexp=re.compile('<manvolnum>(.*)</manvolnum>',re.M)
def posti... |
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
class RabbitMqUser(object):
def ... |
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='wedo',
version='1.1.0',
packages=find_packages(),
install_requires=['pyusb'],
zip_safe=False,
include_package_data=... |
import collections
import mock
from neutron.common import constants
from neutron.common import ipv6_utils
from neutron.tests import base
class IPv6byEUI64TestCase(base.BaseTestCase):
"""Unit tests for generate IPv6 by EUI-64 operations."""
def test_generate_IPv6_by_EUI64(self):
addr = ipv6_utils.get... |
def my_function():
print "Hello From My Function!"
def my_function_with_args(username, greeting):
print "Hello, %s , From My Function!, I wish you %s"%(username, greeting)
def sum_two_numbers(a, b):
return a + b
# print a simple greeting
my_function()
#prints - "Hello, John Doe, From My Function!, I wish... |
#!/usr/bin/env python3
import sys
import os
from tkinter import *
from idlelib.Percolator import Percolator
from idlelib.ColorDelegator import ColorDelegator
from idlelib.textView import view_file # TextViewer
from imp import reload
import turtle
import time
demo_dir = os.path.dirname(os.path.abspath(__file__))
STA... |
from asposewords import Settings
from com.aspose.words import Document
from com.aspose.words import DocumentBuilder
from com.aspose.words import HeaderFooterType
from com.aspose.words import ControlChar
from com.aspose.words import SectionStart
from com.aspose.words import TabAlignment
from com.aspose.words import TabL... |
"""
An L2 learning switch.
It is derived from one written live for an SDN crash course.
It is somwhat similar to NOX's pyswitch in that it installs
exact-match rules for each flow.
"""
from pox.core import core
import pox.openflow.libopenflow_01 as of
from pox.lib.util import dpid_to_str
from pox.lib.util import str_... |
"""
Middleware that profiles the request with cProfile and displays profiling
information at the bottom of each page.
"""
import sys
import os
import threading
import cgi
import time
from cStringIO import StringIO
from paste import response
try:
# Included in Python 2.5
import cProfile
except:
try:
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import time
from ansible import constants as C
from ansible.executor.module_common import get_action_args_with_defaults
from ansible.module_utils.parsing.convert_bool import boolean
from ansible.plugins.action import Act... |
import sys, time
from django.db.backends.creation import BaseDatabaseCreation
TEST_DATABASE_PREFIX = 'test_'
PASSWORD = 'Im_a_lumberjack'
class DatabaseCreation(BaseDatabaseCreation):
# This dictionary maps Field objects to their associated Oracle column
# types, as strings. Column-type strings can co... |
from django.conf.urls import patterns, url
from pdp.messages import views
urlpatterns = patterns(
'',
# Viewing a thread
url(r'^nouveau$', views.new),
url(r'^editer$', views.edit),
url(r'^(?P<topic_pk>\d+)/(?P<topic_slug>.+)$', views.topic),
# Message-related
url(r'^message/editer$', vie... |
from django.core.files.uploadedfile import SimpleUploadedFile
from pamietacz.models import Shelf, Deck, Card
from test_utils import (add_shelf,
add_deck,
add_card,
TransactionTestCaseWithAuthentication)
class DumpLoadTests(TransactionTestCaseWith... |
"""Tests for broadcast rules."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import dtypes as dtypes_lib
from tensorflow.python.framework import errors_impl
from tensorflow.python.framework import ops... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.backend.core.tasks.paths import Path, Paths
from pants.base.exceptions import TaskError
from pants_test.tasks.task_test_base import ConsoleTaskTestBase
cl... |
"""
Read temperature information from Eddystone beacons.
Your beacons must be configured to transmit UID (for identification) and TLM
(for temperature) frames.
"""
import logging
# pylint: disable=import-error
from beacontools import BeaconScanner, EddystoneFilter, EddystoneTLMFrame
import voluptuous as vol
from hom... |
"""
Tests of ModelAdmin validation logic.
"""
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
class Album(models.Model):
title = models.CharField(max_length=150)
@python_2_unicode_compatible
class Song(models.Model):
title = models.CharField(max_length=150)
al... |
# encoding: utf-8
from setuptools import setup, find_packages, Command
import sys, os
version = '0.7.2'
class Unit2Discover(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys, subprocess
basecmd... |
# -*- coding: utf-8 -*-
# Writer (c) 2019, dandy
# Rev. 1.0.0
# Licence: GPL v.3: http://www.gnu.org/copyleft/gpl.html
import xbmc
import xbmcaddon
import xbmcplugin
import xbmcgui
import XbmcHelpers as common
import resources.lib.SearchHistory as history
ID = 'script.module.dandy.search.history'
ADDON = xbmcaddon.... |
#!/usr/bin/python2.6
import os
import sys
import Queue
import threading
from subprocess import Popen, PIPE, STDOUT
import copy
import time
import re
import logging
class ExecutionError(Exception): pass
class Shell:
@classmethod
def sh(cls, cmd, host=None, username=None):
'''Execute a command locally or remot... |
import httplib, urllib, sys, socket, os
from optparse import OptionParser
from urlparse import urlparse
class InvalidParameterError(Exception):
""" Custom exception class. """
def __str__(self):
return "Invalid parameter format. Expected 'param=value param=value ...'"
def check_arguments(options, a... |
microcode = '''
def macroop PFMUL_MMX_MMX {
mmulf mmx, mmx, mmxm, size=4, ext=0
};
def macroop PFMUL_MMX_M {
ldfp ufp1, seg, sib, disp, dataSize=8
mmulf mmx, mmx, ufp1, size=4, ext=0
};
def macroop PFMUL_MMX_P {
rdip t7
ldfp ufp1, seg, riprel, disp, dataSize=8
mmulf mmx, mmx, ufp1, size=4, ext... |
from __future__ import unicode_literals
import copy
import datetime
from django.contrib.auth.models import User
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class RevisionableModel(models.Model):
base = models.ForeignKey('self', models.S... |
from test.test_support import TESTFN, run_unittest
import os
import wave
import unittest
nchannels = 2
sampwidth = 2
framerate = 8000
nframes = 100
class TestWave(unittest.TestCase):
def setUp(self):
self.f = None
def tearDown(self):
if self.f is not None:
self.f.close()
... |
# PermWrapper and PermLookupDict proxy the permissions system into objects that
# the template system can understand.
class PermLookupDict(object):
def __init__(self, user, app_label):
self.user, self.app_label = user, app_label
def __repr__(self):
return str(self.user.get_all_permissions())
... |
"""
Block Structure Transformer Registry implemented using the platform's
PluginManager.
"""
from base64 import b64encode
from hashlib import sha1
import six
from openedx.core.lib.cache_utils import process_cached
from openedx.core.lib.plugins import PluginManager
class TransformerRegistry(PluginManager):
"""... |
"""ipdevpoll plugin to monitor the state of known field-replaceable power supply and
fan units.
"""
import datetime
from twisted.internet import defer
from django.db import transaction
from nav.event2 import EventFactory
from nav.ipdevpoll import Plugin, db
from nav.models.manage import PowerSupplyOrFan
from .psu ... |
#!/usr/bin/env python
import sys
import serial
import time
print('Opening port')
arduino = serial.Serial('/dev/ttyACM0', 115200, timeout=1, dsrdtr=False)
time.sleep(3)
print('Flushing the buffer')
arduino.readline()
def a2s(arr):
""" Array of integer byte values --> binary string
"""
return ''.join(chr(b... |
import sys
import re
import functools
import distutils.core
import distutils.errors
import distutils.extension
from .dist import _get_unpatched
from . import msvc9_support
_Extension = _get_unpatched(distutils.core.Extension)
msvc9_support.patch_for_specialized_compiler()
def have_pyrex():
"""
Return True i... |
import ctypes
import binaryninja
from binaryninja import _binaryninjacore as core
from binaryninja import highlight
from binaryninja import function
from binaryninja import basicblock
from binaryninja.enums import LinearViewObjectIdentifierType
class LinearDisassemblyLine(object):
def __init__(self, line_type, func... |
import werkzeug
from openerp import http, SUPERUSER_ID
from openerp.http import request
class MassMailController(http.Controller):
@http.route('/mail/track/<int:mail_id>/blank.gif', type='http', auth='none')
def track_mail_open(self, mail_id, **post):
""" Email tracking. """
mail_mail_stats ... |
# Test some Unicode file name semantics
# We dont test many operations on files other than
# that their names can be used with Unicode characters.
import os, glob, time, shutil
import unicodedata
import unittest
from test.test_support import run_unittest, TESTFN_UNICODE
from test.test_support import TESTFN_ENCODING, T... |
import collections
import hashlib
import operator
import os
import re
import sys
RESOURCE_EXTRACT_REGEX = re.compile('^#define (\S*) (\d*)$', re.MULTILINE)
class Error(Exception):
"""Base error class for all exceptions in generated_resources_map."""
class HashCollisionError(Error):
"""Multiple resource names h... |
import os
import sys
from setuptools import setup, find_packages
version = '0.1.5'
def read(f):
return open(os.path.join(os.path.dirname(__file__), f)).read().strip()
setup(name='android-resource-remover',
version=version,
description=('Android resource remover'),
long_description='\n\n'.join... |
import unittest
from collections import namedtuple
from Vintageous.vi.utils import modes
from Vintageous.tests import set_text
from Vintageous.tests import add_sel
from Vintageous.tests import get_sel
from Vintageous.tests import first_sel
from Vintageous.tests import ViewTest
def get_text(test):
return test.vi... |
from django.shortcuts import render, Http404
from blog.models import *
from django.contrib.auth.decorators import login_required
def user_or_challenger(request):
user_id = request.user.id
chexist = False
uexist = False
try:
user = User.objects.get(id=user_id)
uexist = True
try:... |
"""
Directives for table elements.
"""
__docformat__ = 'reStructuredText'
import sys
import os.path
import csv
from docutils import io, nodes, statemachine, utils
from docutils.utils import SystemMessagePropagation
from docutils.parsers.rst import Directive
from docutils.parsers.rst import directives
class Table(... |
#!/usr/bin/env python
import json
import config
import sys
import re
from flask_cors import CORS
from gevent.pywsgi import WSGIServer
from flask import Flask, request
from werkzeug.exceptions import NotFound, Unauthorized, BadRequest
from models import *
app = Flask(__name__)
app.debug = True
app.config['CORS_HEADERS'... |
from django.core.mail import EmailMessage
from django.template.loader import render_to_string
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_protect
from django.views.generic.edit import FormView
from bedrock.base.urlresolvers import reverse
from .forms import (Pres... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
import copy
from ansible import constants as C
from ansible.module_utils._text import to_text
from ansible.module_utils.connection import Connection
from ansible.plugins.action.network import ActionModule as ActionNetwo... |
"""
Utility functions to cast types
"""
#-------------------------------------------------------------------------
#
# Python modules
#
#-------------------------------------------------------------------------
import os
import sys
import logging
LOG = logging.getLogger(".")
#-----------------------------------------... |
import unittest
from webkitpy.common.system.crashlogs import CrashLogs
from webkitpy.common.system.filesystem_mock import MockFileSystem
from webkitpy.common.system.systemhost import SystemHost
from webkitpy.common.system.systemhost_mock import MockSystemHost
def make_mock_crash_report_darwin(process_name, pid):
... |
import os
from twisted.python.failure import Failure
from twisted.internet import defer, reactor, protocol, error
from twisted.protocols.basic import LineOnlyReceiver
class FakeTransport:
disconnecting = False
class BuildmasterTimeoutError(Exception):
pass
class BuildslaveTimeoutError(Exception):
pass
cla... |
#!/usr/bin/python3
import sys, getpass, urllib.request, urllib.error, json, re
def mgmt(cmd, data=None, is_json=False):
# The base URL for the management daemon. (Listens on IPv4 only.)
mgmt_uri = 'http://127.0.0.1:10222'
setup_key_auth(mgmt_uri)
req = urllib.request.Request(mgmt_uri + cmd, urllib.parse.urlenco... |
#!/usr/bin/env python
from nose.tools import *
from nose import SkipTest
from nose.plugins.attrib import attr
import networkx
# Example from
# A. Langville and C. Meyer, "A survey of eigenvector methods of web
# information retrieval." http://citeseer.ist.psu.edu/713792.html
class TestHITS:
def setUp(self):
... |
# -*- coding: utf-8 -*-
#
try:
import xbmcaddon
__settings__ = xbmcaddon.Addon("script.myshows")
__myshows__ = xbmcaddon.Addon("plugin.video.myshows")
try:
debug = __myshows__.getSetting("debug")
except:
debug = __settings__.getSetting("debug")
except:
debug='true'
def Log(msg,... |
import logging, time, os, signal
from autotest.client.shared import error
from virttest import utils_test
def run_timedrift_with_stop(test, params, env):
"""
Time drift test with stop/continue the guest:
1) Log into a guest.
2) Take a time reading from the guest and host.
3) Stop the running of t... |
"""
Course Advanced Settings page
"""
from bok_choy.promise import EmptyPromise
from common.test.acceptance.pages.studio.course_page import CoursePage
from common.test.acceptance.pages.studio.utils import (
get_codemirror_value,
press_the_notification_button,
type_in_codemirror
)
KEY_CSS = '.key h3.title... |
'''
Created on Jun 4, 2011
@author: mkiyer
chimerascan: chimeric transcript discovery using RNA-seq
Copyright (C) 2011 Matthew Iyer
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 ... |
"""
A collection is a container for several items having the same data
structure (dtype). Each data type can be declared as local (it specific to a
vertex), shared (it is shared among an item vertices) or global (it is shared
by all vertices). It is based on the BaseCollection but offers a more intuitive
interface.
"""... |
#!/usr/bin/env python
#
# Used for quickly measuring how long the solver takes to run.
#
# Hazen 08/19
#
import numpy
import pycuda.autoinit
import pycuda.driver as drv
from pycuda.compiler import SourceModule
import time
# python3 and C NCS reference version.
import pyCNCS.ncs_c as ncsC
# OpenCL version (for the OTF... |
import os
import unittest
from conans.paths import (BUILD_FOLDER, PACKAGES_FOLDER, EXPORT_FOLDER, SimplePaths, CONANINFO)
from conans.model.ref import ConanFileReference
from conans.test.utils.test_files import temp_folder
from conans.search.search import DiskSearchManager, DiskSearchAdapter
from conans.util.files impo... |
import copy
import pickle
from random import shuffle
import unittest
from collections import OrderedDict
from collections import MutableMapping
from test import mapping_tests, test_support
class TestOrderedDict(unittest.TestCase):
def test_init(self):
with self.assertRaises(TypeError):
Ordere... |
"""Class to represent a full Closure Library dependency tree.
Offers a queryable tree of dependencies of a given set of sources. The tree
will also do logical validation to prevent duplicate provides and circular
dependencies.
"""
__author__ = '<EMAIL> (Nathan Naze)'
class DepsTree(object):
"""Represents the set... |
"""Defines access permissions for the API."""
from __future__ import absolute_import
from rest_framework import permissions
from readthedocs.core.permissions import AdminPermission
class IsOwner(permissions.BasePermission):
"""Custom permission to only allow owners of an object to edit it."""
def has_obj... |
#! /usr/bin/env python
# xxci
#
# check in files for which rcsdiff returns nonzero exit status
import sys
import os
from stat import *
import fnmatch
EXECMAGIC = '\001\140\000\010'
MAXSIZE = 200*1024 # Files this big must be binaries and are skipped.
def getargs():
args = sys.argv[1:]
if args:
retu... |
def main(request, response):
import simplejson as json
f = file('config.json')
source = f.read()
s = json.JSONDecoder().decode(source)
url1 = "http://" + s['host'] + ":" + str(s['ports']['http'][1])
url2 = "http://" + s['host'] + ":" + str(s['ports']['http'][0])
response.headers.set("Content... |
import cherrypy
# 這是 MAN 類別的定義
'''
# 在 application 中導入子模組
import programs.cdag1.remsub6 as cdag1_remsub6
# 加入 cdag1 模組下的 remsub6.py 且以子模組 remsub6 對應其 remsub6() 類別
root.cdag1.remsub6 = cdag1_remsub6.remsub6()
# 完成設定後, 可以利用
/cdag1/remsub6
# 呼叫 man.py 中 MAN 類別的 assembly 方法
'''
class remsub6(object):
# 各組利用 index 引... |
"""
Base class for graph loggers.
"""
from . import _Logger
from ..decorators import notimplemented
import re
class _GraphLogger (_Logger):
"""Provide base method to get node data."""
def __init__ (self, **kwargs):
"""Initialize graph node list and internal id counter."""
args = self.get_args... |
# -*- coding: utf-8 -*-
"""
Copyright (c) 2003-2005 Gustavo Niemeyer <<EMAIL>>
This module offers extensions to the standard Python
datetime module.
"""
from dateutil.tz import tzfile
from tarfile import TarFile
import os
__author__ = "Tomi Pieviläinen <<EMAIL>>"
__license__ = "Simplified BSD"
__all__ = ["setcaches... |
from commands.ServerCommand import ServerCommand
from database.action_group_devices import ActionGroupDevices
#######################################################################
# Command handler for group off command
class GroupOff(ServerCommand):
############################################################... |
import sys
sys.path.insert(1, "..")
from SOAPpy import *
from SOAPpy import Parser
# Uncomment to see outgoing HTTP headers and SOAP and incoming
#Config.debug = 1
if len(sys.argv) > 1 and sys.argv[1] == '-s':
server = SOAPProxy("https://localhost:9900")
else:
server = SOAPProxy("http://localhost:9900")
#... |
import os.path
import gitutil
def DetectProject():
"""Autodetect the name of the current project.
This looks for signature files/directories that are unlikely to exist except
in the given project.
Returns:
The name of the project, like "linux" or "u-boot". Returns "unknown"
if we ca... |
import re
from urllib import request as urllib2
from oslo_log import log as logging
import paste.urlmap
from nova.api.openstack import wsgi
LOG = logging.getLogger(__name__)
_quoted_string_re = r'"[^"\\]*(?:\\.[^"\\]*)*"'
_option_header_piece_re = re.compile(r';\s*([^\s;=]+|%s)\s*'
... |
"""Here lies still breathing and only renderer implementation."""
from docutils.parsers.rst import directives
from . import abc
from .. import openapi20, openapi30, utils
class HttpdomainOldRenderer(abc.RestructuredTextRenderer):
option_spec = {
# A list of endpoints to be rendered. Endpoints must be w... |
# pylint: skip-file
# flake8: noqa
# pylint: disable=too-many-instance-attributes
class OCProcess(OpenShiftCLI):
''' Class to wrap the oc command line tools '''
# pylint allows 5. we need 6
# pylint: disable=too-many-arguments
def __init__(self,
namespace,
tname=None... |
#!/usr/bin/env python
import sys
def gen_test(n):
print "CREATE TABLE t (a CHAR(%d));" % (n)
for v in [ 'hi', 'there', 'people' ]:
print "INSERT INTO t VALUES ('%s');" % (v)
for i in range(2,256):
if i < n:
print "--replace_regex /MariaDB/XYZ/ /MySQL/XYZ/"
print "--e... |
from .functions import defun, defun_wrapped
@defun_wrapped
def _erf_complex(ctx, z):
z2 = ctx.square_exp_arg(z, -1)
#z2 = -z**2
v = (2/ctx.sqrt(ctx.pi))*z * ctx.hyp1f1((1,2),(3,2), z2)
if not ctx._re(z):
v = ctx._im(v)*ctx.j
return v
@defun_wrapped
def _erfc_complex(ctx, z):
if ctx.re(... |
"""Tests for GRU layer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.keras._impl import keras
from tensorflow.python.keras._impl.keras import testing_utils
from tensorflow.python.platform import test
class ... |
from __future__ import unicode_literals
# Ensure 'assert_raises' context manager support for Python 2.6
import tests.backport_assert_raises
from nose.tools import assert_raises
import boto
import boto3
from boto.exception import EC2ResponseError
import sure # noqa
from moto import mock_ec2_deprecated, mock_ec2
@mo... |
"""Usage:
./fileinfo.py
./fileinfo.py [--help | -h]
./fileinfo.py [--verbose | -v]
./fileinfo.py [--files | -f]
./fileinfo.py [--dirs | -d]
Options:
--help -h display help information
--verbose -v increase the verbosity of output
--files -f display files only
--dirs -d... |
import textwrap
from ansible import constants as C
from ansible import errors
from ansible.callbacks import display
__all__ = ['deprecated', 'warning', 'system_warning']
# list of all deprecation messages to prevent duplicate display
deprecations = {}
warns = {}
def deprecated(msg, version, removed=False):
''' ... |
import os
import sys
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../../'))
sys.path.inser... |
"""Various utility functions."""
from collections import namedtuple, OrderedDict
__unittest = True
_MAX_LENGTH = 80
def safe_repr(obj, short=False):
try:
result = repr(obj)
except Exception:
result = object.__repr__(obj)
if not short or len(result) < _MAX_LENGTH:
return result
... |
#!/usr/bin/python2
import os
import sys
import traceback
import fcntl
from xml.dom import minidom
try:
# 3.0 compat
import libvirtconnection
libvirtconnection
except ImportError:
# 3.1 compat
from vdsm import libvirtconnection
'''
Placed in before_vm_migrate_destination
vmfex hook on migration de... |
import sys
def SetRecursionLimit(n=5000):
sys.setrecursionlimit(n)
def _or(smth, defv):
if None is smth:
return defv
else:
return smth
def get_from_dictstack(name="", *dict_stack, dstack=None):
stack = _or(dstack, dict_stack)
for d in stack:
try:
return d[name... |
import unittest
from django.test import TestCase
from django.contrib.auth import authenticate
from django.core import mail
from oscar.core.compat import get_user_model
User = get_user_model()
class TestEmailAuthBackend(TestCase):
def test_authenticates_multiple_users(self):
password = 'lookmanohands'
... |
import tempfile
from pele.systems import AtomicCluster
from pele.potentials import LJ
from pele.utils.xyz import write_xyz
__all__ = ["LJCluster"]
class LJCluster(AtomicCluster):
"""
define the System class for a Lennard-Jones cluster
Parameters
----------
natoms : int
See Also
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from decimal import Decimal, localcontext
from unittest import expectedFailure
from django.template.defaultfilters import floatformat
from django.test import SimpleTestCase
from django.utils import six
from django.utils.safestring import mark_safe
from ... |
"""
******
Layout
******
Node positioning algorithms for graph drawing.
"""
# Copyright (C) 2004-2015 by
# Aric Hagberg <<EMAIL>>
# Dan Schult <<EMAIL>>
# Pieter Swart <<EMAIL>>
# All rights reserved.
# BSD license.
import collections
import networkx as nx
__author__ = """Aric Hagberg (<EMAIL>)\nDan ... |
'''Trace data model.'''
import sys
import string
import format
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
class Node:
def visit(self, visitor):
raise NotImplementedError
def __str__(self):
stream = StringIO()
formatter = forma... |
from django.db.backends.base.features import BaseDatabaseFeatures
from django.db.utils import InterfaceError
try:
import pytz
except ImportError:
pytz = None
class DatabaseFeatures(BaseDatabaseFeatures):
empty_fetchmany_value = ()
interprets_empty_strings_as_nulls = True
uses_savepoints = True
... |
#!/usr/bin/env python
""" Create application check for v3 """
# We just want to see any exception that happens
# don't want the script to die under any cicumstances
# script must try to clean itself up
# pylint: disable=broad-except
# main() function has a lot of setup and error handling
# pylint: disable=too-many-st... |
from libcloud.compute.providers import Provider
from libcloud.compute.base import Node, NodeDriver, NodeImage, NodeLocation, \
NodeSize
from libcloud.compute.types import NodeState
from libcloud.compute.drivers.cloudstack import CloudStackNodeDriver
class KTUCloudNodeDriver(CloudStackNodeDriver):
"Driver for ... |
import tvm
import numpy as np
def test_sort():
n = 2
l = 5
m = 3
data = tvm.placeholder((n, l, m), name='data')
sort_num = tvm.placeholder((n, m), name="sort_num", dtype="int32")
axis = 1
is_ascend = False
out = tvm.extern(data.shape, [data, sort_num],
lambda ins, o... |
"""
%prog [options] <packages>
create UML diagrams for classes and modules in <packages>
"""
from __future__ import print_function
import sys, os
from logilab.common.configuration import ConfigurationMixIn
from astroid.manager import AstroidManager
from astroid.inspector import Linker
from pylint.pyreverse.diade... |
from django.conf import settings
from .. import Tags, Warning, register
from ..utils import patch_middleware_message
SECRET_KEY_MIN_LENGTH = 50
SECRET_KEY_MIN_UNIQUE_CHARACTERS = 5
W001 = Warning(
"You do not have 'django.middleware.security.SecurityMiddleware' "
"in your MIDDLEWARE so the SECURE_HSTS_SECOND... |
from __future__ import unicode_literals
from django.conf import settings
from django.utils.encoding import force_text, python_2_unicode_compatible
from django.contrib.messages import constants, utils
LEVEL_TAGS = utils.get_level_tags()
@python_2_unicode_compatible
class Message(object):
"""
Represents an a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.