content stringlengths 4 20k |
|---|
from collections import namedtuple
from games import (Game)
class GameState:
def __init__(self, to_move, board, label=None, depth=8):
self.to_move = to_move
self.board = board
self.label = label
self.maxDepth = depth
def __str__(self):
if self.label == None:
... |
'''This module monkey patches functions in ckan/authz.py and updates the
default roles with custom roles and decorates
has_user_permission_for_group_org_org to allow a GroupAdmin to admin groups.
GroupAdmins can manage all organizations/groups, but have no other sysadmin
powers.
'''
from ckan import authz, model
from c... |
import os
from nupic.frameworks.opf.expdescriptionhelpers import importBaseDescription
# the sub-experiment configuration
config = \
{ 'modelParams': { 'clParams': { 'verbosity': 0},
'sensorParams': { 'encoders': { 'consumption': { 'clipInput': True,
... |
# This file provides common utility functions for the test suite.
from clang.cindex import Cursor
from clang.cindex import TranslationUnit
def get_tu(source, lang='c', all_warnings=False, flags=[]):
"""Obtain a translation unit from source and language.
By default, the translation unit is created from source... |
from browser import document as doc
from browser.html import *
trans_menu = {
'menu_console':{'en':'Console','es':'Consola','fr':'Console', 'pt':'Console'},
'menu_editor':{'en':'Editor','es':'Editor','fr':'Editeur', 'pt':'Editor'},
'menu_gallery':{'en':'Gallery','es':'Galería','fr':'Galerie', 'pt':'Galeri... |
from __future__ import absolute_import
from . import util as testutil
from sqlalchemy import pool, orm, util
from sqlalchemy.engine import default, create_engine, url
from sqlalchemy import exc as sa_exc
from sqlalchemy.util import decorator
from sqlalchemy import types as sqltypes, schema
import warnings
import re
fr... |
# -*- coding: utf-8 -*-
"""
werkzeug.testsuite.fixers
~~~~~~~~~~~~~~~~~~~~~~~~~
Server / Browser fixers.
:copyright: (c) 2013 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import unittest
from werkzeug.testsuite import WerkzeugTestCase
from werkzeug.datastructures import Res... |
from __future__ import unicode_literals
from datetime import timedelta
from uuid import uuid4
from django.db import models
from django.contrib.auth import authenticate, get_user_model
from django.conf import settings
from django.core.urlresolvers import reverse
from django.utils import timezone
now = timezone.now
de... |
# -*- coding: utf-8 -*-
'''
The Django Admin Generator is a project which can automatically generate
(scaffold) a Django Admin for you. By doing this it will introspect your
models and automatically generate an Admin with properties like:
- `list_display` for all local fields
- `list_filter` for foreign keys with fe... |
"""Test cases for Zinnia's mixins"""
from datetime import date
from django.test import TestCase
from django.contrib.sites.models import Site
from django.core.exceptions import ImproperlyConfigured
from django.contrib.auth.tests.utils import skipIfCustomUser
from zinnia.models.entry import Entry
from zinnia.models.aut... |
import unittest
import re
from VintageousEx.test_runner import g_test_view
from VintageousEx.tests import select_bof
from VintageousEx.tests import select_eof
from VintageousEx.tests import select_line
from VintageousEx.vex.ex_range import EX_RANGE
from VintageousEx.vex.ex_range import new_calculate_range
f... |
#!/usr/bin/env python
"""Checks for link behavior required for sdist to retain symlinks."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import platform
import shutil
import sys
import tempfile
def main():
"""Main program entry point."""
temp_dir = tempf... |
from logging import getLogger
from django.http import Http404
from api.api_views import APIView
# noinspection PyProtectedMember
from api.fields import get_boolean_value
from api.exceptions import PermissionDenied
from api.task.response import FailureTaskResponse, mgmt_task_response
from api.mon import MonitoringServ... |
from neutron.openstack.common import jsonutils
from neutron.openstack.common import log as logging
from neutron.plugins.vmware.vshield.common import VcnsApiClient
LOG = logging.getLogger(__name__)
HTTP_GET = "GET"
HTTP_POST = "POST"
HTTP_DELETE = "DELETE"
HTTP_PUT = "PUT"
URI_PREFIX = "/api/4.0/edges"
#FwaaS constan... |
import mock
from oslo.config import cfg
from webob import exc
from neutron.common import constants
from neutron.db import api as db_api
from neutron.db import external_net_db
from neutron.db import l3_db
from neutron.db import l3_gwmode_db
from neutron.db import models_v2
from neutron.extensions import l3
from neutron... |
#!/usr/bin/env python
"""
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");... |
class Expense:
def __init__(self, date, amount, tags, note):
ESTR_BAD_AMT_VAL = "Bad amount value for an expense at date %s"
ESTR_BAD_TAG_LST = "Bad tags list for an expense at date %s"
ESTR_EMP_TAG_LST = "Tags list for an expense at date %s is empty"
ESTR_INV_NTE = "Note for an ... |
from __future__ import absolute_import
from sentry.cache import default_cache
from django.core.urlresolvers import reverse
from sentry.api import client
from sentry.models import ApiToken
from sentry.api.serializers import serialize
from sentry.web.frontend.base import BaseView
from sentry.web.helpers import render_t... |
# -*- coding: utf-8 -*-
"""
test_views
Tests Views
"""
import sys
import os
DIR = os.path.abspath(os.path.normpath(
os.path.join(
__file__,
'..', '..', '..', '..', '..', 'trytond'
)
))
if os.path.isdir(DIR):
sys.path.insert(0, os.path.dirname(DIR))
import unittest
import trytond.t... |
from pyelliptic.openssl import OpenSSL
class Cipher:
"""
Symmetric encryption
import pyelliptic
iv = pyelliptic.Cipher.gen_IV('aes-256-cfb')
ctx = pyelliptic.Cipher("secretkey", iv, 1, ciphername='aes-256-cfb')
ciphertext = ctx.update('test1')
ciphertext += ctx.update(... |
from savu.plugins.plugin import Plugin
"""
.. module:: plugins_test
:platform: Unix
:synopsis: unittest test classes for plugins
.. moduleauthor:: Mark Basham <<EMAIL>>
"""
import unittest
from savu.plugins import utils as pu
from savu.test import test_utils as tu
from savu.plugins.cpu_plugin import CpuPlug... |
from ansible.module_utils.basic import *
from collections import defaultdict
try:
from pysnmp.entity.rfc3413.oneliner import cmdgen
has_pysnmp = True
except:
has_pysnmp = False
class DefineOid(object):
def __init__(self,dotprefix=False):
if dotprefix:
dp = "."
else:
... |
from flask_wtf import Form
from wtforms import validators
from wtforms import StringField, PasswordField, BooleanField
from mmm.validators import validate_active_user, validate_domain_name, validate_email_username, validate_combined_email_address
from mmm.models import Domain
from mmm.fields import DomainField
class ... |
"""
timeformat.py
Contains functions to format time periods. Based on code from the Django project and CloudBot contributors.
The licensing for this module isn't solid, because I started working on this module before I had a proper
system for tracking code licences. If your code is in this file and you have any queri... |
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.network.che... |
import numpy as np
from .univariate_model import UnivariateModel
from scipy.interpolate import UnivariateSpline
from statsmodels.distributions.empirical_distribution import StepFunction
class UnivariateCurve(UnivariateModel):
def __init__(self, xx):
super(UnivariateCurve, self).__init__(xx_is_categorical=F... |
#!/usr/bin/env python
"""
This script demonstrates how one can script the Mayavi application by
subclassing the application, create a new scene and create a few
simple modules.
This should be run as::
$ python test.py
"""
# Copyright (c) 2005-2007, Enthought, Inc.
# License: BSD Style.
# Standard library imports... |
import uno
import unohelper
import string
import re
from com.sun.star.task import XJobExecutor
if __name__<>"package":
from lib.gui import *
from LoginTest import *
database="test"
uid = 3
class ConvertFieldsToBraces( unohelper.Base, XJobExecutor ):
def __init__(self,ctx):
self.ctx = ct... |
"""
This page is in the table of contents.
Extrusion is a script to set the extrusion profile for the skeinforge chain.
The displayed craft sequence is the sequence in which the tools craft the model and export the output.
On the extrusion dialog, clicking the 'Add Profile' button will duplicate the selected profile ... |
"""
This module houses the error-checking routines used by the GDAL
ctypes prototypes.
"""
from ctypes import c_void_p, string_at
from django.contrib.gis.gdal.error import check_err, OGRException, SRSException
from django.contrib.gis.gdal.libgdal import lgdal
# Helper routines for retrieving pointers and/or values f... |
# -*- coding: utf-8 -*-
"""
pygments.styles.xcode
~~~~~~~~~~~~~~~~~~~~~
Style similar to the `Xcode` default theme.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.style import Style
from pygments.token import Keyword, N... |
from django.core.files.uploadedfile import SimpleUploadedFile
from django.forms import ClearableFileInput
from django.utils import six
from django.utils.encoding import python_2_unicode_compatible
from .base import WidgetTest
@python_2_unicode_compatible
class FakeFieldFile(object):
"""
Quacks like a FieldFi... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import io
from units.compat import unittest
from ansible.parsing import vault
from ansible.parsing.yaml import dumper, objects
from ansible.parsing.yaml.loader import AnsibleLoader
from units.mock.yaml_helper import YamlTestUtils... |
from Screens.Screen import Screen
from Components.ActionMap import NumberActionMap
from Components.Label import Label
from Components.ChoiceList import ChoiceEntryComponent, ChoiceList
from Components.Sources.StaticText import StaticText
from Components.Pixmap import Pixmap
import enigma
class ChoiceBox(Screen):
def ... |
__author__ = "huhamhire <<EMAIL>>"
import sys
from zipfile import BadZipfile
from qdialog_slots import QDialogSlots
sys.path.append("..")
from util import RetrieveData, CommonUtil
# Path to store language files
LANG_DIR = "./gui/lang/"
class HostsUtil(QDialogSlots):
"""
HostsUtil class is the main entran... |
"""distutils.command.build
Implements the Distutils 'build' command."""
# This module should be kept compatible with Python 2.1.
__revision__ = "$Id: build.py 62197 2008-04-07 01:53:39Z mark.hammond $"
import sys, os
from distutils.core import Command
from distutils.errors import DistutilsOptionError
from distutils... |
from __future__ import absolute_import
import collections
import functools
import logging
try: # Python 3
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
from ._collections import RecentlyUsedContainer
from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool
from ... |
from nose.tools import assert_raises
import gevent
import sys
from zerorpc import zmq
import zerorpc
from testutils import teardown, random_ipc_endpoint
def test_server_manual():
endpoint = random_ipc_endpoint()
class MySrv(zerorpc.Server):
def lolita(self):
return 42
def add(s... |
import datetime
from decimal import Decimal
from django.db import models
from django.utils.translation import ugettext_lazy as _
class StandardMetadata(models.Model):
"""
A basic (abstract) model for metadata.
"""
created = models.DateTimeField(_('Created'), default=datetime.datetime.now)
updated ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
import sys
if sys.version_info < (2, 7):
pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7")
from ansible.module_utils.basic import AnsibleModule
try:
from librar... |
"""Definition of XLA test case."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import contextlib
import os
import random
import re
import numpy as np
from tensorflow.contrib.compiler import jit
from tensorflow.core.framework import types_pb2
from tens... |
# -*- coding: utf-8 -*-
from babelfish import LanguageReverseConverter
from ..exceptions import ConfigurationError
class TheSubDBConverter(LanguageReverseConverter):
def __init__(self):
self.from_thesubdb = {'en': ('eng',), 'es': ('spa',), 'fr': ('fra',), 'it': ('ita',), 'nl': ('nld',),
... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
QtTest.py
---------------------
Date : March 2016
Copyright : (C) 2016 by Juergen E. Fischer
Email : jef at norbit dot de
*******************************... |
"""
Dialogue used to select and configure an inputdevice. This includes mapping
buttons and axis to match controls for the Crazyflie.
"""
import sys
import json
import logging
from cfclient.utils.config_manager import ConfigManager
from cflib.crtp.exceptions import CommunicationException
from PyQt4 import Qt, QtCore... |
from copy import deepcopy
import unittest
from extensions_paths import CHROME_API
from file_system import FileNotFoundError
from host_file_system_provider import HostFileSystemProvider
from object_store_creator import ObjectStoreCreator
from test_data.canned_data import CANNED_API_FILE_SYSTEM_DATA
from test_file_syste... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
import pipes
import subprocess
import sys
import time
from ansible import constants as C
from ansible.errors import AnsibleError, AnsibleParserError
from ansible.executor.connection_info import ConnectionInformation
fr... |
import time
from tests.compat import mock, unittest
from tests.unit import AWSMockServiceTestCase
from tests.unit import MockServiceWithConfigTestCase
from boto.s3.connection import S3Connection, HostRequiredError
from boto.s3.connection import S3ResponseError, Bucket
class TestSignatureAlteration(AWSMockServiceTes... |
import tensorflow as tf
from sys import argv
from util import run_model
def main():
inputs = tf.Variable(tf.reshape(tf.range(0.0, 16), [1, 1, 4, 4]), name = 'input')
inputs = tf.identity(inputs, "input_node")
output = tf.layers.batch_normalization(inputs, axis=1, training=True)
named_output = tf.nn.... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import subprocess
import unittest
from pants.base.scm_project_tree import ScmProjectTree
from pants.scm.git import Git
from pants_test.base.pants_ignore_test_base imp... |
import xlrd
import numpy as np
def importBus():
wb = xlrd.open_workbook('Demand.xlsx')
sh = wb.sheet_by_name(u'Sheet1')
resultFinal=[]
compteur = 0
for rownum in range(sh.nrows):
inter1 = sh.row_values(rownum)
if compteur > 0:
nomBus = inter1[0]
typeCons = 2... |
# -*- coding: utf-8 -*-
"""Código para display HD44780 conectado via I2C con un modulo PCF8574."""
from Adafruit_BBIO import GPIO
from i2c_lcd import I2cLcd
import time
"""
Dirección por defecto del display: 0x27. Probado en una BB Black con Debian -
kernel 4.4.83 - Verificar la dirección con el comando ' i2cdetect -y... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'acq4/pyqtgraph/canvas/CanvasTemplate.ui'
#
# by: PyQt4 UI code generator 4.9
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
... |
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
from ctypes import *
from pyglet.gl import *
from pyglet.image import *
from pyglet.image.codecs import *
from pyglet.image.codecs import gif
import pyglet.lib
import pyglet.window
gdk = pyglet.lib.load_library('gdk-x11-2.0')
gdkpixbuf = pyglet.lib.lo... |
from django.contrib.gis.gdal.error import OGRException
#### OGRGeomType ####
class OGRGeomType(object):
"Encapulates OGR Geometry Types."
# Ordered array of acceptable strings and their corresponding OGRwkbGeometryType
__ogr_str = ['Unknown', 'Point', 'LineString', 'Polygon', 'MultiPoint',
... |
from __future__ import division
from openerp import models, fields, api, exceptions
import openerp.addons.decimal_precision as dp
from openerp.tools.translate import _
class PurchaseLineInvoice(models.TransientModel):
_inherit = 'purchase.order.line_invoice'
line_ids = fields.One2many('purchase.order.line_i... |
from config import messages
from google.appengine.ext import db
from model.queuepropertymixin import QueuePropertyMixin
class QueueStatus(db.Model, QueuePropertyMixin):
author = db.UserProperty()
queue_name = db.StringProperty()
bot_id = db.StringProperty()
active_bug_id = db.IntegerProperty()
act... |
from django.conf import settings
if settings.FILE_DB == settings.S3:
from crits.core.s3_tools import get_file_s3
import gridfs
import pymongo
import magic
class MongoError(Exception):
"""
Generic MongoError exception.
"""
pass
# TODO: mongo_connector() and gridfs_connector() can probably be comb... |
{
'name': 'Calendar',
'version': '1.0',
'depends': ['base', 'mail', 'base_action_rule', 'web_calendar'],
'summary': 'Personal & Shared Calendar',
'description': """
This is a full-featured calendar system.
========================================
It supports:
------------
- Calendar of events
... |
"""A retry helper for tolerating transient failures in distributed training."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import contextlib
import time
from tensorflow.python.framework import errors
from tensorflow.python.platform import tf_logging a... |
import random
from util import hook, http
def api_get(query, key, is_image=None, num=1):
url = ('https://www.googleapis.com/customsearch/v1?cx=007629729846476161907:ud5nlxktgcw'
'&fields=items(title,link,snippet)&safe=off' + ('&searchType=image' if is_image else ''))
return http.get_json(url, key=... |
import sys
import unittest
import greenlet
import _test_extension
class CAPITests(unittest.TestCase):
def test_switch(self):
self.assertEquals(
50, _test_extension.test_switch(greenlet.greenlet(lambda: 50)))
def test_switch_kwargs(self):
def foo(x, y):
return x * y
... |
"""Functions for FIR filter design."""
from math import ceil, log
import numpy as np
from numpy.fft import irfft
from scipy.special import sinc
import sigtools
# Some notes on function parameters:
#
# `cutoff` and `width` are given as a numbers between 0 and 1. These
# are relative frequencies, expressed as a fracti... |
"""
Tests for VisibilityTransformer.
"""
import ddt
from nose.plugins.attrib import attr
from ..visibility import VisibilityTransformer
from .helpers import BlockParentsMapTestCase, update_block
@attr(shard=3)
@ddt.ddt
class VisibilityTransformerTestCase(BlockParentsMapTestCase):
"""
VisibilityTransformer Te... |
# -*- coding: UTF-8 -*-
__kupfer_name__ = _("Getting Things GNOME")
__kupfer_sources__ = ("TasksSource", )
__kupfer_actions__ = ("CreateNewTask",)
__description__ = _("Browse and create new tasks in GTG")
__version__ = "2010-05-27"
__author__ = "Karol Będkowski <<EMAIL>>"
import os
import dbus
from kupfer import pl... |
from core import perf_benchmark
from measurements import blink_style
from telemetry import benchmark
import page_sets
@benchmark.Disabled('reference', 'win8')
class BlinkStyleTop25(perf_benchmark.PerfBenchmark):
"""Measures performance of Blink's style engine (CSS Parsing, Style Recalc,
etc.) on the top 25 pages... |
__all__ = [
'SoftLayerDNSDriver'
]
from libcloud.common.softlayer import SoftLayerConnection
from libcloud.common.softlayer import SoftLayerObjectDoesntExist
from libcloud.dns.types import Provider, RecordType
from libcloud.dns.types import ZoneDoesNotExistError, RecordDoesNotExistError
from libcloud.dns.base imp... |
#!/usr/bin/env python
from __future__ import print_function
import json, sys, os
from subprocess import call
from shutil import copyfile
pfx = os.path.join( os.path.dirname(__file__), "grand")
try:
copyfile( pfx+'.state', 'state' )
copyfile( pfx+'.test', 'grand.test' )
except: pass
def mkinput():
d = {
"m... |
"""A number of useful helper functions to automate common tasks."""
from django.contrib import admin
from django.contrib.admin.sites import NotRegistered
from reversion.admin import VersionAdmin
def patch_admin(model, admin_site=None):
"""
Enables version control with full admin integration for a model tha... |
"""
WSGI config for tally project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` se... |
"""
Test discovery functions.
"""
import copy
import os
import sys
from lit.TestingConfig import TestingConfig
from lit import LitConfig, Test
def chooseConfigFileFromDir(dir, config_names):
for name in config_names:
p = os.path.join(dir, name)
if os.path.exists(p):
return p
retur... |
import os
import re
import json
import shutil
import logging
import requests
import tempfile
import traceback
from slugify import Slugify
from httplib import HTTPConnection, HTTPSConnection
from urlparse import urlsplit, urljoin
from django.conf import settings
from django.http import HttpResponse
from django.utils.ht... |
"""Implementation of the public test library logging API.
This is exposed via :py:mod:`robot.api.logger`. Implementation must reside
here to avoid cyclic imports.
"""
import sys
import threading
from robot.utils import unic, encode_output
from .logger import LOGGER
from .loggerhelper import Message
LOGGING_THREAD... |
"""Main Pynche (Pythonically Natural Color and Hue Editor) widget.
This window provides the basic decorations, primarily including the menubar.
It is used to bring up other windows.
"""
import sys
import os
from Tkinter import *
import tkMessageBox
import tkFileDialog
import ColorDB
# Milliseconds between interrupt ... |
#!/usr/bin/env python
"""
Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
try:
import pymysql
except ImportError:
pass
import logging
from lib.core.data import conf
from lib.core.data import logger
from lib.core.exception import SqlmapConn... |
# -*- coding: UTF-8 -*-
import mock
import unittest
from lxml import etree
from hamcrest import assert_that, has_entry, equal_to
from ptp.libptp.exceptions import NotSupportedVersionError
from ptp.tools.burpsuite.parser import BurpXMLParser
def lxml_etree_parse(string):
return etree.fromstring(string).getroottr... |
{
"name": "MRP Variants Configurable Timing",
"version": "1.0",
"author": "OdooMRP team,"
"Avanzosc,"
"Serv. Tecnol. Avanzados - Pedro M. Baeza",
"website": "http://www.odoomrp.com",
"category": "Manufacturing",
"depends": ["mrp_configurable_timing",
"... |
import io
import os
import sys
import warnings
from itertools import takewhile
from django.apps import apps
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.db import DEFAULT_DB_ALIAS, connections, router
from django.db.migrations import Migration
from djan... |
from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^render/(?P<photo_id>\d+)/$', 'render.views.raw'),
url(r'^render/(?P<photo_id>\d+)/thumbnail/$', 'render.views... |
"""Constants for working with shell link files"""
__docformat__ = "restructuredtext en"
__all__ = [
"SLDF_DEFAULT", "SLDF_HAS_ID_LIST", "SLDF_HAS_LINK_INFO", "SLDF_HAS_NAME",
"SLDF_HAS_RELPATH", "SLDF_HAS_WORKINGDIR", "SLDF_HAS_ARGS",
"SLDF_HAS_ICONLOCATION", "SLDF_UNICODE","SLDF_FORCE_NO_LINKINFO",
"S... |
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.insert(0,... |
"""Simple textbox editing widget with Emacs-like keybindings."""
import curses
import curses.ascii
def rectangle(win, uly, ulx, lry, lrx):
"""Draw a rectangle with corners at the provided upper-left
and lower-right coordinates.
"""
win.vline(uly+1, ulx, curses.ACS_VLINE, lry - uly - 1)
win.hline(u... |
from tempest.api.compute import base
from tempest import test
class AbsoluteLimitsTestJSON(base.BaseV2ComputeTest):
@classmethod
def setup_clients(cls):
super(AbsoluteLimitsTestJSON, cls).setup_clients()
cls.client = cls.limits_client
@test.idempotent_id('b54c66af-6ab6-4cf0-a9e5-a0cb58d7... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_urllib_parse_urlparse
from ..utils import remove_end
class IwaraIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.|ecchi\.)?iwara\.tv/videos/(?P<id>[a-zA-Z0-9]+)'
_TESTS = [{
'url': ... |
import encoder_check
import numpy as np
from nupic.encoders.scalar import ScalarEncoder
if __name__ == "__main__":
print "Testing ScalarEncoder Quality"
maxval = 100.0
minval = -100.0
Nsamples = 1000
encoder = ScalarEncoder(name="scalar", n=14, w=3, minval=minval,
maxval=maxval,... |
class BaseSpatialOperations(object):
"""
This module holds the base `BaseSpatialBackend` object, which is
instantiated by each spatial database backend with the features
it has.
"""
truncate_params = {}
# Quick booleans for the type of this spatial backend, and
# an attribute for the sp... |
"""Compatibility fixes for older version of python, numpy and scipy
If you add content to this file, please give the version of the package
at which the fixe is no longer needed.
"""
# Authors: Emmanuelle Gouillart <<EMAIL>>
# Gael Varoquaux <<EMAIL>>
# Fabian Pedregosa <<EMAIL>>
# Lars Buit... |
import functools
from urllib.parse import urlencode, urljoin
from django import http, forms
from django.conf import settings
from django.contrib import admin
from django.core import validators
from django.forms.models import modelformset_factory
from django.http.response import (
HttpResponseForbidden,
HttpRes... |
"""Self-test for utility modules"""
__revision__ = "$Id$"
import os
def get_tests(config={}):
tests = []
if os.name == 'nt':
from Crypto.SelfTest.Util import test_winrandom; tests += test_winrandom.get_tests(config=config)
from Crypto.SelfTest.Util import test_number; tests += test_number.get_tes... |
import media
import fresh_tomatoes
print (media.Movie.__doc__)
# Instantiate of class Movie
inglourious_basterds = media.Movie("Inglourious Basterds",
"Story of war between France and Germany",
"http://goo.gl/rz9p8v",
... |
import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-theherk-resources',
version='1.6',
packages=find_packages(),
include_package_data=True,
install_requires=[
'django-localflavor'... |
from config import TARGET, CHANNEL_ID, CHANNEL_KEY, EXPIRY_DAYS
from .helpers import PURPOSE
from django.shortcuts import render
from creation.models import FossCategory, Language
from cms.models import Profile
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login... |
import time
import re
from openerp.report import report_sxw
from common_report_header import common_report_header
from openerp import SUPERUSER_ID
from openerp.tools.translate import _
class third_party_ledger(report_sxw.rml_parse, common_report_header):
def __init__(self, cr, uid, name, context=None):
su... |
"""Utilities for manipulating blocks and transactions."""
from .mininode import *
from .script import CScript, OP_TRUE, OP_CHECKSIG, OP_RETURN
# Create a block (with regtest difficulty)
def create_block(hashprev, coinbase, nTime=None):
block = CBlock()
if nTime is None:
import time
block.nTime... |
"""Helper script to repack paks for a list of locales.
Gyp doesn't have any built-in looping capability, so this just provides a way to
loop over a list of locales when repacking pak files, thus avoiding a
proliferation of mostly duplicate, cut-n-paste gyp actions.
"""
import optparse
import os
import sys
sys.path.a... |
from oslo_config import cfg
from oslo_log import log as logging
import paste.urlmap
from cinder.i18n import _LW
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
def root_app_factory(loader, global_conf, **local_conf):
if CONF.enable_v1_api:
LOG.warning(_LW('The v1 api is deprecated and will be removed... |
from collections import namedtuple
knapsack_item = namedtuple("knapsack_item", ["weight", "value"])
max_weight = 15
items = [
knapsack_item(weight=2, value=2),
knapsack_item(weight=1, value=2),
knapsack_item(weight=12, value=4),
knapsack_item(weight=1, value=1),
knapsack_item(weight=4, value=10),... |
"""Tools to make it a bit easier to use LabeledTensor."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six import string_types
from tensorflow.contrib.labeled_tensor.python.ops import _typecheck as tc
from tensorflow.contrib.labeled_tensor.python.op... |
"""
BibClassify daemon.
FIXME: the code below requires collection table to be updated to add column:
clsMETHOD_fk mediumint(9) unsigned NOT NULL,
This is not clean and should be fixed.
"""
import sys
import time
import os
from invenio.dbquery import run_sql
from invenio.bibtask import task_init, write_message, ta... |
"""
Django settings for journal project.
Generated by 'django-admin startproject' using Django 1.10.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os... |
class ModuleDocFragment(object):
# Standard files documentation fragment
DOCUMENTATION = """
options:
provider:
description:
- A dict object containing connection details.
default: null
suboptions:
host:
description:
- Specifies the DNS host name or address for conne... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.