content stringlengths 4 20k |
|---|
# -*- coding: utf-8 -*-
import urlparse
import unittest2
import urllib2
import werkzeug.urls
import lxml.html
import openerp
from openerp import tools
import cases
__all__ = ['load_tests', 'CrawlSuite']
class RedirectHandler(urllib2.HTTPRedirectHandler):
"""
HTTPRedirectHandler is predicated upon HTTPError... |
from ...pipeline import Lemmatizer
from ...tokens import Token
class EnglishLemmatizer(Lemmatizer):
"""English lemmatizer. Only overrides is_base_form."""
def is_base_form(self, token: Token) -> bool:
"""
Check whether we're dealing with an uninflected paradigm, so we can
avoid lemmat... |
apiAttachAvailable = u'API disponibile'
apiAttachNotAvailable = u'Non disponibile'
apiAttachPendingAuthorization = u'In attesa di autorizzazione'
apiAttachRefused = u'Rifiutato'
apiAttachSuccess = u'Riuscito'
apiAttachUnknown = u'Sconosciuto'
budDeletedFriend = u"Eliminato dall'elenco amici"
budFriend = u'Amico'... |
#!/usr/bin/env python
from __future__ import print_function
import re
from param import known_param_fields, known_units
from emit import Emit
import html
# Emit docs in a RST format
class RSTEmit(Emit):
def blurb(self):
return """This is a complete list of the parameters which can be set (e.g. via the MAV... |
from itertools import chain
import numpy as np
import scipy.signal
import mxnet as mx
class Agent(object):
def __init__(self, input_size, act_space, config):
super(Agent, self).__init__()
self.input_size = input_size
self.num_envs = config.num_envs
self.ctx = config.ctx
sel... |
import collections
import copy
import datetime
import itertools
import os
import sys
import types
from aip.classic import enforce_schema, author_match
import adsputils as utils
_config = utils.load_config()
def mergeRecords(records):
completeRecords = []
e = enforce_schema.Enforcer() # TODO: no need to creat... |
from __future__ import absolute_import
from six.moves import range, zip
import pytest
import time
import functools
import numpy as np
from numpy.testing import assert_almost_equal, assert_equal
from pmda.util import timeit, make_balanced_slices, fold_second_order_moments
def test_timeit():
with timeit() as ti... |
__all__ = [
'HTML5TreeBuilder',
]
from pdb import set_trace
import warnings
from bs4.builder import (
PERMISSIVE,
HTML,
HTML_5,
HTMLTreeBuilder,
)
from bs4.element import (
NamespacedAttribute,
whitespace_re,
)
import html5lib
from html5lib.constants import namespaces
from bs4.eleme... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'curated'}
from ansible.module_utils.basic import *
from ansible.module_utils.azure_rm_common import *
try:
from msrestazure.azure_exceptions import CloudError
from azure.common impor... |
"""
Automatic concatenation of multiple cubes over one or more existing dimensions.
.. warning::
This functionality has now been moved to
:meth:`iris.cube.CubeList.concatenate`.
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # n... |
class RegionInfo(object):
"""
Represents an AWS Region
"""
def __init__(self, connection=None, name=None, endpoint=None,
connection_cls=None):
self.connection = connection
self.name = name
self.endpoint = endpoint
self.connection_cls = connection_cls
... |
"""A module for CodeOfConduct (CoC) related classes.
https://launchpad.canonical.com/CodeOfConduct
"""
__metaclass__ = type
__all__ = ['CodeOfConduct', 'CodeOfConductSet', 'CodeOfConductConf',
'SignedCodeOfConduct', 'SignedCodeOfConductSet']
from datetime import datetime
import os
import pytz
from sqlobj... |
import os
# toolchains options
ARCH='ia32'
CPU=''
CROSS_TOOL='gcc'
if os.getenv('RTT_CC'):
CROSS_TOOL = os.getenv('RTT_CC')
# cross_tool provides the cross compiler
# EXEC_PATH is the compiler execute path, for example, CodeSourcery,
if CROSS_TOOL == 'gcc':
PLATFORM = 'gcc'
EXEC_PATH = 'E:/Program Files/CodeS... |
from LogAnalyzer import Test,TestResult
import math
class TestNaN(Test):
'''test for NaNs present in log'''
def __init__(self):
Test.__init__(self)
self.name = "NaNs"
def run(self, logdata, verbose):
self.result = TestResult()
self.result.status = TestResult.StatusType.GOO... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
try:
import shade
HAS_SHADE = True
except ImportError:
HAS_SHADE = False
def main():
argument_spec = openstack_full_argument_spec(
port=dict(required=False),
... |
from PyQt4 import QtCore, QtGui
class PyAnalogClock(QtGui.QWidget):
"""PyAnalogClock(QtGui.QWidget)
Provides an analog clock custom widget with signals, slots and properties.
The implementation is based on the Analog Clock example provided with both
Qt and PyQt.
"""
# Emitted when the clock... |
'''
We loop over words in a dataset, and for each word, we look at a context window around the word.
We generate pairs of (pivot_word, other_word_from_same_context) with label 1,
and pairs of (pivot_word, random_word) with label 0 (skip-gram method).
We use the layer WordContextProduct to learn embeddi... |
"""Base Class of TensorFlow Debugger (tfdbg) Command-Line Interface."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
from tensorflow.python.debug.cli import cli_config
from tensorflow.python.debug.cli import command_parser
from tensorflow... |
import gtk
import gobject
import dbus
import dbus.mainloop
import dbus.service
import dbus.glib
import urllib
import time
import gpodder
class gPodderPlayer(dbus.service.Object):
# Empty class with method definitions to send D-Bus signals
def __init__(self, path, name):
dbus.service.Object.__init__(s... |
maxlen=100000
minval=-1000000000
maxval=1000000000
def solution(A):
premax= None
postmax = None
maxabs = 0
tmpabs = 0
maxA=[]
length=len(A)
#not good list
if length < 2 or length > maxlen:
return 0
#build max val list for #n element
for i,val in enumerate(A):
... |
from unittest import TestCase
from scrapy.spider import Spider
from scrapy.http import Request
from scrapy.contrib.downloadermiddleware.useragent import UserAgentMiddleware
from scrapy.utils.test import get_crawler
class UserAgentMiddlewareTest(TestCase):
def get_spider_and_mw(self, default_useragent):
... |
import datetime
from django.core.exceptions import ValidationError
from django.urls import reverse
from mock import patch
from .mixins import SimpleTests
class ModelTests(SimpleTests):
def setUp(self):
self.user = self.make_user("test_user")
self.scale = self._ordinal_scale()
def test_ord... |
""" Helper methods for determining user access permissions in Studio """
from student.roles import CourseStaffRole, GlobalStaff, CourseInstructorRole, OrgStaffRole, OrgInstructorRole
from student import auth
def has_course_access(user, course_key, role=CourseStaffRole):
"""
Return True if user allowed to acc... |
import os
import sys
from itertools import takewhile
from django.apps import apps
from django.core.management.base import BaseCommand, CommandError
from django.db.migrations import Migration
from django.db.migrations.autodetector import MigrationAutodetector
from django.db.migrations.loader import MigrationLoader
from... |
import os
import subprocess
import tempfile
import logging
from functools import partial
from mako import exceptions
from openerp.osv.orm import except_orm
from openerp.tools.translate import _
from openerp import pooler
from openerp import tools
from openerp.addons.report_webkit import webkit_report
from openerp.add... |
"""
DisplayNameService provides the mapping needed to associate an un-friendly user identifier to a more friendly
user nick name.
Maintains a dict (profile_dict) of ssl profile names to SSLProfile objects. The SSLProfile objects are built using
the file name which contains a mapping of user identifiers to user names.
"... |
'''
Unit tests for applying MergeMove.py to HDPModel.py
Verification of math behind merge evidence bound (ELBO) calculation.
Attributes
-----------
self.Data : K=4 simple WordsData object from AbstractBaseTestForHDP
self.hmodel : K=4 simple bnpy model from AbstractBaseTestForHDP
Coverage
-----------
* ELBO Z terms
*... |
"""Control of and utilities for debugging."""
import os
# When debugging, it can be helpful to force some options, especially when
# debugging the configuration mechanisms you usually use to control debugging!
# This is a list of forced debugging options.
FORCED_DEBUG = []
class DebugControl(object):
"""Contro... |
"""Cluster Resolvers are used for dynamic cluster IP/hostname resolution."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
from tensorflow.python.training.server_lib import ClusterSpec
class ClusterResolver(object):
"""Abstract class for a... |
"""Utility functions related to output descriptors"""
import re
INPUT_CHARSET = "0123456789()[],'/*abcdefgh@:$%{}IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~ijklmnopqrstuvwxyzABCDEFGH`#\"\\ "
CHECKSUM_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
GENERATOR = [0xf5dee51989, 0xa9fdca3312, 0x1bab10e32d, 0x3706b1677a, 0x644d626ffd]
... |
from __future__ import print_function
import sys, os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'common')))
import multiprocessing, time, pickle
import memcached_workload_common, serial_mix
from vcoptparse import *
def child(opts, log_path, load, save):
# This is run ... |
import os
from telemetry.page import page_test
from telemetry.page import page_test
from telemetry.value import scalar
class Screenshot(page_test.PageTest):
def __init__(self):
super(Screenshot, self).__init__(
action_name_to_run = 'RunPrepareForScreenshot',
is_action_name_to_run_optional=True)... |
from __future__ import print_function
import sys
import binascii
from file_processing import *
def ngram_extract(CODE,window):
CODE = binascii.hexlify(CODE)
b = range(len(CODE))
for i in b[::2]:
print(CODE[i:i+window*2])
if __name__ == '__main__':
for filename in sys.argv[1:]:
einfo ... |
import time
import unittest
import config
import node
LEADER = 1
ROUTER = 2
ED2 = 3
SED2 = 4
MTDS = [ED2, SED2]
class Cert_7_1_5_BorderRouterAsRouter(unittest.TestCase):
def setUp(self):
self.simulator = config.create_default_simulator()
self.nodes = {}
for i in range(1,5):
... |
from django import template
from django.conf import settings
from django.contrib.flatpages.models import FlatPage
from django.contrib.sites.models import get_current_site
register = template.Library()
class FlatpageNode(template.Node):
def __init__(self, context_name, starts_with=None, user=None):
self.... |
from .TProtocol import TType, TProtocolBase, TProtocolException
from struct import pack, unpack
class TBinaryProtocol(TProtocolBase):
"""Binary implementation of the Thrift protocol driver."""
# NastyHaxx. Python 2.4+ on 32-bit machines forces hex constants to be
# positive, converting this into a long. ... |
"""
Distributed web servers.
This is going to have to be refactored so that argument parsing is done
by each subprocess and not by the main web server (i.e. GET, POST etc.).
"""
# System Imports
import types, os, copy, cStringIO
try:
import pwd
except ImportError:
pwd = None
from xml.dom.minidom import Eleme... |
from unittest import TestCase
import sys
import os.path
import tempfile
import pexpect
DATADIR = os.path.join(os.path.dirname(__file__), 'data')
SIMPLE_PNG = os.path.join(DATADIR, 'simple.png')
EXAMPLE_PNG = os.path.join(DATADIR, 'example.png')
EXAMPLE_NOCURSOR_PNG = os.path.join(DATADIR, 'example_nocursor.png')
... |
"""
Depth Spider Middleware
See documentation in docs/topics/spider-middleware.rst
"""
from pyrake import log
from pyrake.http import Request
class DepthMiddleware(object):
def __init__(self, maxdepth, stats=None, verbose_stats=False, prio=1):
self.maxdepth = maxdepth
self.stats = stats
... |
import pickle
import cocos
import ant
import skin
class Actors(cocos.layer.Layer):
def __init__(self):
super().__init__()
self.add(cocos.sprite.Sprite('background.jpg', anchor=(0, 0)))
ant_ = cocos.skeleton.BitmapSkin(ant.skeleton, skin.skin)
ant_.scale = 0.1
ant_.width ... |
"""
websocket - WebSocket client library for Python
Copyright (C) 2010 Hiroki Ohtani(liris)
This library 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 2.1 of the License, ... |
microcode = '''
def macroop POR_XMM_XMM {
mor xmml, xmml, xmmlm
mor xmmh, xmmh, xmmhm
};
def macroop POR_XMM_M {
lea t1, seg, sib, disp, dataSize=asz
ldfp ufp1, seg, [1, t0, t1], dataSize=8
ldfp ufp2, seg, [1, t0, t1], 8, dataSize=8
mor xmml, xmml, ufp1
mor xmmh, xmmh, ufp2
};
def macroop ... |
# -*- coding: utf-'8' "-*-"
import base64
try:
import simplejson as json
except ImportError:
import json
from hashlib import sha1
import hmac
import logging
import urlparse
from openerp.addons.payment.models.payment_acquirer import ValidationError
from openerp.addons.payment_adyen.controllers.main import Adye... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
########################################################
import datetime
import os
import platform
import random
import shutil
import socket
import sys
import time
from ansible.cli import CLI
from ansible.errors import AnsibleOpti... |
"""
Copyright 2015 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
dist... |
"""Generate docs for the TensorFlow Python API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import fnmatch
import os
import shutil
import six
from tensorflow.python.util import tf_inspect
from tensorflow.tools.common import public_a... |
import wx
import launcher
class PrefController(object):
"""Controller for preferences (M)."""
def __init__(self, prefs, view=None):
"""Initialize a PrefController.
Args:
prefs: the Preferences object.
view: the preference view (dialog) to use.
If None, one is created when needed.
... |
import socket
from django.conf import settings
import mock
from nose.tools import eq_, ok_
import mkt.site.tests
from mkt.users.models import UserProfile
import mkt
from mkt.api.tests.test_oauth import RestOAuth
_langs = ['cs', 'de', 'en-US', 'es', 'fr', 'pl', 'pt-BR', 'pt-PT']
@mock.patch.object(settings, 'LAN... |
# -*- 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):
# Changing field 'AnonymousUserId.anonymous_user_id'
db.alter_column('student_anonymoususerid', 'anonymous_... |
from django.conf import settings
from django.contrib.staticfiles import utils
from django.contrib.staticfiles.views import serve
from django.core.handlers.wsgi import WSGIHandler, get_path_info
from django.utils.six.moves.urllib.parse import urlparse
from django.utils.six.moves.urllib.request import url2pathname
clas... |
from __future__ import unicode_literals
import random
import string
from .exceptions import MessageAttributesInvalid
def generate_receipt_handle():
# http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/ImportantIdentifiers.html#ImportantIdentifiers-receipt-handles
length = 185
retur... |
"Test posix functions"
from test import test_support
# Skip these tests if there is no posix module.
posix = test_support.import_module('posix')
import errno
import time
import os
import pwd
import shutil
import unittest
import warnings
warnings.filterwarnings('ignore', '.* potential security risk .*',
... |
"""
==================
Pipeline Anova SVM
==================
Simple usage of Pipeline that runs successively a univariate
feature selection with anova and then a C-SVM of the selected features.
"""
from sklearn import svm
from sklearn.datasets import samples_generator
from sklearn.feature_selection import SelectKBest,... |
# -*- coding: utf-8 -*-
from openerp.osv import fields, osv
import random
import re
import string
import urllib2
import logging
from openerp import SUPERUSER_ID
from openerp.tools.translate import _
from openerp.tools import html2plaintext
from py_etherpad import EtherpadLiteClient
_logger = logging.getLogger(__name__... |
try:
import shade
HAS_SHADE = True
except ImportError:
HAS_SHADE = False
from distutils.version import StrictVersion
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
def _system_state_change(state, assignment):
if state... |
"""
NUMBER A simple integer type that's just any series of digits.
FLOAT A simple floating point type.
STRING A string is double quotes with anything inside that's not a " or
newline character. You can include \n and \" to include these
characters.
MARK Marks a point in the stack that demarcates the ... |
import os
import signal
import socket
import sys
import ovs.socket_util
def main(argv):
if len(argv) not in (2, 3):
sys.stderr.write("usage: %s SOCKETNAME1 [SOCKETNAME2]", argv[0])
sys.exit(1)
sockname1 = argv[1]
if len(argv) > 2:
sockname2 = argv[2]
else:
sockname2 = ... |
from setuptools import setup, find_packages
import os
file_dir = os.path.abspath(os.path.dirname(__file__))
def read_file(filename):
filepath = os.path.join(file_dir, filename)
return open(filepath).read()
def install_requires():
reqs = read_file('requirements.txt')
reqs = reqs.splitlines()
reqs ... |
import webob
import socialauth
from socialauth import fb
from socialauth import openid_ as openid
from socialauth import twitter
from socialauth import utils
utils.LOGIN_PATH = '/socialauth/login'
class SocialAuthMiddleware(object):
def __init__(self, app, config, User, prefix=''):
"""Init the mid... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_urllib_parse_unquote
from ..utils import (
determine_ext,
float_or_none,
get_element_by_id,
int_or_none,
parse_iso8601,
str_to_int,
)
class IzleseneIE(InfoExtractor... |
'''
This implementation is a heavily modified fixed point implementation of
BBP_formula for calculating the nth position of pi. The original hosted
at: http://en.literateprograms.org/Pi_with_the_BBP_formula_(Python)
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and a... |
#!/usr/bin/python
import pygame
from gi.repository import Gtk
class TestGame:
def __init__(self):
# Set up a clock for managing the frame rate.
self.clock = pygame.time.Clock()
self.x = -100
self.y = 100
self.vx = 10
self.vy = 0
self.paused = False
... |
#!/usr/bin/python
import os
import requests
import bitly_api
import blower
import tweet
import twilio_sms
from log import log_job
from rq import Queue
from worker import conn
from datetime import datetime
from pytz import timezone
tz = timezone('US/Pacific')
price_target = 35
earliest = 8
latest = 23
_blower = False
... |
""" LDAP datastore. """
import importlib
import logging
import tldap.backend
from tldap import Q
from tldap.database import (
Database,
LdapObject,
LdapObjectClass,
changeset,
delete,
get_one,
preload,
rename,
save,
)
from tldap.exceptions import ObjectDoesNotExist
import karaage.... |
from django.contrib.auth import get_user_model
from django.shortcuts import render, redirect
from lists.forms import ItemForm, ExistingListItemForm, NewListForm
from .models import Item, List
User = get_user_model()
def home_page(request):
return render(request, 'home.html', {'form': ItemForm()})
def view_lis... |
"""
Unit Page for Studio
"""
from edxapp_acceptance.pages.studio.container import ContainerPage
class UnitPageExtended(ContainerPage):
"""
Unit Page for Studio
"""
def view_live_version(self):
"""
Clicks View live version button on Units page which opens a new browser
window a... |
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# Create the RenderWindow, Renderer and both Actors
#
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetR... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 25 15:33:17 2016
@author: marco
"""
from requests.exceptions import ConnectionError
import datetime as dt
import numpy as np
from pandas import DataFrame, Series, set_option
from pandas_datareader import data
from shutil import copytree
from os import path, stat
class ... |
"""
SAX driver for the pyexpat C module. This driver works with
pyexpat.__version__ == '2.22'.
"""
version = "0.20"
from xml.sax._exceptions import *
from xml.sax.handler import feature_validation, feature_namespaces
from xml.sax.handler import feature_namespace_prefixes
from xml.sax.handler import feature_external_... |
"""
A pytz version that runs smoothly on Google App Engine.
Based on http://appengine-cookbook.appspot.com/recipe/caching-pytz-helper/
To use, add pytz to your path normally, but import it from the gae module:
from pytz.gae import pytz
Applied patches:
- The zoneinfo dir is removed fr... |
import time
from openerp.osv import fields
from openerp.osv import osv
from openerp.tools.translate import _
import openerp
class hr_employee(osv.osv):
_name = "hr.employee"
_inherit = "hr.employee"
_columns = {
'product_id': fields.many2one('product.product', 'Product', help="If you want to reinv... |
from openerp.osv import osv, fields
class account_bank_statement(osv.osv):
_inherit = 'account.bank.statement'
_columns = {
'coda_note': fields.text('CODA Notes'),
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
""" Common Authentication Handlers used across projects. """
from rest_framework.authentication import SessionAuthentication
from rest_framework_oauth.authentication import OAuth2Authentication
from rest_framework.exceptions import AuthenticationFailed
from rest_framework_oauth.compat import oauth2_provider, provider_n... |
from errno import ENOENT
from stat import S_IFDIR, S_IFLNK, S_IFREG
from sys import argv, exit, stdout
from time import time
from types import StringTypes
from array import array
import os
from fuse import FUSE, Operations, LoggingMixIn
import logging
logging.basicConfig(level=logging.DEBUG,
forma... |
'''
Run Resnet50 on Imagenet data.
Generate TFrecords for Imagenet data by following instructions in:
examples/build_imagenet_data/README.md
run:
# 4 GPU machine 2 sockets typically --map-by ppr:2:socket works well.
TMPDIR=/tmp mpirun --report-bindings \
--map-by ppr:2:socket -oversubscribe -np 4 p... |
from InsightToolkit import *
from sys import argv
reader = itkImageFileReaderUS2_New()
writer = itkImageFileWriterUS2_New()
inputCast = itkCastImageFilterUS2F2_New()
outputCast = itkRescaleIntensityImageFilterF2US2_New()
filter = itkCurvatureFlowImageFilterF2F2_New()
inputCast.SetInput( reader.GetOutput() ... |
import urllib
from lxml import etree
from tempest.common.rest_client import RestClientXML
from tempest.services.compute.xml.common import Document
from tempest.services.compute.xml.common import Element
from tempest.services.compute.xml.common import Text
from tempest.services.compute.xml.common import xml_to_json
fr... |
DATE_FORMAT = 'd F Y' # 25 Ottobre 2006
TIME_FORMAT = 'H:i:s' # 14:30:59
DATETIME_FORMAT = 'l d F Y H:i:s' # Mercoledì 25 Ottobre 2006 14:30:59
YEAR_MONTH_FORMAT = 'F Y' # Ottobre 2006
MONTH_DAY_FORMAT = 'j/F' # 10/2006
SHORT_DATE_FORMAT = 'd/m/Y' # 25/12/2009
SHORT_DATETIME_FORMAT = 'd/m/Y H:i:s' # 25/10/2009 14:30:59... |
#!/usr/bin/python
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import django.shortcuts
import json
from wlokalu.api import presence
#-----------------------------------------------------------------------------
from wlokalu.logging import getLogger, message as log
logger... |
import sys
import unittest
from django.test import TestCase
@unittest.skipIf(sys.version_info < (3, 3),
'Python < 3.3 cannot import the project template because '
'django/conf/project_template doesn\'t have an __init__.py file.')
class TestStartProjectSettings(TestCase):
def test_middleware_classes_head... |
"""Preprocessing utilities for sequence data.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import random
import numpy as np
from six.moves import range # pylint: disable=redefined-builtin
def pad_sequences(sequences,
maxlen=None,... |
class ModuleDocFragment(object):
# Standard oVirt documentation fragment
DOCUMENTATION = '''
options:
wait:
description:
- "I(True) if the module should wait for the entity to get into desired state."
fetch_nested:
description:
- "If I(True) the module will fetch... |
""" native_test_execution:
code related to the execution of native test cases
We are provided access to a testManager with
native-specific testCases.
"""
# imports
import os
import re
import imp
import sys
import subprocess
import unittest
import lib.test_mgmt.test_execution as test_execution
... |
"""
Instagram Image Tag
-------------------
By `Tom Spalding <https://github.com/digitalvapor>`_
You can see a working example at `antivapor.net/instagram-tag.html <http://antivapor.net/instagram-tag.html>`_.
Based on `Liquid Image Tag <https://github.com/getpelican/pelican-plugins/blob/master/liquid_tags/img.py>`_ ... |
from collections import defaultdict
# Ordered List of Coin Symbol Dictionaries
COIN_SYMBOL_ODICT_LIST = [
{
'coin_symbol': 'btc',
'display_name': 'Bitcoin',
'display_shortname': 'BTC',
'blockcypher_code': 'btc',
'blockcypher_network': 'main',
... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
import codecs
from ansible.module_utils.basic import AnsibleModule
try:
import selinux
HAVE_SELINUX=True
except ImportError:
HAVE_SELINUX=False
try:
import seobject
H... |
from __future__ import print_function
import sys, optparse, time
import logging
from proton import *
# Hi python3!
try:
long()
except:
long = int
usage = """
Usage: msgr-recv [OPTIONS]
-a <addr>[,<addr>]* \tAddresses to listen on [amqp://~0.0.0.0]
-c # \tNumber of messages to receive before exiting [0=fore... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_portgroup_info
short_description: Gathers info about an ESXi host's Port Group... |
import logging
import mock
import transaction
from itertools import islice
from db import Page, Salary, Department
from zerodb.catalog.query import Contains, InRange, Eq, Gt
# Also need to test optimize, Lt(e), Gt(e)
logging.basicConfig(level=logging.DEBUG)
def test_query(db):
pre_request_count = db._storage._de... |
from symbolic import SymbolicReference
import os
from git.objects import Object
from git.util import (
LazyMixin,
Iterable,
)
from gitdb.util import (
isfile,
hex_to_bin
)
__all__ = ["Reference"]
#{ Utilities
def require_remote_ref_path(func):
"""A decorator raising a TypeError ... |
from iptest.assert_util import *
skiptest("win32")
from System import *
import clr
#silverlight already has this
if is_cli:
math_assembly = (1).GetType().Assembly
clr.AddReference(math_assembly)
load_iron_python_test()
import IronPythonTest
if is_net40:
from System.Numerics import BigInteger, Complex
els... |
"""Local volatility model."""
from tf_quant_finance.experimental.local_stochastic_volatility.local_stochastic_volatility_model import LocalStochasticVolatilityModel
from tf_quant_finance.experimental.local_stochastic_volatility.lsv_variance_model import LSVVarianceModel
from tensorflow.python.util.all_util import rem... |
import numpy
from chainer import cuda
from chainer import function
from chainer import utils
from chainer.utils import type_check
class CrossCovariance(function.Function):
"""Cross-covariance loss."""
def __init__(self):
self.y_centered = None
self.z_centered = None
self.covariance ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations, connection
import django.db.models.deletion
is_index = connection.vendor != 'mysql'
class Migration(migrations.Migration):
dependencies = [
('django_comments', '__first__'),
]
operations =... |
import logging
import re
import time
from Config import config
from Plugin import PluginManager
allow_reload = False # No reload supported
log = logging.getLogger("ZeronamePlugin")
@PluginManager.registerTo("SiteManager")
class SiteManagerPlugin(object):
site_zeroname = None
db_domains = None
db_domai... |
import json
from tempest_lib.common import rest_client
from tempest_lib import exceptions as lib_exc
from neutron.tests.tempest.common import service_client
from neutron.tests.tempest import exceptions
class V3TokenClientJSON(rest_client.RestClient):
def __init__(self, auth_url, disable_ssl_certificate_validati... |
"""A simple log mechanism styled after PEP 282."""
# The class here is styled after PEP 282 so that it could later be
# replaced with a standard Python logging implementation.
DEBUG = 1
INFO = 2
WARN = 3
ERROR = 4
FATAL = 5
import sys
class Log:
def __init__(self, threshold=WARN):
self.threshold = thre... |
import leveldb, pointless, random, string, itertools, collections
from twisted.internet import reactor, defer, threads
def compare(a, b):
return cmp(a, b)
c = 'bytewise'
c = ('leveldb.BytewiseComparator', compare)
kw = {
'create_if_missing': True,
'error_if_exists': False,
'paranoid_checks': False,
'block_cach... |
import os
import sys
import StringIO
import BoostBuild
vms = ( os.name == 'posix' and sys.platform == 'OpenVMS')
t = BoostBuild.Tester()
## Setup test archive sources and symbols they contain.
sources = {
"a.cpp" : ["a"],
"b.cpp" : ["b"],
"b_match.cpp" : ["b_match"],
"c/nopath_check.cpp" : ["nopath_c... |
__socket = __import__('socket')
exec "\n".join(["%s = __socket.%s" % (var, var) for var in __socket.__all__])
os = __import__('os')
import sys
import warnings
from eventlet.hubs import get_hub
from eventlet.greenio import GreenSocket as socket
from eventlet.greenio import SSL as _SSL # for exceptions
from eventlet.g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.