content stringlengths 4 20k |
|---|
"""
=========================================================
Comparing different clustering algorithms on toy datasets
=========================================================
This example aims at showing characteristics of different
clustering algorithms on datasets that are "interesting"
but still in 2D. The last ... |
"""
The :mod:`sklearn.metrics.scorer` submodule implements a flexible
interface for model selection and evaluation using
arbitrary score functions.
A scorer object is a callable that can be passed to
:class:`sklearn.model_selection.GridSearchCV` or
:func:`sklearn.model_selection.cross_val_score` as the ``scoring``
par... |
from oslo_concurrency import lockutils
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import timeutils
import six
from neutron.db import agentschedulers_db
from neutron.extensions import agent as ext_agent
from networking_cisco._i18n import _, _LI
from networking_cisco import backward... |
# -*- coding: utf-8 -*-
from django import forms
from django.forms import ValidationError
from django.utils.translation import ugettext_lazy as _
from moocng.externalapps.models import ExternalApp
from moocng.forms import BootstrapMixin
class ExternalAppForm(forms.ModelForm, BootstrapMixin):
error_messages = {
... |
from __future__ import unicode_literals
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'j E Y г.'
TIME_FORMAT = 'G:i'
DATETIME_FORMAT = 'j E Y г. G:i'
YEAR_MONTH_FORMAT = 'F Y г.'
MONTH_DAY_FORMAT = 'j F'
SHORT_DATE_FORMAT... |
"""
Copyright (C) 2009-2012 Oracle Corporation
This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free software;
you can redistribute it and/or modify it under the terms of the GNU
General Public License (GPL) as published by the Free Software
Foundatio... |
from django import template
from django.utils import safestring
import hashlib
register = template.Library()
@register.tag(name="textile")
def textileParser(parser, token):
nodelist = parser.parse(('endtextile',))
parser.delete_first_token()
return TextileNode(nodelist)
class TextileNode(template.Node):... |
"""
Template tags and helper functions for displaying breadcrumbs in page titles
based on the current micro site.
"""
from django import template
from django.conf import settings
from microsite_configuration import microsite
from django.templatetags.static import static
register = template.Library()
def page_title_b... |
"""
ovirt external inventory script
=================================
Generates inventory that Ansible can understand by making API requests to
oVirt via the ovirt-engine-sdk-python library.
When run against a specific host, this script returns the following variables
based on the data obtained from the ovirt_sdk Nod... |
"""
Identity v2 authorization plugins. The plugin must be constructed with an
auhorization URL and a user id, user name or token. A user id or user name
would also require a password. For example::
from openstack.auth.identity import v2
from openstack import transport
args = {
'password': 'openS... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
################################################################################
# Documentation
################################################################################
ANSIBLE_METADATA = {'metadata_version': '1.1', 'statu... |
#
from .base import *
from .standard import *
from .extended import *
def is_lbtype(type_obj, object_only = False):
""" Verify if type_obj is an instance of lbtype
If object_only is false, return also true if the class
descend from lbtype
"""
if not object_only and isinstance(type_obj, type... |
import unittest
import imath
import inspect
import IECore
import Gaffer
import GafferScene
import GafferSceneTest
class SceneLoopTest( GafferSceneTest.SceneTestCase ) :
def testLoop( self ) :
script = Gaffer.ScriptNode()
script["sphere"] = GafferScene.Sphere()
script["loop"] = Gaffer.Loop()
script["loop"... |
"""
To run this, you'll need to have installed.
* glmnet-python
* scikit-learn (of course)
Does two benchmarks
First, we fix a training set and increase the number of
samples. Then we plot the computation time as function of
the number of samples.
In the second benchmark, we increase the number of dimensions of... |
from django.db import transaction
from django.contrib.auth import get_user_model
from report_builder.models import Report, DisplayField, FilterField, Format
from rest_framework import serializers
import datetime
User = get_user_model()
class FormatSerializer(serializers.ModelSerializer):
class Meta:
mode... |
from django.http import HttpResponse
from django.test import RequestFactory, SimpleTestCase
from django.test.utils import override_settings
class SecurityMiddlewareTest(SimpleTestCase):
@property
def middleware(self):
from django.middleware.security import SecurityMiddleware
return SecurityMid... |
import bisect
import fnmatch
import os
from os.path import isdir, isfile, join, basename, splitext
from django.conf import settings
# Use the built-in version of scandir/walk if possible, otherwise
# use the scandir module version
try:
from os import scandir, walk
except ImportError:
from scandir import scandi... |
"""Tests for the CherryPy configuration system."""
import os
import sys
localDir = os.path.join(os.getcwd(), os.path.dirname(__file__))
import socket
import time
import cherrypy
# Client-side code #
from cherrypy.test import helper
class ServerConfigTests(h... |
# -*- coding: utf-8 -*-
"""
AR-specific Form helpers.
"""
from __future__ import absolute_import, unicode_literals
from django.contrib.localflavor.ar.ar_provinces import PROVINCE_CHOICES
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import RegexField... |
"""
Decorators to wrap functions to make them WSGI applications.
The main decorator :class:`wsgify` turns a function into a WSGI
application (while also allowing normal calling of the method with an
instantiated request).
"""
from webob.compat import (
bytes_,
text_type,
)
from webob.request import Reque... |
from odoo import api, fields, models, _
from odoo.exceptions import UserError
class StockPickingWave(models.Model):
_inherit = "mail.thread"
_name = "stock.picking.wave"
_description = "Picking Wave"
_order = "name desc"
name = fields.Char(
string='Picking Wave Name', default='/',
... |
"""
This module contains functions and methods to authenticate with OAuth1
providers.
"""
__revision__ = \
"$Id$"
from invenio.containerutils import get_substructure
from invenio.dbquery import run_sql
from invenio.external_authentication import ExternalAuth
class ExternalOAuth1(ExternalAuth):
"""
Contai... |
"""Base script for doing test setup."""
import logging
import os
from pylib import constants
from pylib import valgrind_tools
from pylib.utils import isolator
def GenerateDepsDirUsingIsolate(suite_name, isolate_file_path,
isolate_file_paths, deps_exclusion_list):
"""Generate the dep... |
#
# iso2022_jp_ext.py: Python Unicode Codec for ISO2022_JP_EXT
#
# Written by Hye-Shik Chang <<EMAIL>>
#
import _codecs_iso2022, codecs
import _multibytecodec as mbc
codec = _codecs_iso2022.getcodec('iso2022_jp_ext')
class Codec(codecs.Codec):
encode = codec.encode
decode = codec.decode
class IncrementalEnc... |
"""
Very similar to the Django Paginator class, but easier to work with
when you don't have the full object list.
"""
from django.db.models import query
import django.core.paginator
class Paginator(django.core.paginator.Paginator):
"""
Override certain methods of the Django Paginator to allow a partial object lis... |
import boxm_batch;
import os;
boxm_batch.register_processes();
boxm_batch.register_datatypes();
class dbvalue:
def __init__(self, index, type):
self.id = index # unsigned integer
self.type = type # string
# Capitol
model_dir = "/Users/isa/Experiments/CapitolBOXM";
model_imgs_dir = "/Users/isa/Experime... |
"""Backend-independent tests for the Python XLA client."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import unittest
from absl.testing import absltest
import numpy as np
from tensorflow.compiler.xla.python import xla_client
# pylint: disable=g-impo... |
from __future__ import absolute_import
from __future__ import unicode_literals
import copy
from getpass import getuser
from string import ascii_letters
from PyQt4.QtGui import QDialog
from PyQt4.QtGui import QGridLayout
from PyQt4.QtGui import QVBoxLayout
from PyQt4.QtGui import QHBoxLayout
from PyQt4.QtGui import QS... |
import unittest
from iobeam.resources import data
class TestTimestamp(unittest.TestCase):
def test_invalidValues(self):
def verify(val):
try:
ts = data.Timestamp(val)
self.assertTrue(False)
except ValueError:
pass
verify(No... |
# -*- coding: utf-8 -*-
import os, sys
from PyQt4 import QtGui
from Ui_conf import Ui_Dialog as ConfDialog
if hasattr(sys, 'frozen'):
PATH = os.path.join(os.path.abspath(os.path.dirname(sys.executable)),'plugins')
else:
PATH = os.path.abspath(os.path.dirname(__file__))
class ConfigDialog(QtGui.QDialog):
... |
'''
This module provides various assertion functions used by kitty,
not that important, but makes the life easier.
Useful for making assertions that throw :class:`~kitty.core.KittyException`
'''
from kitty.core import KittyException
import types
def is_of_types(obj, the_types):
'''
:param obj: object to asser... |
import cherrypy
# 這是 C2G1 類別的定義
class C2G1(object):
# 各組利用 index 引導隨後的程式執行
@cherrypy.expose
def index(self, *args, **kwargs):
outstring = '''
這是 2014C2 協同專案下的 c2g1 分組程式開發網頁, 以下為 W12 的任務執行內容.<br />
<!-- 這裡採用相對連結, 而非網址的絕對連結 (這一段為 html 註解) -->
<a href="fillpoly">c2g1 fillpoly 繪圖</a><br />
<a href="dra... |
# -*- coding: utf-8 -*-
"""
pygments.filters
~~~~~~~~~~~~~~~~
Module containing filter lookup functions and default
filters.
:copyright: 2006-2007 by Armin Ronacher, Georg Brandl.
:license: BSD, see LICENSE for more details.
"""
try:
set
except NameError:
from sets import Set as set
i... |
from robograph.datamodel.base import graph
from robograph.datamodel.nodes import plotter
from robograph.datamodel.nodes.lib import value, printer, buffers, maths
def plot():
v1 = value.Value(value=[9, -3, 8.7], name='v1')
v2 = value.Value(value=[86, -0.43], name='v2')
s = maths.Sum(name='sum')
m = mat... |
"""Tests for the 'setuptools' package"""
import sys
import os
import distutils.core
import distutils.cmd
from distutils.errors import DistutilsOptionError, DistutilsPlatformError
from distutils.errors import DistutilsSetupError
from distutils.core import Extension
from distutils.version import LooseVersion
from setupto... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import six
import binascii
import io
import os
from binascii import hexlify
from nose.plugins.skip import SkipTest
from ansible.compat.tests import unittest
from ansible import errors
from ansible.parsing.vault import VaultLib
... |
from unittest import TestCase
from src.Piloto import Piloto
from src.Escuderia import Escuderia
from src.CampeonatoMundial import CampeonatoMundial
from src.Circuito import Circuito
from src.GranPremio import GranPremio
from src.Formula1 import Formula1
from mockito import *
__author__ = 'MAMISHO'
class TestFormula1... |
import unittest
from selenium.webdriver.common.proxy import Proxy, ProxyType
class ProxyTests(unittest.TestCase):
MANUAL_PROXY = {
'httpProxy': 'some.url:1234',
'ftpProxy': 'ftp.proxy',
'noProxy': 'localhost, foo.localhost',
'sslProxy': 'ssl.proxy:1234',
'socksProxy': 'sock... |
# 149. Max Points on a Line QuestionEditorial Solution My Submissions
# Total Accepted: 69049
# Total Submissions: 450757
# Difficulty: Hard
# Contributors: Admin
# Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
#
# Subscribe to see which companies asked this que... |
from PIL import Image
from os import listdir, walk
from os.path import isfile, join
import shutil
if __name__ == '__main__':
srcFolder = "/home/prasanna/workspace_ram/dataset/lowes/label_training/big_blue_box/src/test/";
dst = "/home/prasanna/workspace_ram/dataset/lowes/label_training/big_blue_box/src/test_r... |
from django.db import models
class Garden(models.Model):
name = models.CharField(max_length=100)
area = models.IntegerField()
raining = models.BooleanField()
@property
def howbig(self):
if self.area < 50:
return 'small'
elif self.area < 150:
return 'medium'... |
# -*- coding: utf-8 -*-
"""
requests.adapters
~~~~~~~~~~~~~~~~~
This module contains the transport adapters that Requests uses to define
and maintain connections.
"""
import socket
from .models import Response
from .packages.urllib3 import Retry
from .packages.urllib3.poolmanager import PoolManager, proxy_from_url
... |
from oslo_log import log
import testtools
from tempest import config
from tempest.scenario import manager
from tempest import test
CONF = config.CONF
LOG = log.getLogger(__name__)
class TestSnapshotPattern(manager.ScenarioTest):
"""
This test is for snapshotting an instance and booting with it.
The fol... |
#!/usr/bin/env python
"""
Test code for the BBox Object
"""
import unittest
from BBox import *
class testCreator(unittest.TestCase):
def testCreates(self):
B = BBox(((0,0),(5,5)))
self.failUnless(isinstance(B, BBox))
def testType(self):
B = N.array(((0,0),(5,5)))... |
"""Hooks helper to return a list of TensorFlow hooks for training by name.
More hooks can be added to this set. To add a new hook, 1) add the new hook to
the registry in HOOKS, 2) add a corresponding function that parses out necessary
parameters.
"""
from __future__ import absolute_import
from __future__ import divis... |
import wx
class Popup(wx.PopupTransientWindow):
'''mfc1.Popup(parent, style, text, font, colors, icon)
Show the text notification for the MindfulClock.
parent = wx.window
style = wx.SIMPLE_BORDER, wx.RAISED_BORDER, wx.SUNKEN_BORDER,
wx.NO_BORDER
text = 'notification text... |
from flask import request, session, g, redirect, url_for, abort, render_template, flash
from flask.views import MethodView
from models import User,KeyingTask, KeyingAnswer
import cache_methods
cache = cache_methods.cache
from database import db_session
class KeyerView(MethodView):
'''
This class displays... |
import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
TestCommand.initialize_options(self)
self.pytest_args = ['tests']
... |
# -*- coding: utf-8 -*-
from odoo import api, fields, models
from odoo.addons import account
import logging
_logger = logging.getLogger(__name__)
class FakeDict(dict):
def __init__(self, orig_dict={}):
super(FakeDict, self).__init__(orig_dict)
def __getitem__(self, key):
try:
... |
from threading import Semaphore
from unittest.case import SkipTest
from batchy.runloop import coro_return, runloop_coroutine
from batchy.batch_coroutine import batch_coroutine, class_batch_coroutine
try:
from concurrent.futures import ThreadPoolExecutor
import batchy.futures as batchy_futures
except ImportEr... |
import os
from nose.plugins.skip import SkipTest
from theano import config
import pylearn2
from pylearn2.testing import no_debug_mode
from pylearn2.utils.serial import load_train_file
@no_debug_mode
def test_train_example():
""" tests that the grbm_smd example script runs correctly """
assert config.mode !... |
"""Helper methods for creating & verifying XSRF tokens."""
__authors__ = [
'"Doug Coker" <<EMAIL>>',
'"Joe Gregorio" <<EMAIL>>',
]
import base64
import hmac
import os # for urandom
import time
from oauth2client import util
# Delimiter character
DELIMITER = ':'
# 1 hour in seconds
DEFAULT_TIMEOUT_SECS = 1*60... |
import numpy as np
# Define the boundary-type codes
#: Indicates a node is *core*.
CORE_NODE = 0
#: Indicates a boundary node is has a fixed values.
FIXED_VALUE_BOUNDARY = 1
#: Indicates a boundary node is has a fixed gradient.
FIXED_GRADIENT_BOUNDARY = 2
#: Indicates a boundary node is wrap-around.
TRACKS_CELL_BO... |
"""Copyright (C) 2013 COLDWELL AG
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 of the License, or
(at your option) any later version.
This program is distributed in the hope that... |
"""Debounce helper."""
from __future__ import annotations
import asyncio
from logging import Logger
from typing import Any, Awaitable, Callable
from homeassistant.core import HassJob, HomeAssistant, callback
class Debouncer:
"""Class to rate limit calls to a specific command."""
def __init__(
self,... |
from glob import glob
from distutils.util import convert_path
import distutils.command.build_py as orig
import os
import sys
import fnmatch
import textwrap
try:
from setuptools.lib2to3_ex import Mixin2to3
except ImportError:
class Mixin2to3:
def run_2to3(self, files, doctests=True):
"do not... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import base64
import json
import os
import pkgutil
import random
import re
from distutils.version import LooseVersion
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.module_utils._text impo... |
#-*- coding: utf-8 -*-
from django import forms
from django.contrib.admin import widgets
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django.te... |
import os
from setuptools import find_packages
from setuptools import setup
f = open(os.path.join(os.path.dirname(__file__), 'README.rst'))
readme = f.read()
f.close()
try:
from Cython.Build import cythonize
except ImportError:
ext_modules = None
else:
ext_modules = cythonize('playhouse/speedups.pyx')
se... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import re
import time
import glob
from ansible.plugins.action.junos import ActionModule as _ActionModule
from ansible.module_utils._text import to_text
from ansible.module_utils.six.moves.urllib.parse import urlsplit
fro... |
import os
import time
#SERVOD_PATH='/home/pi/ServoBlaster1/user/servod'
#SERVOD_PATH='/usr/local/sbin/servod'
SERVOD_PATH='/usr/sbin/pi-blaster'
SERVO_ANGLE = 0
SERVO_CONTINUOUS = 1
class Servo(object):
"""A Servo instance controls a single servo
Parameters
----------
pin : int
GPIO pin numbe... |
from django.contrib import admin
from cs_courses import models
@admin.register(models.Course)
class CourseAdmin(admin.ModelAdmin):
# Inline models
class TimeSlotInline(admin.TabularInline):
model = models.TimeSlot
extra = 0
classes = ('collapse',)
class LessonInline(admin.TabularI... |
{
"name": "IPA Code (IndicePA)",
"version": "8.0.1.0.0",
"category": "Localisation/Italy",
"author": "KTec S.r.l, Odoo Community Association (OCA)",
"website": "http://www.ktec.it",
"license": "AGPL-3",
"depends": ['base'],
"data": [
'view/partner_view.xml',
],
"qweb": []... |
from django.db import models
CHOICES = (
(1, 'first'),
(2, 'second'),
)
class Article(models.Model):
headline = models.CharField(max_length=100, default='Default headline')
pub_date = models.DateTimeField()
status = models.IntegerField(blank=True, null=True, choices=CHOICES)
misc_data = model... |
"""Decorator that provides a warning if the wrapped object is never used."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import functools
import itertools
import traceback
import types
import six # pylint: disable=unused-import
from... |
""" sending OSC with pyOSC
https://trac.v2.nl/wiki/pyOSC
example by www.ixi-audio.net based on pyOSC documentation
"""
import OSC
import time, random
"""
note that if there is nobody listening in the other end we get an error like this
OSC.OSCClientError: while sending: [Errno 111] Connection refused
so we need ... |
#! /usr/bin/env python
import sys
import ddlib # DeepDive python utility
ARR_DELIM = '~^~'
# For each input tuple
for row in sys.stdin:
parts = row.strip().split('\t')
if len(parts) != 6:
print >>sys.stderr, 'Failed to parse row:', row
continue
# Get all fields from a row
words = parts[0].split(... |
import unittest
from test import support
from ctypes import *
import _ctypes_test
lib = CDLL(_ctypes_test.__file__)
class StringPtrTestCase(unittest.TestCase):
@support.refcount_test
def test__POINTER_c_char(self):
class X(Structure):
_fields_ = [("str", POINTER(c_char))]
x = X()... |
import sys, string
import os.path
import unique
import export
dirfile = unique
############ File Import Functions #############
def filepath(filename):
fn = unique.filepath(filename)
return fn
def read_directory(sub_dir):
dir_list = unique.read_directory(sub_dir)
#add in code to prevent f... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import importlib
import unittest
from django.core import management, serializers
from django.core.serializers.base import DeserializationError
from django.test import SimpleTestCase, TestCase, TransactionTestCase
from django.utils import six
from django.... |
from __future__ import absolute_import, division, unicode_literals
import re
from xml.sax.saxutils import escape, unescape
from six.moves import urllib_parse as urlparse
from .tokenizer import HTMLTokenizer
from .constants import tokenTypes
content_type_rgx = re.compile(r'''
^
... |
"""
Authorization module that allow users listed in
/etc/cobbler/users.conf to be permitted to access resources, with
the further restriction that cobbler objects can be edited to only
allow certain users/groups to access those specific objects.
Copyright 2008, Red Hat, Inc
Michael DeHaan <<EMAIL>>
This software may ... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
from ansible.module_utils.network.nxos.nxos import load_config, run_commands
from ansible.module_utils.network.nxos.nxos import nxos_argument_spec, check_args
from ansible.module_ut... |
'''
Copyright (c) 2016-2017 Dell Inc. or its subsidiaries. All Rights Reserved.
Author(s):
'''
import fit_path # NOQA: unused import
import json
import fit_common
import flogging
from on_http_api2_0 import ApiApi as Api
from on_http_api2_0.rest import ApiException
from config.api2_0_config import config
from datetim... |
from sahara import exceptions as ex
from sahara.i18n import _
from sahara.service.api import v10 as api
import sahara.service.validations.base as b
from sahara.service.validations import shares
def check_node_group_template_create(data, **kwargs):
plugin_version = 'hadoop_version'
if data.get('plugin_version'... |
import click
import os
from defusedxml import ElementTree as etree
import jinja2
property_file_name = '.property.yml'
property_template_dir = 'hack/templates'
property_template_file_name = 'property_template.jinja'
class Migrator(object):
def __init__(self, input_dir, output_dir):
self.input_dir = input_d... |
"""Testing extensions.
this module is designed to work as a testing-framework-agnostic library,
so that we can continue to support nose and also begin adding new
functionality via py.test.
NOTE: copied/adapted from SQLAlchemy master for backwards compatibility;
this should be removable when Alembic targets SQLAlchem... |
"""
ROS Service Description Language Spec
Implements http://ros.org/wiki/srv
"""
import os
import sys
from . names import is_legal_resource_name, is_legal_resource_base_name, package_resource_name, resource_name
class SrvSpec(object):
def __init__(self, request, response, text, full_name = '', short_name = ... |
"""
Blowfish Encryption
This module is a pure python implementation of Bruce Schneier's
encryption scheme 'Blowfish'. Blowish is a 16-round Feistel Network
cipher and offers substantial speed gains over DES.
The key is a string of length anywhere between 64 and 448 bits, or
equivalently 8 and 56 bytes. The encryption... |
"""Unit tests to cover Basic Operations examples."""
__author__ = '<EMAIL> (Kevin Winter)'
import os
import sys
sys.path.insert(0, os.path.join('..', '..', '..', '..'))
import time
import unittest
from examples.adspygoogle.adwords.v201309.basic_operations import add_ad_groups
from examples.adspygoogle.adwords.v20130... |
from pyspark.ml.feature import VectorSlicer
from pyspark.ml.linalg import Vectors
from pyspark.sql.types import Row
# $example off$
from pyspark.sql import SparkSession
if __name__ == "__main__":
spark = SparkSession\
.builder\
.appName("VectorSlicerExample")\
.getOrCreate()
# $example... |
import unittest
import os
import arkimet as arki
import datetime
class TestScanODIMH5(unittest.TestCase):
def read(self, pathname, size, format="odimh5"):
"""
Read all the metadata from a file
"""
ds = arki.dataset.Reader({
"format": format,
"name": os.path.... |
from django.conf import settings
from django.contrib.sites.models import Site
from django.contrib.auth.decorators import login_required, \
permission_required
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.template.context import ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# ===========================================================================
# iDevice Orientaciones tutoria creado para la FPD por José Ramón Jiménez Reyes
# ===========================================================================
"""
FPD - Guidelines Teacher
Orientaciones... |
#!/usr/bin/env python3
import json
import os
from wsgiref.handlers import CGIHandler
from philologic.runtime.DB import DB
from philologic.runtime.Query import split_terms
from philologic.runtime.QuerySyntax import group_terms, parse_query
import sys
sys.path.append("..")
import custom_functions
try:
from custo... |
"""Test lazymod.py"""
import sys
import unittest
from capa.safe_exec.lazymod import LazyModule
class ModuleIsolation(object):
"""
Manage changes to sys.modules so that we can roll back imported modules.
Create this object, it will snapshot the currently imported modules. When
you call `clean_up()`,... |
from __future__ import unicode_literals
from django.apps import apps
from django.conf import settings
from django.db import connection
from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
from .models.tablespaces import (
Article, ArticleRef, Authors, Reviewers, Scientist, ScientistRef,
)
def ... |
from __future__ import unicode_literals
from django.contrib.gis.geos import HAS_GEOS
from django.contrib.gis.tests.utils import no_oracle
from django.db import connection
from django.test import TestCase, skipUnlessDBFeature
from django.test.utils import override_settings
from django.utils import timezone
if HAS_GEOS... |
from feedly.tests.feeds.base import TestBaseFeed, implementation
import pytest
from feedly.feeds.cassandra import CassandraFeed
from feedly.utils import datetime_to_epoch
from feedly.activity import Activity
class CustomActivity(Activity):
@property
def serialization_id(self):
'''
Shorter ser... |
from __future__ import unicode_literals
from prompt_toolkit.validation import Validator, ValidationError
from six import string_types
class SentenceValidator(Validator):
"""
Validate input only when it appears in this list of sentences.
:param sentences: List of sentences.
:param ignore_case: If True... |
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion,
# linux, chromeos, android
#
# GPU vendors:
# amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm,
# vivante
#
#... |
"""Expands CMake variables in a text file."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
import sys
_CMAKE_DEFINE_REGEX = re.compile(r"\s*#cmakedefine\s+([A-Za-z_0-9]*)(\s.*)?$")
_CMAKE_DEFINE01_REGEX = re.compile(r"\s*#cmakedefine01\s+([A-Z... |
from openerp import models, api, exceptions, _
class AccountMove(models.Model):
_inherit = "account.move"
@api.constrains('journal_id', 'period_id', 'date')
def _check_fiscal_year(self):
for move in self:
if move.journal_id.allow_date_fy:
date_start = move.period_id.fi... |
from __future__ import absolute_import
from collections import defaultdict
from vdsm.network import tc
NON_VLANNED_ID = 5000
DEFAULT_CLASSID = '%x' % NON_VLANNED_ID
def report_network_qos(nets_info, devs_info):
"""Augment netinfo information with QoS data for the engine"""
qdiscs = defaultdict(list)
fo... |
import logging
import time
from future import Future
from url_fetcher import UrlFetcher
from urllib2 import urlopen, Request, HTTPError
class UrlFetcherUrllib2(UrlFetcher):
"""UrlFetcher implementation for use outside of AppEngine. Does NOT support
async fetching, so FetchAsync calls are still blocking.
"""
... |
"""Test LRUCache by running different input batch sizes on same network."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.compiler.tensorrt.test import tf_trt_integration_test_base as trt_test
from tensorflow.pyt... |
"""
Module for abstract serializer/unserializer base classes.
"""
from django.db import models
from django.utils import six
class SerializerDoesNotExist(KeyError):
"""The requested serializer was not found."""
pass
class SerializationError(Exception):
"""Something bad happened during serialization."""
... |
"""
Replaces the use of python-gssapi with pykerberos in ldap3.
"""
from __future__ import absolute_import
import socket
import base64
import kerberos
from ldap3.core.exceptions import LDAPCommunicationError
from ldap3.protocol.sasl.sasl import send_sasl_negotiation
from ldap3.protocol.sasl.sasl import abort_sasl_neg... |
from __future__ import unicode_literals
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'j N Y'
DATETIME_FORMAT = "j N Y, G.i"
TIME_FORMAT = 'G.i'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'j F'
SHORT_DATE_FORMAT = 'd-m-... |
import collections
import hashlib
import random
import sys
import threading
random.seed(917) # Predictable random numbers for regression testing
Reading = collections.namedtuple("Reading", "when reading reason username")
class Error(Exception): pass
class ThreadSafeDict:
def __init__(self, *a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.