content stringlengths 4 20k |
|---|
"Dummy cache backend"
from django.core.cache.backends.base import BaseCache, DEFAULT_TIMEOUT
class DummyCache(BaseCache):
def __init__(self, host, *args, **kwargs):
BaseCache.__init__(self, *args, **kwargs)
def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
key = self.make_key(... |
# Copied and modified from http://stackoverflow.com/a/12712362/605356
import logging, sys
from PyQt5.QtCore import pyqtSignal, QTextStream, Qt
from PyQt5.QtNetwork import QLocalSocket, QLocalServer
from PyQt5.QtWidgets import QApplication
LOGVARSTR = "%25s = '%s'"
class QtSingleApplication(QApplication):
"""
... |
import binascii
import os
import tempfile
import eventlet
import fixtures
from mox3 import mox
from nova.api.ec2 import ec2utils
from nova import context
from nova import db
from nova import exception
from nova.image import s3
from nova import test
from nova.tests.unit.image import fake
ami_manifest_xml = """<?xml ... |
import json
def getSmallestNeighbours(nextElem, arrOfArr, visited, heuristic):
elems = []
i = ord(nextElem) - ord('A')
x = 0
p = 0
smallest = max(heuristic)
for j in arrOfArr[i]:
if j > 0:
if smallest > heuristic[x]:
smallest = heuristic[x]
p = x
x += 1
data = chr(p + ord('A'))
if data not in vis... |
import time, logging, threading, traceback
import common
from iomediator import Key, IoMediator
from configmanager import *
if common.USING_QT:
from qtui.popupmenu import *
from PyKDE4.kdecore import i18n
else:
from gtkui.popupmenu import *
from macro import MacroManager
import scripting, model
logger = lo... |
import abc
import typing
import pkg_resources
from google import auth
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
from google.auth import credentials # type: ignore
from google.ads.googleads.v7.resources.types import customer_client_link
from goog... |
"""
.. dialect:: firebird+fdb
:name: fdb
:dbapi: pyodbc
:connectstring: firebird+fdb://user:password@host:port/path/to/db\
[?key=value&key=value...]
:url: http://pypi.python.org/pypi/fdb/
fdb is a kinterbasdb compatible DBAPI for Firebird.
.. versionadded:: 0.8 - Support for the fdb Firebird d... |
"""Library code for language-independent D-Bus-related code generation.
The master copy of this library is in the telepathy-glib repository -
please make any changes there.
"""
# Copyright (C) 2006-2008 Collabora Limited
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of ... |
'''
xbmcswift2.log
--------------
This module contains the xbmcswift2 logger as well as a convenience
method for creating new loggers.
:copyright: (c) 2012 by Jonathan Beluch
:license: GPLv3, see LICENSE for more details.
'''
import logging
from xbmcswift2 import CLI_MODE
# TODO: Add logging... |
from django.conf.urls import patterns, url
from accounts.views.userprofile_views import *
urlpatterns = patterns('',
url(
regex=r'^userprofile/(?P<pk>\d+)/$',
view=UserProfileDetailView.as_view(),
name='accounts_userprofile_de... |
#!/usr/bin/env python
# encoding: utf-8
# Matthias Jahn jahn dôt matthias ât freenet dôt de 2007 (pmarat)
import os, sys, imp, types, ccroot
import optparse
import Utils, Configure, Options
from Logs import debug
cxx_compiler = {
'win32': ['msvc', 'g++'],
'cygwin': ['g++'],
'darwin': ['g++'],
'aix': ['xlc++', 'g+... |
"""Functional tests for modules/upload/upload.py."""
__author__ = [
'<EMAIL> (John Cox)',
]
import os
from controllers import utils
from models import models
from models import student_work
from modules.upload import upload
from tests.functional import actions
from google.appengine.ext import db
class TextFile... |
import os
import re
import sys
from setuptools import setup, find_packages
if sys.version_info[:2] < (2, 6):
raise RuntimeError('Requires Python 2.6 or better')
here = os.path.abspath(os.path.dirname(__file__))
info = open(os.path.join(here, 'inferno', 'lib', '__init__.py')).read()
VERSION = re.compile(r".*__ve... |
"""TLS Lite + asyncore."""
import asyncore
from tlslite.tlsconnection import TLSConnection
from .asyncstatemachine import AsyncStateMachine
class TLSAsyncDispatcherMixIn(AsyncStateMachine):
"""This class can be "mixed in" with an
L{asyncore.dispatcher} to add TLS support.
This class essentially sits be... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
determine_ext,
int_or_none,
try_get,
unified_timestamp,
url_or_none,
)
class EggheadCourseIE(InfoExtractor):
IE_DESC = 'egghead.io course'
IE_NAM... |
import pytest
from unittest import mock
from asynccmd import Cmd
@pytest.mark.parametrize(("platform", "expected"), [
("linux", "<_UnixSelectorEventLoop"),
])
def test_create_cmd(loop, platform, expected):
platform_patcher = mock.patch('sys.platform', platform)
platform_patcher.start()
aio_cmd = Cmd(m... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: aci_filter_entry
short_description: Manage filter entries (v... |
"""Scans a source JS file for its provided and required namespaces.
Simple class to scan a JavaScript file and express its dependencies.
"""
__author__ = '<EMAIL>'
import re
_BASE_REGEX_STRING = '^\s*goog\.%s\(\s*[\'"](.+)[\'"]\s*\)'
_PROVIDE_REGEX = re.compile(_BASE_REGEX_STRING % 'provide')
_REQUIRES_REGEX = re.... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('manufacturers', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Car',
fields=[
... |
import document_page_show_diff
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
"""Message actions."""
__metaclass__ = type
__all__ = [
'Action',
'FilterAction',
]
from flufl.enum import Enum
class Action(Enum):
hold = 0
reject = 1
discard = 2
accept = 3
defer = 4
class FilterAction(Action):
forward = 5
preserve = 6 |
from libcloud.common.base import ConnectionKey, JsonResponse
from libcloud.common.types import InvalidCredsError
from libcloud.utils.py3 import PY3
from libcloud.utils.py3 import b
__all__ = [
'API_HOST',
'API_ROOT',
'LinodeException',
'LinodeResponse',
'LinodeConnection'
]
# Endpoint for the Lin... |
"""
## @file
"""
import numpy
from PIL import Image
from nupic.regions.ImageSensorFilters.BaseFilter import BaseFilter, uint
class HistogramShift(BaseFilter):
"""
Shifts the image histogram randomly in any direction, given a difficulty level.
"""
def __init__(self, difficulty = 0.5, seed=None, reproducible=F... |
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
from .._ffi import FFIEngineError, register_ffi
from .._types import str_cls
from ..errors import LibraryNotFoundError
try:
from cffi import FFI
except (ImportError):
raise FFIEngineError('Error importing cffi'... |
"""
Slovak-language mappings for language-dependent features of
reStructuredText.
"""
__docformat__ = 'reStructuredText'
directives = {
'pozor': 'attention',
'opatrne': 'caution',
'code (translation required)': 'code',
'nebezpe\xe8enstvo': 'danger',
'chyba': 'error',
'rada': 'hint... |
import _add_pooling
from ast import literal_eval
def _get_input_output_name(net, node, index=0):
name = node['name']
inputs = node['inputs']
if index == 'all':
input_name = [_get_node_name(net, inputs[idx][0]) for idx in range(len(inputs))]
elif type(index) == int:
input_name = _get_no... |
"""
Django settings for athena_web project.
Generated by 'django-admin startproject' using Django 1.9.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os... |
from couchpotato.core.event import addEvent
from couchpotato.core.helpers.encoding import toUnicode
from couchpotato.core.helpers.variable import getTitle, splitString
from couchpotato.core.logger import CPLog
from couchpotato.core.plugins.base import Plugin
from couchpotato.core.plugins.score.scores import nameScore, ... |
from openerp.osv import osv
from openerp.report import report_sxw
class payslip_details_report(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(payslip_details_report, self).__init__(cr, uid, name, context)
self.localcontext.update({
'get_details_by_rule_catego... |
from django.test import RequestFactory
from test_plus.test import TestCase
from ..views import (
UserRedirectView,
UserUpdateView
)
class BaseUserTestCase(TestCase):
def setUp(self):
self.user = self.make_user()
self.factory = RequestFactory()
class TestUserRedirectView(BaseUserTestCa... |
from django.http import HttpResponseForbidden
from django.template import Context, Template
from django.conf import settings
# We include the template inline since we need to be able to reliably display
# this error message, especially for the sake of developers, and there isn't any
# other way of making it available ... |
"Thread-safe in-memory cache backend."
import time
try:
import cPickle as pickle
except ImportError:
import pickle
from django.core.cache.backends.base import BaseCache
from django.utils.synch import RWLock
class CacheClass(BaseCache):
def __init__(self, _, params):
BaseCache.__init__(self, param... |
"""Specific, edge-case tests for the MediaFile metadata layer.
"""
import os
import shutil
import _common
from _common import unittest
import beets.mediafile
class EdgeTest(unittest.TestCase):
def test_emptylist(self):
# Some files have an ID3 frame that has a list with no elements.
# This is ver... |
from .base import BaseStore, Pair
from .lock import Lock
from .key import BaseKeyGenerator
from .formatter import FormatterMixin
from .errors import KeyInsertError, TokenInsertError
class MemcacheKeygen(BaseKeyGenerator):
"""\
Creates keys in-memory. Keys are always generated in increasing order.
"""
de... |
"""
This module contains the abbreviation settings dialog and used components.
This dialog allows the user to set and configure abbreviations to trigger scripts and phrases.
"""
import logging
from PyQt5 import QtCore
from PyQt5.QtWidgets import QListWidgetItem, QDialogButtonBox
from autokey.qtui import common as ui... |
"""Record of phased-in incompatible language changes.
Each line is of the form:
FeatureName = "_Feature(" OptionalRelease "," MandatoryRelease ","
CompilerFlag ")"
where, normally, OptionalRelease < MandatoryRelease, and both are 5-tuples
of the same form as sys.version_info:
(... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
################################################################################
# Documentation
################################################################################
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
from __future__ import division
from __future__ import print_function
import sys
sys.path.insert(1, "../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.gam import H2OGeneralizedAdditiveEstimator
from h2o.estimators.glm import H2OGeneralizedLinearEstimator
from h2o.estimators.gbm import H2OGradien... |
# -*- encoding: utf-8 -*-
import web
from web import form
from web.contrib.template import render_mako
import anydbm
from warnings import catch_warnings
web.config.debug = True
render = web.template.render('templates/')
urls = ('/', 'index',
'/pagina1', 'pagina1',
'/pagina2', 'pagina2',
'/pagina3', 'pagina3',
... |
"""
===========================================================
Hierarchical clustering: structured vs unstructured ward
===========================================================
Example builds a swiss roll dataset and runs
hierarchical clustering on their position.
For more information, see :ref:`hierarchical_clus... |
import datetime
import json
import logging
import os
import re
from telemetry import value as value_module
from telemetry.core import util
from telemetry.results import chart_json_output_formatter
from telemetry.results import output_formatter
from telemetry.util import cloud_storage
util.AddDirToPythonPath(util.GetC... |
'''
Created on Aug 22, 2011
@author: hussain.bohra
@author: fabioz
'''
import os
import sys
import unittest
#=======================================================================================================================
# Test
#================================================================================... |
from __future__ import absolute_import
from pyface.tasks.action.task_action import TaskAction
class CommitChangesAction(TaskAction):
name = 'Commit'
method = 'commit_changes'
# ============= EOF ============================================= |
# -*- coding: utf-8 -*-
from __future__ import print_function
import ipywidgets as w
import sys
import re
import os
import fcntl
import collections
import signal
import threading
import subprocess
import select
import time
import shutil
from queue import Queue
from joblib import Memory
import uuid
import glob
color_re... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import hashlib
import os
from pex.interpreter import PythonIdentity, PythonInterpreter
from pants.backend.python.interpreter_cache import PythonInterpreterCache
from... |
"""Tests for tensorflow.python.framework.tensorboard_logging."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import glob
import os
import shutil
import tempfile
import time
import tensorflow.python.platform
import tensorflow as tf
from tensorflow.core... |
import openerp.exceptions
from openerp.tests.common import TransactionCase
class TestRules(TransactionCase):
def setUp(self):
super(TestRules, self).setUp()
self.id1 = self.env['test_access_right.some_obj']\
.create({'val': 1}).id
self.id2 = self.env['test_access_right.some_obj... |
#!/usr/bin/env python3
from collections import defaultdict
from itertools import chain
from pgmpy.models import BayesianModel
from pgmpy.models import MarkovModel
from pgmpy.models import FactorGraph
from pgmpy.models import JunctionTree
from pgmpy.models import DynamicBayesianNetwork
class Inference(object):
"... |
# -*- coding: utf-8 -*-
u"""Useful I/O operations
:copyright: Copyright (c) 2015 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
from pykern import pkconst
import contextlib
import copy
import errno
impo... |
"""
Provides wrappers for various types for binding to Rex. We do not want to bind
object instances directly in Rex, because this would create an indirect
dependency between rex code in package.py files, and versions of Rez.
The classes in this file are intended to have simple interfaces that hide
unnecessary data fro... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.connection i... |
#!/usr/bin/python
''' This Python script interprets interrupt values.
Validates Ideal load balancer runs in same package where workload is running
'''
import os
import sys
LIB_DIR = "%s/lib" % os.path.dirname(__file__)
sys.path.append(LIB_DIR)
from optparse import OptionParser
from sched_mc import *
__author__ = ... |
"""
Defines data types and models required specifically for EVPN support.
"""
import logging
from ryu.lib.packet.bgp import EvpnNLRI
from ryu.lib.packet.bgp import RF_L2_EVPN
from ryu.services.protocols.bgp.info_base.vpn import VpnDest
from ryu.services.protocols.bgp.info_base.vpn import VpnPath
from ryu.services.p... |
import uuid
import mock
from sqlalchemy.orm import exc as sqla_ex
from solum.common import exception
from solum.objects import registry
from solum.objects.sqlalchemy import assembly
from solum.tests import base
from solum.tests import utils
class TestAssembly(base.BaseTestCase):
def setUp(self):
super(T... |
"""Support for control of ElkM1 sensors."""
from . import DOMAIN as ELK_DOMAIN, ElkEntity, create_elk_entities
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Create the Elk-M1 sensor platform."""
if discovery_info is None:
return
elk_datas = hass.data[EL... |
import PyV8
import os
import hashlib
import logging
import socket
import magic
import ssl
try:
import urllib.parse as urlparse
except ImportError:
import urlparse
from .MimeTypes import MimeTypes
from .Plugins import Plugins
from .UserProfile import UserProfile
from .HTTPSession import AboutBlank, FetchForbid... |
import sys
import re
"""Baby Names exercise
Define the extract_names() function below and change main()
to call it.
For writing regex, it's nice to include a copy of the target
text for inspiration.
Here's what the html looks like in the baby.html files:
...
<h3 align="center">Popularity in 1990</h3>
....
<tr align... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
import os
import re
import smtplib
from ansible.module_utils.six import string_types
from ansible.module_utils._text import to_bytes
from ansible.plugins.callback import CallbackBase
class CallbackModule(CallbackBase... |
"""
Defines the abstract base class that all backends should derive from
"""
import abc
class ProctoringBackendProvider(object):
"""
The base abstract class for all proctoring service providers
"""
# don't allow instantiation of this class, it must be subclassed
__metaclass__ = abc.ABCMeta
... |
"""
"PYSTONE" Benchmark Program
Version: Python/1.2 (corresponds to C/1.1 plus 3 Pystone fixes)
Author: Reinhold P. Weicker, CACM Vol 27, No 10, 10/84 pg. 1013.
Translated from ADA to C by Rick Richardson.
Every method to preserve ADA-likeness has been used,
... |
import omero
from omero.plugins.duplicate import DuplicateControl
from omero.testlib.cli import CLITest
import pytest
object_types = ["Image", "Dataset", "Project", "Plate", "Screen"]
model = ["", "I"]
class TestDuplicate(CLITest):
def setup_method(self, method):
super(TestDuplicate, self).setup_method(... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2014 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the... |
import ConfigParser
import importlib
import os
from oslo_config import cfg
from neutron.openstack.common import log as logging
LOG = logging.getLogger(__name__)
class NeutronModules(object):
MODULES = {
'neutron_fwaas': {
'alembic-name': 'fwaas',
},
'neutron_lbaas': {
... |
"""
Implementation of RFC2617: HTTP Digest Authentication
@see: U{http://www.faqs.org/rfcs/rfc2617.html}
"""
from zope.interface import implements
from twisted.cred import credentials
from twisted.web.iweb import ICredentialFactory
class DigestCredentialFactory(object):
"""
Wrapper for L{digest.DigestCredent... |
#!/usr/bin/python
'''Notify-OSD Apport interface
Copyright (C) 2009 Canonical Ltd.
Author: Ara Pulido <<EMAIL>>
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2 of the License, or (... |
import unittest
from unittest import mock
import logging
from pyprint.NullPrinter import NullPrinter
from pyprint.Printer import Printer
from coalib.misc import Constants
from coalib.output.printers.LogPrinter import LogPrinter, LogPrinterMixin
from coalib.processes.communication.LogMessage import LOG_LEVEL, LogMessa... |
'''
Created on 17/05/2012
@author: piranna
'''
try:
from collections import OrderedDict
except ImportError:
OrderedDict = None
if OrderedDict:
class Cache(OrderedDict):
"""Cache with LRU algorithm using an OrderedDict as basis
"""
def __init__(self, maxsize=100):
Orde... |
__author__ = 'hensh'
from django.shortcuts import render_to_response
from django.template import RequestContext
from TaxiService.models import Car, Ride, Driver
from django.http import Http404
from dateutil import parser
from django.shortcuts import redirect
from TaxiService.required_group_test import group_required
... |
import pytest
from .addons import using
from .utils import *
import math
import numpy as np
import qcelemental as qcel
import psi4
from psi4.driver import qcdb
pytestmark = pytest.mark.quick
def hide_test_xtpl_fn_fn_error():
psi4.geometry('He')
with pytest.raises(psi4.UpgradeHelper) as e:
psi4.en... |
# -*- coding: utf-8 -*-
"""
SubRip's subtitle parser
"""
from pysrt.srtexc import InvalidItem, InvalidIndex
from pysrt.srttime import SubRipTime
from pysrt.comparablemixin import ComparableMixin
from pysrt.compat import str, is_py2
import re
class SubRipItem(ComparableMixin):
"""
SubRipItem(index, start, end... |
{
"name" : "Product extension to track sales and purchases",
"version" : "1.0",
"author" : "OpenERP S.A.",
"depends" : ["product", "purchase", "sale", "mrp", "stock_account"],
"category" : "Generic Modules/Inventory Control",
"description": """
Product extension. This module adds:
* Last purch... |
"""
Code generation and import tests.
"""
import sys
from hamcrest import (
assert_that,
calling,
equal_to,
has_properties,
instance_of,
is_,
raises,
)
from jsonschema import ValidationError
from jsonschematypes.registry import Registry
from jsonschematypes.tests.fixtures import NAME, NAME... |
"""SCons.Platform.irix
Platform-specific initialization for SGI IRIX systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# Copyright (c) 2001 - 2015 The SCons Foundation
#
# Permission is here... |
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
import time
sleep_i = 0
firsthtml = Request('http://www.jobkorea.co.kr/Starter/Recruit/SS/engineering?psTab=40&rOrderTab=10&Page=1#JobList', headers={'User-Agent':'Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_fiscal_icflancaracrescimoitem.ui'
#
# by: pyside-uic 0.2.15 running on PySide 1.2.2
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
from pydaruma.pydaruma import iCFLancarAcrescimoItem_ECF_D... |
from __future__ import print_function
import colorsys
import math
import random
import signal
import sys
import time
import threading
import os
import numpy as np
import appleseed as asr
# Initial parameters for generating grid light scene
GridLightsCount = 5
Color = "white"
PlaneSize = 100
RectangleLightSize = 10
o... |
from django.test.client import Client
from django.test import TestCase
from django.core import mail
from nose.tools import eq_
from django.contrib.auth import get_user_model
User = get_user_model()
from amon.apps.alerts.models import alerts_model, alerts_history_model
from amon.apps.servers.models import server_mode... |
#!/usr/bin/env /usr/bin/python3
import math,random
import main
import lang
rand = random.SystemRandom()
R = main.R
@R.add(_(".*\:\s?\/dice\s(\d+)d(\d+)\|?([+|-]?\d+)?\s?(.*)\s?"),"oncommand")
def go_dice(msg):
try:
cont = int(msg["res"].group(1))
rng = int(msg["res"].group(2))
except:
return [(None,msg["from"... |
from django.contrib import admin
from .models import Products, ProductImage, Variation
# Register your models here.
class ProductAdmin(admin.ModelAdmin):
'''
This will be the admin configuration of each individual product that is entered.
With this he will not only be able to search through the products ... |
from unittest import TestCase, main
from scrapy.http import Response, XmlResponse, Request
from scrapy.contrib_exp.downloadermiddleware.decompression import DecompressionMiddleware
from scrapy.spider import BaseSpider
from scrapy.tests import get_testdata
def _test_data(formats):
uncompressed_body = get_testdata(... |
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
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... |
def _name_to_value(name):
val = {'A': 0, 'B': 2, 'C': 3, 'D': 5, 'E': 7, 'F': 8, 'G': 10}
mod = {'#': 1, 'b': -1}
result = val[name[0]] + sum(mod[m] for m in name[1:])
return result % 12
def _value_to_name(value, accidentals='#'):
name = {0: 'A', 2: 'B', 3: 'C', 5: 'D', 7: 'E', 8: 'F', 10: 'G'}
... |
"""
Interface to Constrained Optimization By Linear Approximation
Functions
---------
.. autosummary::
:toctree: generated/
fmin_cobyla
"""
from __future__ import division, print_function, absolute_import
import numpy as np
from scipy._lib.six import callable
from scipy.optimize import _cobyla
from .optimiz... |
"""Sparse DIAgonal format"""
from __future__ import division, print_function, absolute_import
__docformat__ = "restructuredtext en"
__all__ = ['dia_matrix', 'isspmatrix_dia']
import numpy as np
from .base import isspmatrix, _formats, spmatrix
from .data import _data_matrix
from .sputils import (isshape, upcast_cha... |
#!/usr/bin/python
#coding: utf-8 -*-
import time
def increase_pg_count(module, osds, pool_name,
current_pg_count, desired_pg_count):
max_increase_per_pass = osds * 32
diff = desired_pg_count - current_pg_count
while diff > 0:
if diff <= max_increase_per_pass:
cm... |
# -*- coding: utf-8 -*-
"""
Pinyto cloud - A secure cloud database for your personal data
Copyright (C) 2105 Johannes Merkert <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version ... |
from msrest.serialization import Model
class VirtualMachineScaleSetSku(Model):
"""Describes an available virtual machine scale set sku.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar resource_type: The type of resource the sku applies to.
:vartype r... |
from .base import Renderer
class FakeRenderer(Renderer):
"""
Fake Renderer
This is a fake renderer which simply outputs a text tree representing the
elements found in the plot(s). This is used in the unit tests for the
package.
Below are the methods your renderer must implement. You are fre... |
from .phantom import Phantom
from .driver import Driver
import pytest
@pytest.fixture()
def page(request):
driver = Driver(engine='phantomjs', port=3000)
driver.start()
driver.wait_for_ready()
phantom = Phantom(driver=driver)
page = phantom.create_page()
request.addfinalizer(driver.kill)
r... |
"""Support for Sensirion SHT31 temperature and humidity sensor."""
from datetime import timedelta
import logging
import math
from Adafruit_SHT31 import SHT31
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_MONITORED_CONDITIONS,
CONF_... |
""" Test reading of files not conforming to matlab specification
We try and read any file that matlab reads, these files included
"""
from __future__ import division, print_function, absolute_import
from os.path import dirname, join as pjoin
from numpy.testing import assert_
from pytest import raises as assert_raise... |
import re
import os
import warnings
# List of validations
# Validate config file function
# Validate populate input (just pull from the validations at start of populate
def validate_input(config, shell_xls, output_xls):
if not os.path.isfile(config):
raise ValueError("Config not found, make sure your pat... |
from __future__ import unicode_literals
from datetime import date
from django.test import TestCase
from .models import Article
class MethodsTests(TestCase):
def test_custom_methods(self):
a = Article.objects.create(
headline="Area man programs in Python", pub_date=date(2005, 7, 27)
... |
"""
This module is responsible for setting up the part of a pycbc workflow that
will generate the injection files to be used for assessing the workflow's
ability to detect predicted signals. (In ihope parlance, this sets up the
inspinj jobs). Full documentation for this module can be found here:
https://ldas-jobs.ligo.... |
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import tabs
from openstack_dashboard import api
class OverviewTab(tabs.Tab):
name = _("Overview")
slug = "overview"
template_name = "project/networks/ports/_det... |
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
# Let snippet from module_utils/basic.py return a proper error in this case
pass
import base64
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
... |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
import pytest
@pytest.mark.usefixtures('tmpdir')
class TestTorrentSize(object):
config = """
tasks:
test_min:
mock:
- {tit... |
from __future__ import unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
class RESTFrameworkModel(models.Model):
"""
Base for test models that sets app_label, so they play nicely.
"""
class Meta:
app_label = 'tests'
abstract = True
... |
"""
Copyright (c) 2016-2017 Dell Inc. or its subsidiaries. All Rights Reserved.
"""
import fit_path # NOQA: unused import
import unittest
import flogging
from config.redfish1_0_config import config
from on_http_redfish_1_0 impor... |
"""Tests and Benchmarks for Densenet model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gc
import time
import tensorflow as tf
import tensorflow.contrib.eager as tfe
from tensorflow.contrib.eager.python.examples.densenet import densenet
from ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.