content
string
""" Digraph class """ # Imports from graph import * from graph.algorithms import filters class digraph (object): """ Digraph class. Digraphs are built of nodes and directed edges. @sort: __init__, __getitem__, __iter__, __len__, __str__, add_edge, add_edge_attribute, add_graph, add_node, ad...
import subprocess import logging.config import logging import argparse import sys import os import uuid import zipfile import time # constants # id = os.urandom(10) id = str(uuid.uuid4()) gdalContour = r'/usr/bin/gdal_contour' dst = r'contour_'+id[:13] src = '%s/../../../resource_dir/srtm_39_04/srtm_39_04_c.tif' % os....
# -*- coding: utf-8 -*- """ This module provides two different way to access Wikidata: * Through the Wikimedia API with ``Pywikibot`` as a wrapper * Over a scraper using ``BeautifulSoup4`` Currently, accessing the data via the API is faster than the scraper. """ # STD import abc import hashlib import thre...
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. F Y.' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. F Y. H:i' YEAR_MONTH_FORMAT = 'F Y.' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = ...
from oslo_log import helpers as log_helpers from neutron.services.metering.drivers import abstract_driver class NoopMeteringDriver(abstract_driver.MeteringAbstractDriver): @log_helpers.log_method_call def update_routers(self, context, routers): pass @log_helpers.log_method_call def remove_r...
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.or...
import sys import re import functools import distutils.core import distutils.errors import distutils.extension from .dist import _get_unpatched from . import msvc9_support _Extension = _get_unpatched(distutils.core.Extension) msvc9_support.patch_for_specialized_compiler() def _have_cython(): """ Return True...
import pytest import numpy as np from ..census_helpers import Census from .. import categorizer as cat @pytest.fixture def c(): return Census("827402c2958dcf515e4480b7b2bb93d1025f9389") @pytest.fixture def acs_data(c): population = ['B01001_001E'] sex = ['B01001_002E', 'B01001_026E'] race = ['B02001...
from contextlib import contextmanager from edge.models.fragment import Fragment class Genome_Updater(object): """ Mixin with helpers for updating genome. """ @contextmanager def annotate_fragment_by_name(self, name): f = [x for x in self.fragments.all() if x.name == name] if len(f...
""" Convenience routines for creating non-trivial Field subclasses, as well as backwards compatibility utilities. Add SubfieldBase as the __metaclass__ for your Field subclass, implement to_python() and the other necessary methods and everything will work seamlessly. """ from inspect import getargspec from warnings i...
"""Tests for Incremental PCA.""" import numpy as np from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_raises from sklearn import datasets from sklearn.decomposition import PCA, IncrementalPCA iris = datasets.load...
""" Support for 64 bit Linux systems. @author: Michael Cohen @license: GNU General Public License 2.0 @contact: <EMAIL> """ from volatility import obj class VolatilityDTB(obj.VolatilityMagic): """A scanner for DTB values.""" def generate_suggestions(self): """Tries to locate the DTB."...
import time from datetime import datetime from dateutil.relativedelta import relativedelta from operator import itemgetter from openerp.osv import fields, osv import openerp.addons.decimal_precision as dp from openerp.tools.translate import _ # --------------------------------------------------------- # Account Finan...
"""Tests that the IPython printing module is properly loaded. """ from sympy.core.compatibility import u from sympy.interactive.session import init_ipython_session from sympy.external import import_module from sympy.utilities.pytest import raises # run_cell was added in IPython 0.11 ipython = import_module("IPython",...
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.k8s.raw import KubernetesRawModule def main(): KubernetesRa...
# encoding: utf-8 from south.v2 import DataMigration class Migration(DataMigration): depends_on = (('socialaccount', '0002_genericmodels'),) def forwards(self, orm): # Migrate FB apps app_id_to_sapp = {} for app in orm.FacebookApp.objects.all(): sapp = orm['socialaccount.S...
#!/usr/bin/env python ''' Generic Assimilator framework ''' import os, re, signal, sys, time, hashlib import boinc_path_config from Boinc import database, boinc_db, boinc_project_path, configxml, sched_messages # Peter Norvig's Abstract base class hack def abstract(): """ This function is not necessary, but p...
from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation class PostGISCreation(DatabaseCreation): geom_index_type = 'GIST' geom_index_ops = 'GIST_GEOMETRY_OPS' geom_index_ops_nd = 'GIST_GEOMETRY_OPS_ND' def sql_indexes_for_field(self, model, f, style): "Return any spatial ...
import os from Components.config import config from Tools.Directories import pathExists, fileExists from Plugins.Plugin import PluginDescriptor from Components.Harddisk import harddiskmanager detected_DVD = None def main(session, **kwargs): from Screens import DVD session.open(DVD.DVDPlayer) def play(session, **kw...
import json import logging from django.core.urlresolvers import reverse_lazy from django.http import HttpResponse # noqa from django.utils.translation import ugettext_lazy as _ import django.views from horizon import exceptions from horizon import forms from horizon import tabs from horizon.utils import csvbase fro...
def gen_cmake_command(config): """ Generate CMake command. """ from autocmake.extract import extract_list s = [] s.append("\n\ndef gen_cmake_command(options, arguments):") s.append(' """') s.append(" Generate CMake command based on options and arguments.") s.append(' """') ...
""" mbed CMSIS-DAP debugger Copyright (c) 2006-2013 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable ...
import numbers import typing as tp # NOQA import typing_extensions as tpe # NOQA try: from typing import TYPE_CHECKING # NOQA except ImportError: # typing.TYPE_CHECKING doesn't exist before Python 3.5.2 TYPE_CHECKING = False # import chainer modules only for type checkers to avoid circular import if TY...
from django.conf import settings from django.contrib import messages from django.core.urlresolvers import reverse from django.db.models import Q from django.shortcuts import redirect from django.utils.translation import ugettext_lazy as _ from django.views.generic import ( DeleteView, DetailView, FormView, ListView...
# This file is part of CherryPy <http://www.cherrypy.org/> # -*- coding: utf-8 -*- # vim:ts=4:sw=4:expandtab:fileencoding=utf-8 import cherrypy from cherrypy.lib import auth_digest from cherrypy.test import helper class DigestAuthTest(helper.CPWebCase): def setup_server(): class Root: def i...
class DictDiff: """ Represents the difference between two dictionaries """ __slots__ = ('added', 'removed', 'intersection', 'changed', 'unchanged') def __init__(self, added, removed, intersection, changed, unchanged): self.added = added """ `set` ( `mixed` ) : Keys that were...
import sys import time import argparse import traceback from pyndn import Interest from pyndn import Name from pyndn import Face class Consumer(object): '''Sends Interest, listens for data''' def __init__(self, prefix, pipeline, count): self.prefix = prefix self.pipeline = pipeline s...
from __future__ import division, absolute_import, print_function from numpy.testing import assert_, assert_allclose, assert_equal from pytest import raises as assert_raises import numpy as np from scipy.sparse.linalg import LinearOperator from scipy.optimize._lsq.common import ( step_size_to_bound, find_active_co...
from __future__ import absolute_import import os.path import tempfile from pip.utils import rmtree class BuildDirectory(object): def __init__(self, name=None, delete=None): # If we were not given an explicit directory, and we were not given an # explicit delete option, then we'll default to del...
''' Various helpers for interface files. ''' from settings import * from policies import * from declarations import * #============================================================================== # FunctionWrapper #============================================================================== class FunctionWrapper(...
""" Python 'hex_codec' Codec - 2-digit hex content transfer encoding Unlike most of the other codecs which target Unicode, this codec will return Python string objects for both encode and decode. Written by Marc-Andre Lemburg (<EMAIL>). """ import codecs, binascii ### Codec APIs def hex_encode(input,er...
from mbcharsetprober import MultiByteCharSetProber from codingstatemachine import CodingStateMachine from chardistribution import EUCKRDistributionAnalysis from mbcssm import EUCKRSMModel class EUCKRProber(MultiByteCharSetProber): def __init__(self): MultiByteCharSetProber.__init__(self) self._mCod...
from django.db import models class Badge(models.Model): id = models.IntegerField(primary_key=True) class_type = models.IntegerField(null=True) name = models.CharField(max_length=50, null=True) description = models.TextField(null=True) single = models.NullBooleanField(null=True) secret = models.N...
import abc from custodian.custodian import ErrorHandler, Validator #TODO: do we stick to custodian's ErrorHandler/Validator inheritance ?? class SRCErrorHandler(ErrorHandler): HANDLER_PRIORITIES = {'PRIORITY_FIRST': 0, 'PRIORITY_VERY_HIGH': 1, 'PRIORITY_HIGH':...
import imp import os import sys import unittest from importlib import import_module from zipimport import zipimporter from django.test import SimpleTestCase, modify_settings from django.test.utils import extend_sys_path from django.utils import six from django.utils._os import upath from django.utils.module_loading im...
# -*- coding: utf-8 -*- from __future__ import absolute_import import tempfile import os from django import forms from django.contrib import admin from django.contrib.admin.views.main import ChangeList from django.core.files.storage import FileSystemStorage from django.core.mail import EmailMessage from django.conf.u...
from weboob.capabilities.video import BaseVideo __all__ = ['ArteVideo', 'ArteLiveVideo'] class ArteVideo(BaseVideo): @classmethod def id2url(cls, _id): lang = _id[-1:] return 'http://arte.tv/papi/tvguide/videos/stream/%s/%s/HBBTV' % (lang, _id) class ArteLiveVideo(BaseVideo): def __ini...
"""Steps to test the demonstration Cockpit plugin""" from behave import given, when, then from hamcrest import ( assert_that, equal_to, greater_than, greater_than_or_equal_to ) @given("Cockpit is installed on the testing host") def check_cockpit_is_installed(context): """Checks for the `cockpit-bridge` command...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Utility to calculate MOSFETs """ import numpy as np from UliEngineering.EngineerIO import normalize_numeric from UliEngineering.Units import Unit __all__ = ["mosfet_gate_charge_losses", "mosfet_gate_charge_loss_per_cycle"] def mosfet_gate_charge_losses(total_gate_cha...
import os from pip.basecommand import Command from pip.log import logger from pip._vendor import pkg_resources class ShowCommand(Command): """Show information about one or more installed packages.""" name = 'show' usage = """ %prog [options] <package> ...""" summary = 'Show information about in...
"""Tools to read and write numpy arrays from and to image files. """ import freeimage import numpy from . import warn_tools def read_grayscale_array_from_image_file(filename, warn = True): """Read an image from disk into a 2-D grayscale array, converting from color if necessary. If 'warn' is True, issue a w...
#!/usr/bin/env python from __future__ import absolute_import, division, print_function, with_statement from tornado import gen, ioloop from tornado.log import app_log from tornado.testing import AsyncTestCase, gen_test, ExpectLog from tornado.test.util import unittest import contextlib import os import traceback @...
""" All different except 0 Google CP Solver. Decomposition of global constraint alldifferent_except_0. From Global constraint catalogue: http://www.emn.fr/x-info/sdemasse/gccat/Calldifferent_except_0.html ''' Enforce all variables of the collection VARIABLES to take distinct values, except those variab...
"""Fake buckets data.""" FAKE_BUCKETS_MAP = [{ 'project_number': 11111, 'buckets': { 'items': [{ 'kind': 'storage#bucket', 'name': 'fakebucket1', 'timeCreated': '2016-07-21T12:57:04.604Z', 'updated': '2016-07-21T12:57:04.604Z', 'projectNumber'...
from __future__ import absolute_import import fluent.syntax.ast as FTL from fluent.migrate.helpers import transforms_from from fluent.migrate.helpers import VARIABLE_REFERENCE, TERM_REFERENCE from fluent.migrate import REPLACE, COPY whatsnew_73 = "firefox/whatsnew_73.lang" def migrate(ctx): """Migrate bedrock/fir...
from subprocess import Popen,PIPE import sys import json result = {} result['all'] = {} pipe = Popen(['zoneadm', 'list', '-ip'], stdout=PIPE, universal_newlines=True) result['all']['hosts'] = [] for l in pipe.stdout.readlines(): # 1:work:running:/zones/work:3126dc59-9a07-4829-cde9-a816e4c5040e:native:shared s...
from tempest_lib.common.utils import data_utils from tempest.api.orchestration import base from tempest import test class TemplateYAMLTestJSON(base.BaseOrchestrationTest): template = """ HeatTemplateFormatVersion: '2012-12-12' Description: | Template which creates only a new user Resources: CfnUser: Type...
import fixtures from tempest.openstack.common import lockutils class LockFixture(fixtures.Fixture): """External locking fixture. This fixture is basically an alternative to the synchronized decorator with the external flag so that tearDowns and addCleanups will be included in the lock context for lo...
from anthill.common.options import define # Main define("host", default="http://localhost:9507", help="Public hostname of this service", type=str) define("listen", default="port:9507", help="Socket to listen. Could be a port number (port:N), or a unix domain socket (unix:PATH)", ...
from pylib.base import base_test_result class InstrumentationTestResult(base_test_result.BaseTestResult): """Result information for a single instrumentation test.""" def __init__(self, full_name, test_type, start_date, dur, log=''): """Construct an InstrumentationTestResult object. Args: full_name...
import numpy as np def sigmoid(x): """ Compute the sigmoid function for the input here. """ x = 1./(1 + np.exp(-x)) return x def sigmoid_grad(f): """ Compute the gradient for the sigmoid function here. Note that for this implementation, the input f should be the sigmoid f...
""" Test watchpoint condition API. """ from __future__ import print_function import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class WatchpointConditionAPITestCase(TestBase): mydir = TestBase.compute_mydir(__file__) NO_DEBUG_INFO_...
import six import sys import unittest from io import StringIO from itertools import dropwhile from mock import patch, call from airflow import configuration, models from airflow.utils import db from airflow.contrib.hooks.spark_sql_hook import SparkSqlHook def get_after(sentinel, iterable): "Get the value after ...
from __future__ import division, print_function, absolute_import import sys import math import numpy as np from numpy import sqrt, cos, sin, arctan, exp, log, pi, Inf from numpy.testing import (assert_, TestCase, run_module_suite, dec, assert_allclose, assert_array_less, assert_almost_equal) from scipy.integra...
import os # toolchains options ARCH='arm' CPU='cortex-m3' CROSS_TOOL='gcc' # bsp lib config BSP_LIBRARY_TYPE = None if os.getenv('RTT_CC'): CROSS_TOOL = os.getenv('RTT_CC') if os.getenv('RTT_ROOT'): RTT_ROOT = os.getenv('RTT_ROOT') # cross_tool provides the cross compiler # EXEC_PATH is the compiler execute...
import csv from collections import Counter import re from bs4 import BeautifulSoup csv_file = open('data_detikcom_labelled_740.csv') csv_reader = csv.DictReader(csv_file) words = [] docs = [] label_counter = {} unique_label_counter = {} for row in csv_reader: title = row['title'].strip().lower() raw_content ...
# -*- coding: utf-8 -*- # # This module (which must have the name queryfunc.py) is responsible # for converting incoming queries to a database query understood by # this particular node's database schema. # # This module must contain a function setupResults, taking a sql object # as its only argument. # # library im...
#!/usr/bin/env python """ This example illustrates the sudden appearance of a giant connected component in a binomial random graph. Requires pygraphviz and matplotlib to draw. """ # Copyright (C) 2006-2016 # Aric Hagberg <<EMAIL>> # Dan Schult <<EMAIL>> # Pieter Swart <<EMAIL>> # All rights reserved. #...
from abc import ABCMeta from abc import abstractmethod import copy import eventlet import httplib import time import six import six.moves.urllib.parse as urlparse from neutron.openstack.common import excutils from neutron.openstack.common import log as logging from neutron.plugins.vmware.api_client import ctrl_conn_t...
# These are versions of the functions in django.utils.translation.trans_real # that don't actually do anything. This is purely for performance, so that # settings.USE_I18N = False can use this module rather than trans_real.py. from django.conf import settings from django.utils.encoding import force_text def ngettext...
# http://g95.sourceforge.net/ from numpy.distutils.fcompiler import FCompiler compilers = ['G95FCompiler'] class G95FCompiler(FCompiler): compiler_type = 'g95' description = 'G95 Fortran Compiler' # version_pattern = r'G95 \((GCC (?P<gccversion>[\d.]+)|.*?) \(g95!\) (?P<version>.*)\).*' # $ g95 --ver...
from cerbero.commands import Command, register_command from cerbero.build.cookbook import CookBook from cerbero.build.oven import Oven from cerbero.utils import _, N_, ArgparseArgument class Build(Command): doc = N_('Build a recipe') name = 'build' def __init__(self, force=None, no_deps=None): ...
import uno import string import unohelper import xmlrpclib import base64, tempfile from com.sun.star.task import XJobExecutor import os import sys if __name__<>'package': from lib.gui import * from lib.error import * from LoginTest import * from lib.logreport import * from lib.rpc import * dat...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Notices during runtime. :copyright: 2015 Agile Geoscience :license: Apache 2.0 """ class Notice(object): """ Helper class to make printout more readable. """ styles = {'HEADER': '\033[95m', 'INFO': '\033[94m', # blue '...
# -*- coding: utf-8 -*- """ ********** Exceptions ********** Base exceptions and errors for NetworkX. """ __author__ = """Aric Hagberg (<EMAIL>)\nPieter Swart (<EMAIL>)\nDan Schult(<EMAIL>)\nLoïc Séguin-C. <<EMAIL>>""" # Copyright (C) 2004-2011 by # Aric Hagberg <<EMAIL>> # Dan Schult <<EMAIL>> # Pieter S...
from __future__ import unicode_literals from collections import OrderedDict import keyword import re from optparse import make_option from django.core.management.base import NoArgsCommand, CommandError from django.db import connections, DEFAULT_DB_ALIAS class Command(NoArgsCommand): help = "Introspects the data...
import logging, json, requests #requests.packages.urllib3.disable_warnings() # Setup logging logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler()) # Big Data Extensions Endpoint bde_endpoint = 'bde.localdomain' username = '<EMAIL>' password = 'password' # Make...
from .. import base from girder.api.rest import loadmodel, Resource from girder.api import access from girder.constants import AccessType # We deliberately don't have an access decorator def defaultFunctionHandler(**kwargs): return @access.admin def adminFunctionHandler(**kwargs): return @access.user def...
# -*- coding: utf-8 -*- """ jinja2.tests ~~~~~~~~~~~~ Jinja test functions. Used with the "is" operator. :copyright: (c) 2010 by the Jinja Team. :license: BSD, see LICENSE for more details. """ import re from jinja2.runtime import Undefined from jinja2._compat import text_type, string_types, mappi...
from django.contrib.contenttypes.models import ContentType from django.core.files import File from nose.tools import eq_ from kitsune.questions.tests import question from kitsune.sumo.tests import TestCase from kitsune.upload.models import ImageAttachment from kitsune.upload.tasks import generate_thumbnail from kitsu...
""" Django signals connections and associated receiver functions for geonode's third-party 'social' apps which include announcements, notifications, relationships, actstream user_messages and potentially others """ import logging from collections import defaultdict from dialogos.models import Comment from djan...
import sys from sklearn.externals.six.moves import cStringIO as StringIO import numpy as np import scipy.sparse as sp from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_less from sklearn.utils.testing import assert_raises_regexp ...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import pytest from nose.tools import * # noqa: F403 from osf_tests import factories from tests.base import OsfTestCase from website.util import api_url_for from website.views import find_bookmark_collection @...
import unittest from pychess.Utils.const import * from pychess.Utils.lutils.LBoard import LBoard from pychess.Utils.lutils.leval import evaluateComplete from pychess.Utils.lutils import leval class EvalTestCase(unittest.TestCase): def setUp (self): self.board = LBoard(NORMALCHESS) self.boar...
''' Tex: Compressed texture ''' __all__ = ('ImageLoaderTex', ) import json from struct import unpack from kivy.logger import Logger from kivy.core.image import ImageLoaderBase, ImageData, ImageLoader class ImageLoaderTex(ImageLoaderBase): @staticmethod def extensions(): return ('tex', ) def lo...
import json, time from math import log from urllib import quote_plus import urllib2 _COUNT_URL = 'https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=' _AUTOCOMPLETE_URL = 'http://suggestqueries.google.com/complete/search?client=chrome&q=' _GOOGLE_ENCODING = 'latin-1' _last_query_time = 0.0 _QUERY_DELAY = ...
from django.conf import settings FILES_DIR = getattr(settings, 'FILES_WIDGET_FILES_DIR', 'uploads/files_widget/') OLD_VALUE_STR = getattr(settings, 'FILES_WIDGET_OLD_VALUE_STR', 'old_%s_value') DELETED_VALUE_STR = getattr(settings, 'FILES_WIDGET_DELETED_VALUE_STR', 'deleted_%s_value') MOVED_VALUE_STR = getattr(setting...
# coding=utf-8 from _commandbase import RadianceCommand from ..parameters.gendaymtx import GendaymtxParameters import os class Gendaymtx(RadianceCommand): u""" gendaymtx - Generate an annual Perez sky matrix from a weather tape. Attributes: output_name: An optional name for output file name. If ...
"""Update the IP addresses of your Cloudflare DNS records.""" from datetime import timedelta import logging from pycfdns import CloudflareUpdater import voluptuous as vol from homeassistant.const import CONF_API_KEY, CONF_EMAIL, CONF_ZONE import homeassistant.helpers.config_validation as cv from homeassistant.helpers...
"""Timetabler PTF9 import functions.""" import unsync import petl @unsync.command() @unsync.option('--input-file', '-i', type=unsync.Path(exists=True, dir_okay=False, readable=True, resolve_path=True), help='Timetabler PTF9 file to extract data from.', required=True) @unsync.option('--destination', '-d', required=Tru...
from django.test import TestCase from .models import Category, Person class ManyToOneRecursiveTests(TestCase): def setUp(self): self.r = Category(id=None, name='Root category', parent=None) self.r.save() self.c = Category(id=None, name='Child category', parent=self.r) self.c.save...
import stock_change_standard_price import stock_invoice_onshipping import stock_valuation_history import stock_return_picking
"""Functions for Python 2 vs. 3 compatibility. ## Conversion routines In addition to the functions below, `as_str` converts an object to a `str`. @@as_bytes @@as_text @@as_str_any ## Types The compatibility module also provides the following types: * `bytes_or_text_types` * `complex_types` * `integral_types` * `rea...
"""Sensor from an SQL Query.""" import datetime import decimal import logging import sqlalchemy from sqlalchemy.orm import scoped_session, sessionmaker import voluptuous as vol from homeassistant.components.recorder import CONF_DB_URL, DEFAULT_DB_FILE, DEFAULT_URL from homeassistant.components.sensor import PLATFORM_...
"""Convert ViT and non-distilled DeiT checkpoints from the timm library.""" import argparse from pathlib import Path import torch from PIL import Image import requests import timm from transformers import DeiTFeatureExtractor, ViTConfig, ViTFeatureExtractor, ViTForImageClassification, ViTModel from transformers.uti...
from openerp import tools from openerp.tests import common class Test_Lunch(common.TransactionCase): def setUp(self): """*****setUp*****""" super(Test_Lunch, self).setUp() cr, uid = self.cr, self.uid self.res_users = self.registry('res.users') self.lunch_order = self.regis...
"""Interface for validatable objects.""" class IValidatable(object): """Interface for validatable objects. Defines methods to verify if the object's value is valid or not, and to add, remove and list registered validators of the object. @author: Vaadin Ltd. @author: Richard Lincoln @version: ...
''' Provide the Data Model ''' import time class Config(object): def __init__(self): self.play = Playing() self.use_netease_source = False self.scroll_lryic = False self.enable_rpc = False class Playing(object): def __init__(self): self.title = '' self.singer...
from website.tokens.exceptions import TokenError class OSFError(Exception): """Base class for exceptions raised by the Osf application""" pass class NodeError(OSFError): """Raised when an action cannot be performed on a Node model""" pass class NodeStateError(NodeError): """Raised when the Node...
#!/usr/bin/python2 from distutils.core import setup, Extension from os import getenv from distutils.command.build_ext import build_ext as _build_ext from distutils.command.install_lib import install_lib as _install_lib class build_ext(_build_ext): def finalize_options(self): _build_ext.finalize_optio...
"""Test the openended_post management command.""" from datetime import datetime import json from mock import patch from pytz import UTC from django.conf import settings from opaque_keys.edx.locations import Location import capa.xqueue_interface as xqueue_interface from courseware.courses import get_course_with_acces...
from hazelcast.serialization.bits import * from hazelcast.protocol.client_message import ClientMessage from hazelcast.protocol.custom_codec import * from hazelcast.util import ImmutableLazyDataList from hazelcast.protocol.codec.client_message_type import * from hazelcast.protocol.event_response_const import * REQUEST_...
from locals import * from collections import OrderedDict import itertools import sklearn.linear_model import sklearn.svm import sklearn.ensemble import sklearn.neighbors import sklearn.semi_supervised import sklearn.naive_bayes # Code from http://rosettacode.org/wiki/Power_set#Python def list_powerset2(lst): ret...
from functools import wraps from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_control from django.views.decorators.http import last_modified as cache_last_modified from django.utils.translation import gettext_lazy as _ from django.core.exceptions import PermissionDeni...
#!/usr/bin/env python3 """Unit tests for the keyword only argument specified in PEP 3102.""" __author__ = "Jiwon Seo" __email__ = "seojiwon at gmail dot com" import unittest from test.support import run_unittest def posonly_sum(pos_arg1, *arg, **kwarg): return pos_arg1 + sum(arg) + sum(kwarg.values()) def keywo...
"""Code-coverage tools for CherryPy. To use this module, or the coverage tools in the test suite, you need to download 'coverage.py', either Gareth Rees' `original implementation <http://www.garethrees.org/2001/12/04/python-coverage/>`_ or Ned Batchelder's `enhanced version: <http://www.nedbatchelder.com/code/modules/...
from axolotl.state.sessionstore import SessionStore from axolotl.state.sessionrecord import SessionRecord class LiteSessionStore(SessionStore): def __init__(self, dbConn): """ :type dbConn: Connection """ self.dbConn = dbConn dbConn.execute("CREATE TABLE IF NOT EXISTS session...
try: import unittest2 as unittest except ImportError: import unittest # noqa from uuid import uuid4 from cassandra.cqlengine import columns from cassandra.cqlengine.management import sync_table, drop_table from cassandra.cqlengine.models import Model from tests.integration.cqlengine.base import BaseCassEngT...
"""Module containing functions to calculate PAM statistics Todo: Convert to use Matrix instead of numpy matrices """ import numpy as np from LmCommon.common.lmconstants import PamStatKeys, PhyloTreeKeys from LmCompute.plugins.multi.calculate import ot_phylo from lmpy import Matrix # ...............................
from gi.repository import Gtk from gi.repository import Gdk from gi.repository import GLib from gi.repository import GObject from draobpilc import common from draobpilc.lib import utils from draobpilc.lib import fuzzy from draobpilc.widgets.histories_manager import HistoriesManager from draobpilc.widgets.items_counter...