repo_name stringlengths 5 100 | path stringlengths 4 294 | copies stringclasses 990
values | size stringlengths 4 7 | content stringlengths 666 1M | license stringclasses 15
values |
|---|---|---|---|---|---|
sahilshekhawat/pydy | examples/inertia_of_torus/inertia_of_torus.py | 7 | 2067 | """Derivation of central inertia of a uniform density torus.
See Kane & Levinson, 1985, Chapter 3, Section 3 for further background.
"""
from sympy import integrate, pi, Matrix, symbols
from sympy.physics.mechanics import dot, cross, inertia, ReferenceFrame
phi, theta, s, R, r, m = symbols('phi theta s R r m')
# Volume and density of a torus
V = 2 * R * (pi * r)**2
rho = m / V
A = ReferenceFrame('A') # Torus fixed, x-y in symmetry plane
B = A.orientnew('B', 'Axis', [phi, A.z]) # Intermediate frame
C = B.orientnew('C', 'Axis', [-theta, B.y])# Intermediate frame
# Position vector from torus center to arbitrary point of torus
# R : torus major radius
# s : distance >= 0 from center of torus cross section to point in torus
p = R * B.x + s * C.x
# Determinant of the Jacobian of the mapping from a, b, c to x, y, z
# See Wikipedia for a lucid explanation of why we must comput this Jacobian:
# http://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant#Further_examples
J = Matrix([dot(p, uv) for uv in A]).transpose().jacobian([phi, theta, s])
dv = J.det().trigsimp() # Need to ensure this is positive
print("dx*dy*dz = {0}*dphi*dtheta*ds".format(dv))
# We want to compute the inertia scalars of the torus relative to it's mass
# center, for the following six unit vector pairs
unit_vector_pairs = [(A.x, A.x), (A.y, A.y), (A.z, A.z),
(A.x, A.y), (A.y, A.z), (A.x, A.z)]
# Calculate the six unique inertia scalars using equation 3.3.9 of Kane &
# Levinson, 1985.
inertia_scalars = []
for n_a, n_b in unit_vector_pairs:
# Integrand of Equation 3.3.9
integrand = rho * dot(cross(p, n_a), cross(p, n_b)) * dv
# Compute the integral by integrating over the whole volume of the tours
I_ab = integrate(integrate(integrate(integrand,
(phi, 0, 2*pi)), (theta, 0, 2*pi)), (s, 0, r))
inertia_scalars.append(I_ab)
# Create an inertia dyad from the list of inertia scalars
I_A_O = inertia(A, *inertia_scalars)
print("Inertia of torus about mass center = {0}".format(I_A_O))
| bsd-3-clause |
MorganBauer/gcjcupcake | commands/gcj_cupcake/DataManager.py | 1 | 2201 | # -*- coding: utf-8 -*-
#
# GCJ Cupcake by jbernadas
# Copyright (C) 2010 Jorge Bernadas (jbernadas@gmail.com)
#
# 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 it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
# Read the persistent data from the specified file, which
# should be formatted as a python dict.
def read_data(filename):
try:
# Open the specified file and get its contents.
file = open(filename, 'rt')
file_data = file.read()
file.close()
# Evaluate the file data directly, as it is formatted as a python dict.
return eval(file_data, {}, {})
except IOError as error:
# Log the IO error and exit with error.
sys.stderr.write('IO error happened while reading data '
'from file "{0}" : {1}'.format(filename, str(error)))
sys.exit(1)
# Write the specified data to the specified file, which will
# be formatted as a python dict.
def write_data(data, filename):
try:
# Calculate the space needed for the keys and create a format string
# for each data item.
key_width = max(len(repr(key)) for key in data.iterkeys())
item_format = '{0:' + str(key_width) + '} : {1},'
# Open the file and store each item inside it.
file = open(filename, 'wt')
file.write('{\n');
for key, value in sorted(data.iteritems()):
item_line = item_format.format(repr(key), repr(value))
file.write('{0}\n'.format(item_line))
file.write('}\n');
file.close()
except IOError as error:
# Log the IO error and exit with error.
sys.stderr.write('IO error happened while writing data file '
'from "{0}" : {1}'.format(filename, str(error)))
sys.exit(1)
| gpl-3.0 |
HalescodeLLC/django-munsell | munsell/mcolor/tests.py | 1 | 3821 | import logging
from django.core.urlresolvers import resolve
from django.template.loader import render_to_string
from django.test import TestCase
from django.http import HttpRequest
from .views import home_page, results_page
from .models import MunsellColor
# Create your tests here.
class HomePageTest(TestCase):
def test_root_url_resolves_to_home_page_view(self):
found = resolve('/')
self.assertEqual(found.func, home_page)
def test_home_page_returns_correct_html(self):
request = HttpRequest()
response = home_page(request)
expected_html = render_to_string('mcolor/home.html')
self.assertEqual(response.content.decode(), expected_html)
def test_home_page_can_save_a_POST_request(self):
request = HttpRequest()
request.method = 'POST'
request.POST['munsell_color'] = '2.5YR 4/6'
response = results_page(request)
self.assertIn('1 match found for 2.5YR 4/6', response.content.decode())
self.assertIn('140, 81, 54', response.content.decode())
def test_matches_are_case_insensitive(self):
request = HttpRequest()
request.method = 'POST'
request.POST['munsell_color'] = '2.5yr 4/6'
response = results_page(request)
self.assertIn('1 match found for 2.5yr 4/6', response.content.decode())
self.assertIn('140, 81, 54', response.content.decode())
def test_partial_matches_return_list(self):
# self.maxDiff = None
request = HttpRequest()
request.method = 'POST'
request.POST['munsell_color'] = 'N'
response = results_page(request)
self.assertIn('10 matches found for N', response.content.decode())
def test_query_color_does_not_need_whitespace_in_name(self):
request = HttpRequest()
request.method = 'POST'
request.POST['munsell_color'] = 'N2.5'
response = results_page(request)
self.assertIn('1 match found for N2.5', response.content.decode())
self.assertIn('60, 60, 60', response.content.decode())
class MunsellColorModelTest(TestCase):
fixtures = ['initial_data.json']
def setUp(self):
# fixture pk=42
self.color02 = MunsellColor()
self.color02.hue_a = '2.5'
self.color02.hue_b = 'Y'
self.color02.value = '8'
self.color02.chroma = '6'
self.color02.nice_name = 'Yellow'
self.color02.munsell_name = '2.5Y 8/6'
self.color02.sortable_name = '02.5 8/6'
self.color02.n_r = '0.898'
self.color02.n_g = '0.7686'
self.color02.n_b = '0.4824'
self.color02.s_r = '229'
self.color02.s_g = '196'
self.color02.s_b = '123'
self.color02.hexval = 'E5C47B'
self.color02.save()
def test_fixture_loaded_properly(self):
record = MunsellColor.objects.get(pk=42)
self.assertEqual(record.munsell_name, self.color02.munsell_name)
def test_returns_normalized_RGB_components(self):
x = MunsellColor.objects.get(pk=42).convert_to_normalized_rgb()
self.assertEqual('0.898', x[0])
self.assertEqual('0.7686', x[1])
self.assertEqual('0.4824', x[2])
def test_returns_normalized_RGB_single_string(self):
x = MunsellColor.objects.get(pk=42).convert_to_normalized_rgb_single_string()
self.assertEqual('0.898, 0.7686, 0.4824', x)
def test_returns_standard_RGB_components(self):
x = MunsellColor.objects.get(pk=42).convert_to_standard_rgb()
self.assertEqual('229', x[0])
self.assertEqual('196', x[1])
self.assertEqual('123', x[2])
def test_returns_standard_RGB_single_string(self):
x = MunsellColor.objects.get(pk=42).convert_to_standard_rgb_single_string()
self.assertEqual('229, 196, 123', x)
| mit |
apple/llvm-project | lldb/test/API/functionalities/reproducers/fs-case-sensitivity/TestReproducerFSCaseSensitivity.py | 4 | 2194 | """
Test if the reproducer correctly detects whether the file system is case sensitive.
"""
import lldb
import tempfile
from lldbsuite.test import lldbtest_config
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class ReproducerFileSystemSensitivityTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
NO_DEBUG_INFO_TESTCASE = True
@skipIfNetBSD
@skipIfWindows
@skipIfRemote
@skipIfiOSSimulator
@skipIfReproducer
def test_reproducer_attach(self):
# The reproducer output path. Note that this is on purpose a lower-case
# file name. See the case-sensitivity check below.
reproducer = self.getBuildArtifact('test.reproducer')
try:
shutil.rmtree(reproducer)
except OSError:
pass
# Use Popen because pexpect is overkill and spawnSubprocess is
# asynchronous.
capture = subprocess.Popen([
lldbtest_config.lldbExec, '-b', '--no-lldbinit', '--no-use-colors']
+ sum(map(lambda x: ['-O', x], self.setUpCommands()), [])
+ ['--capture', '--capture-path', reproducer,
'-o', 'reproducer generate'
],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
outs, _ = capture.communicate()
outs = outs.decode('utf-8')
self.assertIn('Reproducer written', outs)
# Read in the YAML file. We only care about a single value, so no
# need to parse the full file.
with open(os.path.join(reproducer, "files.yaml"), 'r') as file:
files_yaml = file.read()
# Detect the file system case sensitivity by checking if we can
# find the reproducer path after converting it to upper case (the
# file name is lower case before conversion, so this only works
# on case insensitive file systems).
case_sensitive = "false" if os.path.exists(reproducer.upper()) else "true"
self.assertIn("'case-sensitive': '" + case_sensitive + "'", files_yaml)
| apache-2.0 |
alete89/PyCGI | src/gui/treeView.py | 1 | 6215 | from PyQt4 import QtGui, QtCore
from ..logic import core
import shutil as shu
import os
class TreeView(QtGui.QTreeView):
def __init__(self, window_instance):
super(TreeView, self).__init__()
self.window = window_instance
self.fsmodel = QtGui.QFileSystemModel(self)
self.fsmodel.setRootPath(core.getTreeViewRootPath())
initialPath = self.fsmodel.index(core.getTreeViewInitialPath())
self.setModel(self.fsmodel)
self.setRootIndex(self.fsmodel.index(core.getTreeViewRootPath()))
self.expand(initialPath)
while initialPath.parent().isValid():
self.expand(initialPath.parent())
initialPath = initialPath.parent()
self.setAnimated(True)
self.setIndentation(15)
self.setSortingEnabled(True)
self.sortByColumn(0, 0)
self.setColumnWidth(0, 300)
self.doubleClicked.connect(self.openFileFromTree)
self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.openRightClickMenu)
def updateTreeView(self):
self.collapseAll()
self.setRootIndex(self.fsmodel.index(core.getTreeViewRootPath()))
self.update()
initialPath = self.fsmodel.index(core.getTreeViewInitialPath())
self.expand(initialPath)
while initialPath.parent().isValid():
self.expand(initialPath.parent())
initialPath = initialPath.parent()
def openFileFromTree(self, index):
indexItem = self.fsmodel.index(index.row(), 0, index.parent())
filePath = self.fsmodel.filePath(indexItem)
if os.path.isfile(filePath):
fname = str(filePath)
self.window.tabWidget.setCurrentIndex(1)
self.window.tabEditor.openFile(fname)
def openRightClickMenu(self, position):
indexes = self.selectedIndexes()
menu = QtGui.QMenu()
clipboard = QtGui.QApplication.clipboard()
filePath = str(self.fsmodel.filePath(indexes[0]))
# Actions
createDirFunction = menu.addAction(self.tr("Create directory"))
renameFunction = menu.addAction(self.tr("Rename"))
separator = menu.addSeparator()
copyFileFunction = menu.addAction(self.tr("Copy"))
moveFileFunction = menu.addAction(self.tr("Move"))
pasteFileFunction = menu.addAction(self.tr("Paste"))
separator = menu.addSeparator()
removeFileFunction = menu.addAction(self.tr("Remove"))
separator = menu.addSeparator()
copyPath = menu.addAction(self.tr("Get Full Path..."))
# Resultado
eleccion = menu.exec_(self.viewport().mapToGlobal(position))
if eleccion == copyPath:
self.setClipboard(filePath, copyOrMove="")
elif eleccion == renameFunction:
self.showDialogRename(filePath)
elif eleccion == createDirFunction:
self.showDialogMkDir(filePath)
elif eleccion == copyFileFunction:
copyOrMove = 1
self.setClipboard(filePath, copyOrMove)
elif eleccion == moveFileFunction:
copyOrMove = 0
self.setClipboard(filePath, copyOrMove)
elif eleccion == removeFileFunction:
res = QtGui.QMessageBox.information(None, "Warning", "<b>Remove this</b>?\n"+str(
filePath), QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Cancel)
if res == QtGui.QMessageBox.Cancel:
return
else:
if os.path.isfile(filePath):
os.remove(filePath)
elif os.path.isdir(filePath):
delDir = QtGui.QMessageBox.information(None, "Warning", "This is a directory. All files inside will be deleted.\n"+str(
filePath), QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Cancel)
if delDir == QtGui.QMessageBox.Cancel:
return
else:
shu.rmtree(filePath)
else:
QtGui.QMessageBox.information(None, "Message", "Error on remove")
elif eleccion == pasteFileFunction:
filePath = str(self.fsmodel.filePath(indexes[0]))
oldFilePath = str(clipboard.text())
copyOrMove = oldFilePath[0]
oldFilePath = oldFilePath[1:]
newPath, newFile = os.path.split(oldFilePath)
fileToPaste = filePath+"/"+newFile
try:
if copyOrMove == "1":
shu.copyfile(oldFilePath, fileToPaste)
else:
shu.move(oldFilePath, fileToPaste)
except:
QtGui.QMessageBox.information(None, "Message", "Error on paste")
def setClipboard(self, text, copyOrMove):
# Necesito indicar en el clipboard si el usuario
# quiere copiar o cortar (mover) el archivo
# para eso agrego un indicador al inicio del path
# en el clipboard
clipboard = QtGui.QApplication.clipboard()
clipboard.setText(str(copyOrMove)+str(text))
def showDialogMkDir(self, filePath):
newPath, newFile = os.path.split(filePath)
myDir, ok = QtGui.QInputDialog.getText(self, 'Input Dialog',
'Create a directory in <b>'+str(newPath)+'</b>')
if ok:
try:
if os.path.exists(newPath):
os.mkdir(newPath+"/"+myDir)
except:
QtGui.QMessageBox.information(None, "Message", "Error on create directory")
def showDialogRename(self, filePath):
newPath, oldFileName = os.path.split(filePath)
myNewName, ok = QtGui.QInputDialog.getText(self, 'Input Dialog',
'Rename <b>'+str(oldFileName)+'</b>', text=oldFileName)
fileToRename = newPath+"/"+myNewName
if ok:
try:
if os.path.exists(newPath):
shu.move(filePath, fileToRename)
except:
QtGui.QMessageBox.information(None, "Message", "Error on rename")
| gpl-3.0 |
kustodian/ansible | lib/ansible/plugins/connection/buildah.py | 23 | 6237 | # Based on the docker connection plugin
# Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
# Connection plugin for building container images using buildah tool
# https://github.com/projectatomic/buildah
#
# Written by: Tomas Tomecek (https://github.com/TomasTomecek)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = """
connection: buildah
short_description: Interact with an existing buildah container
description:
- Run commands or put/fetch files to an existing container using buildah tool.
author: Tomas Tomecek (ttomecek@redhat.com)
version_added: 2.4
options:
remote_addr:
description:
- The ID of the container you want to access.
default: inventory_hostname
vars:
- name: ansible_host
# keyword:
# - name: hosts
remote_user:
description:
- User specified via name or ID which is used to execute commands inside the container.
ini:
- section: defaults
key: remote_user
env:
- name: ANSIBLE_REMOTE_USER
vars:
- name: ansible_user
# keyword:
# - name: remote_user
"""
import shlex
import shutil
import subprocess
import ansible.constants as C
from ansible.module_utils._text import to_bytes, to_native
from ansible.plugins.connection import ConnectionBase, ensure_connect
from ansible.utils.display import Display
display = Display()
# this _has to be_ named Connection
class Connection(ConnectionBase):
"""
This is a connection plugin for buildah: it uses buildah binary to interact with the containers
"""
# String used to identify this Connection class from other classes
transport = 'buildah'
has_pipelining = True
def __init__(self, play_context, new_stdin, *args, **kwargs):
super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs)
self._container_id = self._play_context.remote_addr
self._connected = False
# container filesystem will be mounted here on host
self._mount_point = None
# `buildah inspect` doesn't contain info about what the default user is -- if it's not
# set, it's empty
self.user = self._play_context.remote_user
def _set_user(self):
self._buildah(b"config", [b"--user=" + to_bytes(self.user, errors='surrogate_or_strict')])
def _buildah(self, cmd, cmd_args=None, in_data=None):
"""
run buildah executable
:param cmd: buildah's command to execute (str)
:param cmd_args: list of arguments to pass to the command (list of str/bytes)
:param in_data: data passed to buildah's stdin
:return: return code, stdout, stderr
"""
local_cmd = ['buildah', cmd, '--', self._container_id]
if cmd_args:
local_cmd += cmd_args
local_cmd = [to_bytes(i, errors='surrogate_or_strict') for i in local_cmd]
display.vvv("RUN %s" % (local_cmd,), host=self._container_id)
p = subprocess.Popen(local_cmd, shell=False, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate(input=in_data)
stdout = to_bytes(stdout, errors='surrogate_or_strict')
stderr = to_bytes(stderr, errors='surrogate_or_strict')
return p.returncode, stdout, stderr
def _connect(self):
"""
no persistent connection is being maintained, mount container's filesystem
so we can easily access it
"""
super(Connection, self)._connect()
rc, self._mount_point, stderr = self._buildah("mount")
self._mount_point = self._mount_point.strip()
display.vvvvv("MOUNTPOINT %s RC %s STDERR %r" % (self._mount_point, rc, stderr))
self._connected = True
@ensure_connect
def exec_command(self, cmd, in_data=None, sudoable=False):
""" run specified command in a running OCI container using buildah """
super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)
# shlex.split has a bug with text strings on Python-2.6 and can only handle text strings on Python-3
cmd_args_list = shlex.split(to_native(cmd, errors='surrogate_or_strict'))
rc, stdout, stderr = self._buildah("run", cmd_args_list, in_data)
display.vvvvv("STDOUT %r STDERR %r" % (stderr, stderr))
return rc, stdout, stderr
def put_file(self, in_path, out_path):
""" Place a local file located in 'in_path' inside container at 'out_path' """
super(Connection, self).put_file(in_path, out_path)
display.vvv("PUT %s TO %s" % (in_path, out_path), host=self._container_id)
real_out_path = self._mount_point + to_bytes(out_path, errors='surrogate_or_strict')
shutil.copyfile(
to_bytes(in_path, errors='surrogate_or_strict'),
to_bytes(real_out_path, errors='surrogate_or_strict')
)
# alternatively, this can be implemented using `buildah copy`:
# rc, stdout, stderr = self._buildah(
# "copy",
# [to_bytes(in_path, errors='surrogate_or_strict'),
# to_bytes(out_path, errors='surrogate_or_strict')]
# )
def fetch_file(self, in_path, out_path):
""" obtain file specified via 'in_path' from the container and place it at 'out_path' """
super(Connection, self).fetch_file(in_path, out_path)
display.vvv("FETCH %s TO %s" % (in_path, out_path), host=self._container_id)
real_in_path = self._mount_point + to_bytes(in_path, errors='surrogate_or_strict')
shutil.copyfile(
to_bytes(real_in_path, errors='surrogate_or_strict'),
to_bytes(out_path, errors='surrogate_or_strict')
)
def close(self):
""" unmount container's filesystem """
super(Connection, self).close()
rc, stdout, stderr = self._buildah("umount")
display.vvvvv("RC %s STDOUT %r STDERR %r" % (rc, stdout, stderr))
self._connected = False
| gpl-3.0 |
VielSoft/odoo | addons/project/wizard/__init__.py | 381 | 1075 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import project_task_delegate
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
caioserra/apiAdwords | examples/adspygoogle/dfp/v201302/get_all_user_team_associations.py | 3 | 1933 | #!/usr/bin/python
#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example gets all user team associations.
To create user team associations, run create_user_team_assocations.py.
Tags: UserTeamAssociationService.getUserTeamAssociationsByStatement
"""
__author__ = 'api.shamjeff@gmail.com (Jeff Sham)'
# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys
sys.path.insert(0, os.path.join('..', '..', '..', '..'))
# Import appropriate classes from the client library.
from adspygoogle import DfpClient
from adspygoogle.dfp import DfpUtils
# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))
# Initialize appropriate service.
user_team_association_service = client.GetService(
'UserTeamAssociationService', version='v201302')
# Get the user team associations by statement.
user_team_associations = DfpUtils.GetAllEntitiesByStatementWithService(
user_team_association_service)
# Display results.
for user_team_association in user_team_associations:
print ('User team association between user with ID \'%s\' and team with ID '
'\'%s\' was found.' % (user_team_association['userId'],
user_team_association['teamId']))
print
print 'Number of results found: %s' % len(user_team_associations)
| apache-2.0 |
Belgabor/django | django/utils/formats.py | 20 | 4641 | import decimal
import datetime
from django.conf import settings
from django.utils.translation import get_language, to_locale, check_for_language
from django.utils.importlib import import_module
from django.utils.encoding import smart_str
from django.utils import dateformat, numberformat, datetime_safe
def get_format_modules(reverse=False):
"""
Returns an iterator over the format modules found in the project and Django
"""
modules = []
if not check_for_language(get_language()) or not settings.USE_L10N:
return modules
locale = to_locale(get_language())
if settings.FORMAT_MODULE_PATH:
format_locations = [settings.FORMAT_MODULE_PATH + '.%s']
else:
format_locations = []
format_locations.append('django.conf.locale.%s')
for location in format_locations:
for l in (locale, locale.split('_')[0]):
try:
mod = import_module('.formats', location % l)
except ImportError:
pass
else:
# Don't return duplicates
if mod not in modules:
modules.append(mod)
if reverse:
modules.reverse()
return modules
def get_format(format_type):
"""
For a specific format type, returns the format for the current
language (locale), defaults to the format in the settings.
format_type is the name of the format, e.g. 'DATE_FORMAT'
"""
format_type = smart_str(format_type)
if settings.USE_L10N:
for module in get_format_modules():
try:
return getattr(module, format_type)
except AttributeError:
pass
return getattr(settings, format_type)
def date_format(value, format=None):
"""
Formats a datetime.date or datetime.datetime object using a
localizable format
"""
return dateformat.format(value, get_format(format or 'DATE_FORMAT'))
def time_format(value, format=None):
"""
Formats a datetime.time object using a localizable format
"""
return dateformat.time_format(value, get_format(format or 'TIME_FORMAT'))
def number_format(value, decimal_pos=None):
"""
Formats a numeric value using localization settings
"""
return numberformat.format(
value,
get_format('DECIMAL_SEPARATOR'),
decimal_pos,
get_format('NUMBER_GROUPING'),
get_format('THOUSAND_SEPARATOR'),
)
def localize(value):
"""
Checks if value is a localizable type (date, number...) and returns it
formatted as a string using current locale format
"""
if settings.USE_L10N:
if isinstance(value, (decimal.Decimal, float, int)):
return number_format(value)
elif isinstance(value, datetime.datetime):
return date_format(value, 'DATETIME_FORMAT')
elif isinstance(value, datetime.date):
return date_format(value)
elif isinstance(value, datetime.time):
return time_format(value, 'TIME_FORMAT')
return value
def localize_input(value, default=None):
"""
Checks if an input value is a localizable type and returns it
formatted with the appropriate formatting string of the current locale.
"""
if isinstance(value, (decimal.Decimal, float, int)):
return number_format(value)
if isinstance(value, datetime.datetime):
value = datetime_safe.new_datetime(value)
format = smart_str(default or get_format('DATETIME_INPUT_FORMATS')[0])
return value.strftime(format)
elif isinstance(value, datetime.date):
value = datetime_safe.new_date(value)
format = smart_str(default or get_format('DATE_INPUT_FORMATS')[0])
return value.strftime(format)
elif isinstance(value, datetime.time):
format = smart_str(default or get_format('TIME_INPUT_FORMATS')[0])
return value.strftime(format)
return value
def sanitize_separators(value):
"""
Sanitizes a value according to the current decimal and
thousand separator setting. Used with form field input.
"""
if settings.USE_L10N:
decimal_separator = get_format('DECIMAL_SEPARATOR')
if isinstance(value, basestring):
parts = []
if decimal_separator in value:
value, decimals = value.split(decimal_separator, 1)
parts.append(decimals)
if settings.USE_THOUSAND_SEPARATOR:
parts.append(value.replace(get_format('THOUSAND_SEPARATOR'), ''))
else:
parts.append(value)
value = '.'.join(reversed(parts))
return value
| bsd-3-clause |
stevenmizuno/QGIS | tests/src/python/test_qgssinglesymbolrenderer.py | 17 | 3133 | # -*- coding: utf-8 -*-
"""
***************************************************************************
test_qgssinglesymbolrenderer.py
---------------------
Date : December 2015
Copyright : (C) 2015 by Matthias Kuhn
Email : matthias at opengis dot ch
***************************************************************************
* *
* 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 *
* (at your option) any later version. *
* *
***************************************************************************
"""
__author__ = 'Matthias Kuhn'
__date__ = 'December 2015'
__copyright__ = '(C) 2015, Matthias Kuhn'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import qgis # NOQA
import os
from qgis.PyQt.QtCore import QSize
from qgis.core import (QgsVectorLayer,
QgsProject,
QgsRectangle,
QgsMultiRenderChecker,
QgsSingleSymbolRenderer,
QgsFillSymbol,
QgsFeatureRequest
)
from qgis.testing import unittest
from qgis.testing.mocked import get_iface
from utilities import unitTestDataPath
TEST_DATA_DIR = unitTestDataPath()
class TestQgsSingleSymbolRenderer(unittest.TestCase):
def setUp(self):
self.iface = get_iface()
myShpFile = os.path.join(TEST_DATA_DIR, 'polys_overlapping.shp')
layer = QgsVectorLayer(myShpFile, 'Polys', 'ogr')
QgsProject.instance().addMapLayer(layer)
# Create rulebased style
sym1 = QgsFillSymbol.createSimple({'color': '#fdbf6f', 'outline_color': 'black'})
self.renderer = QgsSingleSymbolRenderer(sym1)
layer.setRenderer(self.renderer)
rendered_layers = [layer]
self.mapsettings = self.iface.mapCanvas().mapSettings()
self.mapsettings.setOutputSize(QSize(400, 400))
self.mapsettings.setOutputDpi(96)
self.mapsettings.setExtent(QgsRectangle(-163, 22, -70, 52))
self.mapsettings.setLayers(rendered_layers)
def testOrderBy(self):
self.renderer.setOrderBy(QgsFeatureRequest.OrderBy([QgsFeatureRequest.OrderByClause('Value', False)]))
self.renderer.setOrderByEnabled(True)
# Setup rendering check
renderchecker = QgsMultiRenderChecker()
renderchecker.setMapSettings(self.mapsettings)
renderchecker.setControlName('expected_singlesymbol_orderby')
self.assertTrue(renderchecker.runTest('singlesymbol_orderby'))
# disable order by and retest
self.renderer.setOrderByEnabled(False)
self.assertTrue(renderchecker.runTest('single'))
if __name__ == '__main__':
unittest.main()
| gpl-2.0 |
unioslo/cerebrum | contrib/no/uit/process_sito_email.py | 1 | 8156 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2002-2019 University of Oslo, Norway
#
# This file is part of Cerebrum.
#
# Cerebrum 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
# (at your option) any later version.
#
# Cerebrum is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Cerebrum; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""
Create or update email addresses for all sito accounts.
This script iterates over all sito accounts with email spreads and asserts that
they have an email address set.
Configuration
-------------
This script use the following cereconf variables:
SITO_PRIMARY_MAILDOMAIN
Which mail domain to assign new email addresses to.
"""
from __future__ import absolute_import, print_function
import argparse
import logging
import cereconf
import Cerebrum.logutils
import Cerebrum.logutils.options
from Cerebrum import Errors
from Cerebrum.Utils import Factory
from Cerebrum.utils.funcwrap import memoize
from Cerebrum.modules.no.uit import Email
from Cerebrum.modules.no.uit.Account import UsernamePolicy
from Cerebrum.modules.Email import EmailDomain, EmailAddress
from Cerebrum.utils.argutils import add_commit_args
logger = logging.getLogger(__name__)
sito_domain = getattr(cereconf, 'SITO_PRIMARY_MAILDOMAIN')
@memoize
def get_domainid(db, domain_part):
domain = EmailDomain(db)
domain.find_by_domain(domain_part)
return domain.entity_id
def is_cnaddr_free_old(db, local_part, domain_part):
domain_id = get_domainid(db, domain_part)
ea = EmailAddress(db)
logger.debug("Considering %s, %s", local_part, domain_part)
try:
ea.find_by_local_part_and_domain(local_part, domain_id)
except Errors.NotFoundError:
# emailaddress is free.
logger.debug("Address %s@%s is free", local_part, domain_part)
else:
logger.warn("Address %s@%s is not free!", local_part, domain_part)
return False
return True
def format_addr(local_part, domain_part):
return '{}@{}'.format(local_part, domain_part)
class AddressGenerator(object):
def __init__(self, db):
self.db = db
self.in_use = set()
self.new_addrs = set()
def get_alternatives(self, account_name):
ac = Factory.get('Account')(self.db)
ac.find_by_name(account_name)
alternatives = list()
first_choice = ac.get_email_cn_local_part(given_names=1,
max_initials=1,
keep_dash=True)
alternatives.append(first_choice)
logger.debug("Alternatives for %s: %s", account_name, alternatives)
return alternatives
def is_cnaddr_free(self, local_part, domain_part):
addr = "@".join((local_part, domain_part))
if addr in self.in_use:
# TODO: Why is this not populated?
logger.warning('address %s already in use', addr)
return False
elif addr in self.new_addrs:
logger.warning('address %s reserved in transaction', addr)
return False
return True
def reserve_addr(self, account_name, domain_part):
attempts = set()
for local_part in self.get_alternatives(account_name):
addr = format_addr(local_part, domain_part)
if self.is_cnaddr_free(local_part, domain_part):
self.new_addrs.add(addr)
return (local_part, domain_part)
else:
attempts.add(addr)
raise ValueError("No free addresses found (%r)" % (attempts))
def get_sito_persons(db):
co = Factory.get('Constants')(db)
pe = Factory.get('Person')(db)
for row in pe.list_affiliations(source_system=co.system_sito):
yield int(row['person_id'])
def process_mail(db):
co = Factory.get('Constants')(db)
ac = Factory.get('Account')(db)
# TODO: Use `Email` module logger
em = Email.email_address(db, logger=logger.getChild('email_address'))
generate_addr = AddressGenerator(db)
spread = co.spread_uit_exchange
logger.info("Fetching all sito persons...")
sito_persons = list(get_sito_persons(db))
logger.info("Got %s persons", len(sito_persons))
exch_users = dict()
uname2accid = dict()
ownerid2uname = dict()
stats = {'included': 0, 'skipped': 0}
logger.info("Fetching all sito accounts with %r spread...", spread)
for a in ac.search(spread=spread):
if not UsernamePolicy.is_valid_sito_name(a['name']):
stats['skipped'] += 1
continue
if a['owner_id'] not in sito_persons:
stats['skipped'] += 1
continue
stats['included'] += 1
exch_users[a['account_id']] = a['name']
uname2accid[a['name']] = a['account_id']
ownerid2uname.setdefault(a['owner_id'], []).append(a['name'])
logger.info('Got %d accounts (%d considered, %d skipped)',
stats['included'], sum(stats.values()), stats['skipped'])
logger.debug("%d account ids, %d usernames",
len(exch_users), len(uname2accid))
for owner, usernames in (t for t in ownerid2uname.items()
if len(t[1]) > 1):
logger.debug("owner_id=%r has %d accounts: %s",
owner, len(usernames), usernames)
logger.info("Fetching all sito email targets...")
sito_mails = dict()
for uname, data in ac.getdict_uname2mailinfo().items():
if uname not in uname2accid:
continue
# this is a sito user
for row in filter(lambda r: r['domain'] == sito_domain, data):
sito_mails[uname] = format_addr(row['local_part'], row['domain'])
logger.info('Got email address for %d sito accounts', len(sito_mails))
# list to hold those we will build addresses for
all_emails = dict()
for account_id, uname in exch_users.items():
if uname in sito_mails:
logger.debug("User %s has existing address %r",
uname, sito_mails[uname])
else:
logger.info("User %s does not have an address!", uname)
try:
cn_addr = generate_addr.reserve_addr(uname, sito_domain)
all_emails.setdefault(account_id, []).append(cn_addr)
except Exception:
logger.error('Unable to generate email address for %r/%r',
uname, sito_domain, exc_info=True)
# update all email addresses
logger.debug('Updating %d sito addresses', len(all_emails))
for acc_id, emaillist in all_emails.items():
for local_part, domain_part in emaillist:
# TBD: is_primary always set to True?
is_primary = True
addr = format_addr(local_part, domain_part)
logger.info('Setting address for %r to %r (primary=%r)',
acc_id, addr, is_primary)
em.process_mail(acc_id, addr, is_primary=is_primary)
def main(inargs=None):
parser = argparse.ArgumentParser(
description="Process accounts for SITO employees")
add_commit_args(parser)
Cerebrum.logutils.options.install_subparser(parser)
args = parser.parse_args(inargs)
Cerebrum.logutils.autoconf('cronjob', args)
logger.info('Start of %s', parser.prog)
logger.debug('args: %r', args)
db = Factory.get('Database')()
db.cl_init(change_program=parser.prog)
process_mail(db)
if args.commit:
logger.info('Commiting changes')
db.commit()
else:
db.rollback()
logger.info('Rolling back changes')
logger.info('Done %s', parser.prog)
if __name__ == '__main__':
main()
| gpl-2.0 |
40223211/2015cd_midterm | static/Brython3.1.1-20150328-091302/Lib/unittest/__init__.py | 900 | 2718 | """
Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's
Smalltalk testing framework.
This module contains the core framework classes that form the basis of
specific test cases and suites (TestCase, TestSuite etc.), and also a
text-based utility class for running the tests and reporting the results
(TextTestRunner).
Simple usage:
import unittest
class IntegerArithmeticTestCase(unittest.TestCase):
def testAdd(self): ## test method names begin 'test*'
self.assertEqual((1 + 2), 3)
self.assertEqual(0 + 1, 1)
def testMultiply(self):
self.assertEqual((0 * 10), 0)
self.assertEqual((5 * 8), 40)
if __name__ == '__main__':
unittest.main()
Further information is available in the bundled documentation, and from
http://docs.python.org/library/unittest.html
Copyright (c) 1999-2003 Steve Purcell
Copyright (c) 2003-2010 Python Software Foundation
This module is free software, and you may redistribute it and/or modify
it under the same terms as Python itself, so long as this copyright message
and disclaimer are retained in their original form.
IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
"""
__all__ = ['TestResult', 'TestCase', 'TestSuite',
'TextTestRunner', 'TestLoader', 'FunctionTestCase', 'main',
'defaultTestLoader', 'SkipTest', 'skip', 'skipIf', 'skipUnless',
'expectedFailure', 'TextTestResult', 'installHandler',
'registerResult', 'removeResult', 'removeHandler']
# Expose obsolete functions for backwards compatibility
__all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases'])
__unittest = True
from .result import TestResult
from .case import (TestCase, FunctionTestCase, SkipTest, skip, skipIf,
skipUnless, expectedFailure)
from .suite import BaseTestSuite, TestSuite
from .loader import (TestLoader, defaultTestLoader, makeSuite, getTestCaseNames,
findTestCases)
from .main import TestProgram, main
from .runner import TextTestRunner, TextTestResult
from .signals import installHandler, registerResult, removeResult, removeHandler
# deprecated
_TextTestResult = TextTestResult
| gpl-3.0 |
sanketloke/scikit-learn | examples/tree/unveil_tree_structure.py | 67 | 4824 | """
=========================================
Understanding the decision tree structure
=========================================
The decision tree structure can be analysed to gain further insight on the
relation between the features and the target to predict. In this example, we
show how to retrieve:
- the binary tree structure;
- the depth of each node and whether or not it's a leaf;
- the nodes that were reached by a sample using the ``decision_path`` method;
- the leaf that was reached by a sample using the apply method;
- the rules that were used to predict a sample;
- the decision path shared by a group of samples.
"""
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
iris = load_iris()
X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
estimator = DecisionTreeClassifier(max_leaf_nodes=3, random_state=0)
estimator.fit(X_train, y_train)
# The decision estimator has an attribute called tree_ which stores the entire
# tree structure and allows access to low level attributes. The binary tree
# tree_ is represented as a number of parallel arrays. The i-th element of each
# array holds information about the node `i`. Node 0 is the tree's root. NOTE:
# Some of the arrays only apply to either leaves or split nodes, resp. In this
# case the values of nodes of the other type are arbitrary!
#
# Among those arrays, we have:
# - left_child, id of the left child of the node
# - right_child, id of the right child of the node
# - feature, feature used for splitting the node
# - threshold, threshold value at the node
#
# Using those arrays, we can parse the tree structure:
n_nodes = estimator.tree_.node_count
children_left = estimator.tree_.children_left
children_right = estimator.tree_.children_right
feature = estimator.tree_.feature
threshold = estimator.tree_.threshold
# The tree structure can be traversed to compute various properties such
# as the depth of each node and whether or not it is a leaf.
node_depth = np.zeros(shape=n_nodes)
is_leaves = np.zeros(shape=n_nodes, dtype=bool)
stack = [(0, -1)] # seed is the root node id and its parent depth
while len(stack) > 0:
node_id, parent_depth = stack.pop()
node_depth[node_id] = parent_depth + 1
# If we have a test node
if (children_left[node_id] != children_right[node_id]):
stack.append((children_left[node_id], parent_depth + 1))
stack.append((children_right[node_id], parent_depth + 1))
else:
is_leaves[node_id] = True
print("The binary tree structure has %s nodes and has "
"the following tree structure:"
% n_nodes)
for i in range(n_nodes):
if is_leaves[i]:
print("%snode=%s leaf node." % (node_depth[i] * "\t", i))
else:
print("%snode=%s test node: go to node %s if X[:, %s] <= %ss else to "
"node %s."
% (node_depth[i] * "\t",
i,
children_left[i],
feature[i],
threshold[i],
children_right[i],
))
print()
# First let's retrieve the decision path of each sample. The decision_path
# method allows to retrieve the node indicator functions. A non zero element of
# indicator matrix at the position (i, j) indicates that the sample i goes
# through the node j.
node_indicator = estimator.decision_path(X_test)
# Similarly, we can also have the leaves ids reached by each sample.
leave_id = estimator.apply(X_test)
# Now, it's possible to get the tests that were used to predict a sample or
# a group of samples. First, let's make it for the sample.
sample_id = 0
node_index = node_indicator.indices[node_indicator.indptr[sample_id]:
node_indicator.indptr[sample_id + 1]]
print('Rules used to predict sample %s: ' % sample_id)
for node_id in node_index:
if leave_id[sample_id] != node_id:
continue
if (X_test[sample_id, feature[node_id]] <= threshold[node_id]):
threshold_sign = "<="
else:
threshold_sign = ">"
print("decision id node %s : (X[%s, %s] (= %s) %s %s)"
% (node_id,
sample_id,
feature[node_id],
X_test[i, feature[node_id]],
threshold_sign,
threshold[node_id]))
# For a group of samples, we have the following common node.
sample_ids = [0, 1]
common_nodes = (node_indicator.toarray()[sample_ids].sum(axis=0) ==
len(sample_ids))
common_node_id = np.arange(n_nodes)[common_nodes]
print("\nThe following samples %s share the node %s in the tree"
% (sample_ids, common_node_id))
print("It is %s %% of all nodes." % (100 * len(common_node_id) / n_nodes,))
| bsd-3-clause |
ujjwalwahi/odoo | addons/point_of_sale/report/pos_details.py | 72 | 9373 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import time
from openerp.osv import osv
from openerp.report import report_sxw
class pos_details(report_sxw.rml_parse):
def _get_invoice(self, inv_id):
res={}
if inv_id:
self.cr.execute("select number from account_invoice as ac where id = %s", (inv_id,))
res = self.cr.fetchone()
return res[0] or 'Draft'
else:
return ''
def _get_all_users(self):
user_obj = self.pool.get('res.users')
return user_obj.search(self.cr, self.uid, [])
def _pos_sales_details(self, form):
pos_obj = self.pool.get('pos.order')
user_obj = self.pool.get('res.users')
data = []
result = {}
user_ids = form['user_ids'] or self._get_all_users()
company_id = user_obj.browse(self.cr, self.uid, self.uid).company_id.id
pos_ids = pos_obj.search(self.cr, self.uid, [('date_order','>=',form['date_start'] + ' 00:00:00'),('date_order','<=',form['date_end'] + ' 23:59:59'),('user_id','in',user_ids),('state','in',['done','paid','invoiced']),('company_id','=',company_id)])
for pos in pos_obj.browse(self.cr, self.uid, pos_ids):
for pol in pos.lines:
result = {
'code': pol.product_id.default_code,
'name': pol.product_id.name,
'invoice_id': pos.invoice_id.id,
'price_unit': pol.price_unit,
'qty': pol.qty,
'discount': pol.discount,
'total': (pol.price_unit * pol.qty * (1 - (pol.discount) / 100.0)),
'date_order': pos.date_order,
'pos_name': pos.name,
'uom': pol.product_id.uom_id.name
}
data.append(result)
self.total += result['total']
self.qty += result['qty']
self.discount += result['discount']
if data:
return data
else:
return {}
def _get_qty_total_2(self):
return self.qty
def _get_sales_total_2(self):
return self.total
def _get_sum_invoice_2(self, form):
pos_obj = self.pool.get('pos.order')
user_obj = self.pool.get('res.users')
user_ids = form['user_ids'] or self._get_all_users()
company_id = user_obj.browse(self.cr, self.uid, self.uid).company_id.id
pos_ids = pos_obj.search(self.cr, self.uid, [('date_order','>=',form['date_start'] + ' 00:00:00'),('date_order','<=',form['date_end'] + ' 23:59:59'),('user_id','in',user_ids),('company_id','=',company_id),('invoice_id','<>',False)])
for pos in pos_obj.browse(self.cr, self.uid, pos_ids):
for pol in pos.lines:
self.total_invoiced += (pol.price_unit * pol.qty * (1 - (pol.discount) / 100.0))
return self.total_invoiced or False
def _paid_total_2(self):
return self.total or 0.0
def _get_sum_dis_2(self):
return self.discount or 0.0
def _get_sum_discount(self, form):
#code for the sum of discount value
pos_obj = self.pool.get('pos.order')
user_obj = self.pool.get('res.users')
user_ids = form['user_ids'] or self._get_all_users()
company_id = user_obj.browse(self.cr, self.uid, self.uid).company_id.id
pos_ids = pos_obj.search(self.cr, self.uid, [('date_order','>=',form['date_start'] + ' 00:00:00'),('date_order','<=',form['date_end'] + ' 23:59:59'),('user_id','in',user_ids),('company_id','=',company_id)])
for pos in pos_obj.browse(self.cr, self.uid, pos_ids):
for pol in pos.lines:
self.total_discount += ((pol.price_unit * pol.qty) * (pol.discount / 100))
return self.total_discount or False
def _get_payments(self, form):
statement_line_obj = self.pool.get("account.bank.statement.line")
pos_order_obj = self.pool.get("pos.order")
user_ids = form['user_ids'] or self._get_all_users()
company_id = self.pool['res.users'].browse(self.cr, self.uid, self.uid).company_id.id
pos_ids = pos_order_obj.search(self.cr, self.uid, [('date_order','>=',form['date_start'] + ' 00:00:00'),('date_order','<=',form['date_end'] + ' 23:59:59'),('state','in',['paid','invoiced','done']),('user_id','in',user_ids), ('company_id', '=', company_id)])
data={}
if pos_ids:
st_line_ids = statement_line_obj.search(self.cr, self.uid, [('pos_statement_id', 'in', pos_ids)])
if st_line_ids:
st_id = statement_line_obj.browse(self.cr, self.uid, st_line_ids)
a_l=[]
for r in st_id:
a_l.append(r['id'])
self.cr.execute("select aj.name,sum(amount) from account_bank_statement_line as absl,account_bank_statement as abs,account_journal as aj " \
"where absl.statement_id = abs.id and abs.journal_id = aj.id and absl.id IN %s " \
"group by aj.name ",(tuple(a_l),))
data = self.cr.dictfetchall()
return data
else:
return {}
def _total_of_the_day(self, objects):
return self.total or 0.00
def _sum_invoice(self, objects):
return reduce(lambda acc, obj:
acc + obj.invoice_id.amount_total,
[o for o in objects if o.invoice_id and o.invoice_id.number],
0.0)
def _ellipsis(self, orig_str, maxlen=100, ellipsis='...'):
maxlen = maxlen - len(ellipsis)
if maxlen <= 0:
maxlen = 1
new_str = orig_str[:maxlen]
return new_str
def _strip_name(self, name, maxlen=50):
return self._ellipsis(name, maxlen, ' ...')
def _get_tax_amount(self, form):
taxes = {}
account_tax_obj = self.pool.get('account.tax')
user_ids = form['user_ids'] or self._get_all_users()
pos_order_obj = self.pool.get('pos.order')
company_id = self.pool['res.users'].browse(self.cr, self.uid, self.uid).company_id.id
pos_ids = pos_order_obj.search(self.cr, self.uid, [('date_order','>=',form['date_start'] + ' 00:00:00'),('date_order','<=',form['date_end'] + ' 23:59:59'),('state','in',['paid','invoiced','done']),('user_id','in',user_ids), ('company_id', '=', company_id)])
for order in pos_order_obj.browse(self.cr, self.uid, pos_ids):
for line in order.lines:
line_taxes = account_tax_obj.compute_all(self.cr, self.uid, line.product_id.taxes_id, line.price_unit * (1-(line.discount or 0.0)/100.0), line.qty, product=line.product_id, partner=line.order_id.partner_id or False)
for tax in line_taxes['taxes']:
taxes.setdefault(tax['id'], {'name': tax['name'], 'amount':0.0})
taxes[tax['id']]['amount'] += tax['amount']
return taxes.values()
def _get_user_names(self, user_ids):
user_obj = self.pool.get('res.users')
return ', '.join(map(lambda x: x.name, user_obj.browse(self.cr, self.uid, user_ids)))
def __init__(self, cr, uid, name, context):
super(pos_details, self).__init__(cr, uid, name, context=context)
self.total = 0.0
self.qty = 0.0
self.total_invoiced = 0.0
self.discount = 0.0
self.total_discount = 0.0
self.localcontext.update({
'time': time,
'strip_name': self._strip_name,
'getpayments': self._get_payments,
'getsumdisc': self._get_sum_discount,
'gettotaloftheday': self._total_of_the_day,
'gettaxamount': self._get_tax_amount,
'pos_sales_details':self._pos_sales_details,
'getqtytotal2': self._get_qty_total_2,
'getsalestotal2': self._get_sales_total_2,
'getsuminvoice2':self._get_sum_invoice_2,
'getpaidtotal2': self._paid_total_2,
'getinvoice':self._get_invoice,
'get_user_names': self._get_user_names,
})
class report_pos_details(osv.AbstractModel):
_name = 'report.point_of_sale.report_detailsofsales'
_inherit = 'report.abstract_report'
_template = 'point_of_sale.report_detailsofsales'
_wrapped_report_class = pos_details
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
jwkozel/demobx | boxsdk/network/default_network.py | 7 | 2014 | # coding: utf-8
from __future__ import unicode_literals
import requests
import time
from .network_interface import Network, NetworkResponse
class DefaultNetwork(Network):
"""Implementation of the network interface using the requests library."""
def __init__(self):
super(DefaultNetwork, self).__init__()
self._session = requests.Session()
def request(self, method, url, access_token, **kwargs):
"""Base class override.
Make a network request using a requests.Session.
"""
return DefaultNetworkResponse(self._session.request(method, url, **kwargs), access_token)
def retry_after(self, delay, request_method, *args, **kwargs):
"""Base class override.
Retry after sleeping for delay seconds.
"""
time.sleep(delay)
return request_method(*args, **kwargs)
class DefaultNetworkResponse(NetworkResponse):
"""Implementation of the network interface using the requests library."""
def __init__(self, request_response, access_token_used):
self._request_response = request_response
self._access_token_used = access_token_used
def json(self):
"""Base class override."""
return self._request_response.json()
@property
def content(self):
"""Base class override."""
return self._request_response.content
@property
def status_code(self):
"""Base class override."""
return self._request_response.status_code
@property
def ok(self):
"""Base class override."""
# pylint:disable=invalid-name
return self._request_response.ok
@property
def headers(self):
"""Base class override."""
return self._request_response.headers
@property
def response_as_stream(self):
"""Base class override."""
return self._request_response.raw
@property
def access_token_used(self):
"""Base class override."""
return self._access_token_used
| apache-2.0 |
HesselTjeerdsma/Cyber-Physical-Pacman-Game | Algor/flask/lib/python2.7/site-packages/scipy/sparse/linalg/_norm.py | 83 | 5867 | """Sparse matrix norms.
"""
from __future__ import division, print_function, absolute_import
import numpy as np
from scipy.sparse import issparse
from numpy.core import Inf, sqrt, abs
__all__ = ['norm']
def _sparse_frobenius_norm(x):
if np.issubdtype(x.dtype, np.complexfloating):
sqnorm = abs(x).power(2).sum()
else:
sqnorm = x.power(2).sum()
return sqrt(sqnorm)
def norm(x, ord=None, axis=None):
"""
Norm of a sparse matrix
This function is able to return one of seven different matrix norms,
depending on the value of the ``ord`` parameter.
Parameters
----------
x : a sparse matrix
Input sparse matrix.
ord : {non-zero int, inf, -inf, 'fro'}, optional
Order of the norm (see table under ``Notes``). inf means numpy's
`inf` object.
axis : {int, 2-tuple of ints, None}, optional
If `axis` is an integer, it specifies the axis of `x` along which to
compute the vector norms. If `axis` is a 2-tuple, it specifies the
axes that hold 2-D matrices, and the matrix norms of these matrices
are computed. If `axis` is None then either a vector norm (when `x`
is 1-D) or a matrix norm (when `x` is 2-D) is returned.
Returns
-------
n : float or ndarray
Notes
-----
Some of the ord are not implemented because some associated functions like,
_multi_svd_norm, are not yet available for sparse matrix.
This docstring is modified based on numpy.linalg.norm.
https://github.com/numpy/numpy/blob/master/numpy/linalg/linalg.py
The following norms can be calculated:
===== ============================
ord norm for sparse matrices
===== ============================
None Frobenius norm
'fro' Frobenius norm
inf max(sum(abs(x), axis=1))
-inf min(sum(abs(x), axis=1))
0 abs(x).sum(axis=axis)
1 max(sum(abs(x), axis=0))
-1 min(sum(abs(x), axis=0))
2 Not implemented
-2 Not implemented
other Not implemented
===== ============================
The Frobenius norm is given by [1]_:
:math:`||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}`
References
----------
.. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*,
Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15
Examples
--------
>>> from scipy.sparse import *
>>> import numpy as np
>>> from scipy.sparse.linalg import norm
>>> a = np.arange(9) - 4
>>> a
array([-4, -3, -2, -1, 0, 1, 2, 3, 4])
>>> b = a.reshape((3, 3))
>>> b
array([[-4, -3, -2],
[-1, 0, 1],
[ 2, 3, 4]])
>>> b = csr_matrix(b)
>>> norm(b)
7.745966692414834
>>> norm(b, 'fro')
7.745966692414834
>>> norm(b, np.inf)
9
>>> norm(b, -np.inf)
2
>>> norm(b, 1)
7
>>> norm(b, -1)
6
"""
if not issparse(x):
raise TypeError("input is not sparse. use numpy.linalg.norm")
# Check the default case first and handle it immediately.
if axis is None and ord in (None, 'fro', 'f'):
return _sparse_frobenius_norm(x)
# Some norms require functions that are not implemented for all types.
x = x.tocsr()
if axis is None:
axis = (0, 1)
elif not isinstance(axis, tuple):
msg = "'axis' must be None, an integer or a tuple of integers"
try:
int_axis = int(axis)
except TypeError:
raise TypeError(msg)
if axis != int_axis:
raise TypeError(msg)
axis = (int_axis,)
nd = 2
if len(axis) == 2:
row_axis, col_axis = axis
if not (-nd <= row_axis < nd and -nd <= col_axis < nd):
raise ValueError('Invalid axis %r for an array with shape %r' %
(axis, x.shape))
if row_axis % nd == col_axis % nd:
raise ValueError('Duplicate axes given.')
if ord == 2:
raise NotImplementedError
#return _multi_svd_norm(x, row_axis, col_axis, amax)
elif ord == -2:
raise NotImplementedError
#return _multi_svd_norm(x, row_axis, col_axis, amin)
elif ord == 1:
return abs(x).sum(axis=row_axis).max(axis=col_axis)[0,0]
elif ord == Inf:
return abs(x).sum(axis=col_axis).max(axis=row_axis)[0,0]
elif ord == -1:
return abs(x).sum(axis=row_axis).min(axis=col_axis)[0,0]
elif ord == -Inf:
return abs(x).sum(axis=col_axis).min(axis=row_axis)[0,0]
elif ord in (None, 'f', 'fro'):
# The axis order does not matter for this norm.
return _sparse_frobenius_norm(x)
else:
raise ValueError("Invalid norm order for matrices.")
elif len(axis) == 1:
a, = axis
if not (-nd <= a < nd):
raise ValueError('Invalid axis %r for an array with shape %r' %
(axis, x.shape))
if ord == Inf:
M = abs(x).max(axis=a)
elif ord == -Inf:
M = abs(x).min(axis=a)
elif ord == 0:
# Zero norm
M = (x != 0).sum(axis=a)
elif ord == 1:
# special case for speedup
M = abs(x).sum(axis=a)
elif ord in (2, None):
M = sqrt(abs(x).power(2).sum(axis=a))
else:
try:
ord + 1
except TypeError:
raise ValueError('Invalid norm order for vectors.')
M = np.power(abs(x).power(ord).sum(axis=a), 1 / ord)
return M.A.ravel()
else:
raise ValueError("Improper number of dimensions to norm.")
| apache-2.0 |
xyuanmu/XX-Net | python3.8.2/Lib/email/feedparser.py | 26 | 22780 | # Copyright (C) 2004-2006 Python Software Foundation
# Authors: Baxter, Wouters and Warsaw
# Contact: email-sig@python.org
"""FeedParser - An email feed parser.
The feed parser implements an interface for incrementally parsing an email
message, line by line. This has advantages for certain applications, such as
those reading email messages off a socket.
FeedParser.feed() is the primary interface for pushing new data into the
parser. It returns when there's nothing more it can do with the available
data. When you have no more data to push into the parser, call .close().
This completes the parsing and returns the root message object.
The other advantage of this parser is that it will never raise a parsing
exception. Instead, when it finds something unexpected, it adds a 'defect' to
the current message. Defects are just instances that live on the message
object's .defects attribute.
"""
__all__ = ['FeedParser', 'BytesFeedParser']
import re
from email import errors
from email._policybase import compat32
from collections import deque
from io import StringIO
NLCRE = re.compile(r'\r\n|\r|\n')
NLCRE_bol = re.compile(r'(\r\n|\r|\n)')
NLCRE_eol = re.compile(r'(\r\n|\r|\n)\Z')
NLCRE_crack = re.compile(r'(\r\n|\r|\n)')
# RFC 2822 $3.6.8 Optional fields. ftext is %d33-57 / %d59-126, Any character
# except controls, SP, and ":".
headerRE = re.compile(r'^(From |[\041-\071\073-\176]*:|[\t ])')
EMPTYSTRING = ''
NL = '\n'
NeedMoreData = object()
class BufferedSubFile(object):
"""A file-ish object that can have new data loaded into it.
You can also push and pop line-matching predicates onto a stack. When the
current predicate matches the current line, a false EOF response
(i.e. empty string) is returned instead. This lets the parser adhere to a
simple abstraction -- it parses until EOF closes the current message.
"""
def __init__(self):
# Text stream of the last partial line pushed into this object.
# See issue 22233 for why this is a text stream and not a list.
self._partial = StringIO(newline='')
# A deque of full, pushed lines
self._lines = deque()
# The stack of false-EOF checking predicates.
self._eofstack = []
# A flag indicating whether the file has been closed or not.
self._closed = False
def push_eof_matcher(self, pred):
self._eofstack.append(pred)
def pop_eof_matcher(self):
return self._eofstack.pop()
def close(self):
# Don't forget any trailing partial line.
self._partial.seek(0)
self.pushlines(self._partial.readlines())
self._partial.seek(0)
self._partial.truncate()
self._closed = True
def readline(self):
if not self._lines:
if self._closed:
return ''
return NeedMoreData
# Pop the line off the stack and see if it matches the current
# false-EOF predicate.
line = self._lines.popleft()
# RFC 2046, section 5.1.2 requires us to recognize outer level
# boundaries at any level of inner nesting. Do this, but be sure it's
# in the order of most to least nested.
for ateof in reversed(self._eofstack):
if ateof(line):
# We're at the false EOF. But push the last line back first.
self._lines.appendleft(line)
return ''
return line
def unreadline(self, line):
# Let the consumer push a line back into the buffer.
assert line is not NeedMoreData
self._lines.appendleft(line)
def push(self, data):
"""Push some new data into this object."""
self._partial.write(data)
if '\n' not in data and '\r' not in data:
# No new complete lines, wait for more.
return
# Crack into lines, preserving the linesep characters.
self._partial.seek(0)
parts = self._partial.readlines()
self._partial.seek(0)
self._partial.truncate()
# If the last element of the list does not end in a newline, then treat
# it as a partial line. We only check for '\n' here because a line
# ending with '\r' might be a line that was split in the middle of a
# '\r\n' sequence (see bugs 1555570 and 1721862).
if not parts[-1].endswith('\n'):
self._partial.write(parts.pop())
self.pushlines(parts)
def pushlines(self, lines):
self._lines.extend(lines)
def __iter__(self):
return self
def __next__(self):
line = self.readline()
if line == '':
raise StopIteration
return line
class FeedParser:
"""A feed-style parser of email."""
def __init__(self, _factory=None, *, policy=compat32):
"""_factory is called with no arguments to create a new message obj
The policy keyword specifies a policy object that controls a number of
aspects of the parser's operation. The default policy maintains
backward compatibility.
"""
self.policy = policy
self._old_style_factory = False
if _factory is None:
if policy.message_factory is None:
from email.message import Message
self._factory = Message
else:
self._factory = policy.message_factory
else:
self._factory = _factory
try:
_factory(policy=self.policy)
except TypeError:
# Assume this is an old-style factory
self._old_style_factory = True
self._input = BufferedSubFile()
self._msgstack = []
self._parse = self._parsegen().__next__
self._cur = None
self._last = None
self._headersonly = False
# Non-public interface for supporting Parser's headersonly flag
def _set_headersonly(self):
self._headersonly = True
def feed(self, data):
"""Push more data into the parser."""
self._input.push(data)
self._call_parse()
def _call_parse(self):
try:
self._parse()
except StopIteration:
pass
def close(self):
"""Parse all remaining data and return the root message object."""
self._input.close()
self._call_parse()
root = self._pop_message()
assert not self._msgstack
# Look for final set of defects
if root.get_content_maintype() == 'multipart' \
and not root.is_multipart():
defect = errors.MultipartInvariantViolationDefect()
self.policy.handle_defect(root, defect)
return root
def _new_message(self):
if self._old_style_factory:
msg = self._factory()
else:
msg = self._factory(policy=self.policy)
if self._cur and self._cur.get_content_type() == 'multipart/digest':
msg.set_default_type('message/rfc822')
if self._msgstack:
self._msgstack[-1].attach(msg)
self._msgstack.append(msg)
self._cur = msg
self._last = msg
def _pop_message(self):
retval = self._msgstack.pop()
if self._msgstack:
self._cur = self._msgstack[-1]
else:
self._cur = None
return retval
def _parsegen(self):
# Create a new message and start by parsing headers.
self._new_message()
headers = []
# Collect the headers, searching for a line that doesn't match the RFC
# 2822 header or continuation pattern (including an empty line).
for line in self._input:
if line is NeedMoreData:
yield NeedMoreData
continue
if not headerRE.match(line):
# If we saw the RFC defined header/body separator
# (i.e. newline), just throw it away. Otherwise the line is
# part of the body so push it back.
if not NLCRE.match(line):
defect = errors.MissingHeaderBodySeparatorDefect()
self.policy.handle_defect(self._cur, defect)
self._input.unreadline(line)
break
headers.append(line)
# Done with the headers, so parse them and figure out what we're
# supposed to see in the body of the message.
self._parse_headers(headers)
# Headers-only parsing is a backwards compatibility hack, which was
# necessary in the older parser, which could raise errors. All
# remaining lines in the input are thrown into the message body.
if self._headersonly:
lines = []
while True:
line = self._input.readline()
if line is NeedMoreData:
yield NeedMoreData
continue
if line == '':
break
lines.append(line)
self._cur.set_payload(EMPTYSTRING.join(lines))
return
if self._cur.get_content_type() == 'message/delivery-status':
# message/delivery-status contains blocks of headers separated by
# a blank line. We'll represent each header block as a separate
# nested message object, but the processing is a bit different
# than standard message/* types because there is no body for the
# nested messages. A blank line separates the subparts.
while True:
self._input.push_eof_matcher(NLCRE.match)
for retval in self._parsegen():
if retval is NeedMoreData:
yield NeedMoreData
continue
break
msg = self._pop_message()
# We need to pop the EOF matcher in order to tell if we're at
# the end of the current file, not the end of the last block
# of message headers.
self._input.pop_eof_matcher()
# The input stream must be sitting at the newline or at the
# EOF. We want to see if we're at the end of this subpart, so
# first consume the blank line, then test the next line to see
# if we're at this subpart's EOF.
while True:
line = self._input.readline()
if line is NeedMoreData:
yield NeedMoreData
continue
break
while True:
line = self._input.readline()
if line is NeedMoreData:
yield NeedMoreData
continue
break
if line == '':
break
# Not at EOF so this is a line we're going to need.
self._input.unreadline(line)
return
if self._cur.get_content_maintype() == 'message':
# The message claims to be a message/* type, then what follows is
# another RFC 2822 message.
for retval in self._parsegen():
if retval is NeedMoreData:
yield NeedMoreData
continue
break
self._pop_message()
return
if self._cur.get_content_maintype() == 'multipart':
boundary = self._cur.get_boundary()
if boundary is None:
# The message /claims/ to be a multipart but it has not
# defined a boundary. That's a problem which we'll handle by
# reading everything until the EOF and marking the message as
# defective.
defect = errors.NoBoundaryInMultipartDefect()
self.policy.handle_defect(self._cur, defect)
lines = []
for line in self._input:
if line is NeedMoreData:
yield NeedMoreData
continue
lines.append(line)
self._cur.set_payload(EMPTYSTRING.join(lines))
return
# Make sure a valid content type was specified per RFC 2045:6.4.
if (str(self._cur.get('content-transfer-encoding', '8bit')).lower()
not in ('7bit', '8bit', 'binary')):
defect = errors.InvalidMultipartContentTransferEncodingDefect()
self.policy.handle_defect(self._cur, defect)
# Create a line match predicate which matches the inter-part
# boundary as well as the end-of-multipart boundary. Don't push
# this onto the input stream until we've scanned past the
# preamble.
separator = '--' + boundary
boundaryre = re.compile(
'(?P<sep>' + re.escape(separator) +
r')(?P<end>--)?(?P<ws>[ \t]*)(?P<linesep>\r\n|\r|\n)?$')
capturing_preamble = True
preamble = []
linesep = False
close_boundary_seen = False
while True:
line = self._input.readline()
if line is NeedMoreData:
yield NeedMoreData
continue
if line == '':
break
mo = boundaryre.match(line)
if mo:
# If we're looking at the end boundary, we're done with
# this multipart. If there was a newline at the end of
# the closing boundary, then we need to initialize the
# epilogue with the empty string (see below).
if mo.group('end'):
close_boundary_seen = True
linesep = mo.group('linesep')
break
# We saw an inter-part boundary. Were we in the preamble?
if capturing_preamble:
if preamble:
# According to RFC 2046, the last newline belongs
# to the boundary.
lastline = preamble[-1]
eolmo = NLCRE_eol.search(lastline)
if eolmo:
preamble[-1] = lastline[:-len(eolmo.group(0))]
self._cur.preamble = EMPTYSTRING.join(preamble)
capturing_preamble = False
self._input.unreadline(line)
continue
# We saw a boundary separating two parts. Consume any
# multiple boundary lines that may be following. Our
# interpretation of RFC 2046 BNF grammar does not produce
# body parts within such double boundaries.
while True:
line = self._input.readline()
if line is NeedMoreData:
yield NeedMoreData
continue
mo = boundaryre.match(line)
if not mo:
self._input.unreadline(line)
break
# Recurse to parse this subpart; the input stream points
# at the subpart's first line.
self._input.push_eof_matcher(boundaryre.match)
for retval in self._parsegen():
if retval is NeedMoreData:
yield NeedMoreData
continue
break
# Because of RFC 2046, the newline preceding the boundary
# separator actually belongs to the boundary, not the
# previous subpart's payload (or epilogue if the previous
# part is a multipart).
if self._last.get_content_maintype() == 'multipart':
epilogue = self._last.epilogue
if epilogue == '':
self._last.epilogue = None
elif epilogue is not None:
mo = NLCRE_eol.search(epilogue)
if mo:
end = len(mo.group(0))
self._last.epilogue = epilogue[:-end]
else:
payload = self._last._payload
if isinstance(payload, str):
mo = NLCRE_eol.search(payload)
if mo:
payload = payload[:-len(mo.group(0))]
self._last._payload = payload
self._input.pop_eof_matcher()
self._pop_message()
# Set the multipart up for newline cleansing, which will
# happen if we're in a nested multipart.
self._last = self._cur
else:
# I think we must be in the preamble
assert capturing_preamble
preamble.append(line)
# We've seen either the EOF or the end boundary. If we're still
# capturing the preamble, we never saw the start boundary. Note
# that as a defect and store the captured text as the payload.
if capturing_preamble:
defect = errors.StartBoundaryNotFoundDefect()
self.policy.handle_defect(self._cur, defect)
self._cur.set_payload(EMPTYSTRING.join(preamble))
epilogue = []
for line in self._input:
if line is NeedMoreData:
yield NeedMoreData
continue
self._cur.epilogue = EMPTYSTRING.join(epilogue)
return
# If we're not processing the preamble, then we might have seen
# EOF without seeing that end boundary...that is also a defect.
if not close_boundary_seen:
defect = errors.CloseBoundaryNotFoundDefect()
self.policy.handle_defect(self._cur, defect)
return
# Everything from here to the EOF is epilogue. If the end boundary
# ended in a newline, we'll need to make sure the epilogue isn't
# None
if linesep:
epilogue = ['']
else:
epilogue = []
for line in self._input:
if line is NeedMoreData:
yield NeedMoreData
continue
epilogue.append(line)
# Any CRLF at the front of the epilogue is not technically part of
# the epilogue. Also, watch out for an empty string epilogue,
# which means a single newline.
if epilogue:
firstline = epilogue[0]
bolmo = NLCRE_bol.match(firstline)
if bolmo:
epilogue[0] = firstline[len(bolmo.group(0)):]
self._cur.epilogue = EMPTYSTRING.join(epilogue)
return
# Otherwise, it's some non-multipart type, so the entire rest of the
# file contents becomes the payload.
lines = []
for line in self._input:
if line is NeedMoreData:
yield NeedMoreData
continue
lines.append(line)
self._cur.set_payload(EMPTYSTRING.join(lines))
def _parse_headers(self, lines):
# Passed a list of lines that make up the headers for the current msg
lastheader = ''
lastvalue = []
for lineno, line in enumerate(lines):
# Check for continuation
if line[0] in ' \t':
if not lastheader:
# The first line of the headers was a continuation. This
# is illegal, so let's note the defect, store the illegal
# line, and ignore it for purposes of headers.
defect = errors.FirstHeaderLineIsContinuationDefect(line)
self.policy.handle_defect(self._cur, defect)
continue
lastvalue.append(line)
continue
if lastheader:
self._cur.set_raw(*self.policy.header_source_parse(lastvalue))
lastheader, lastvalue = '', []
# Check for envelope header, i.e. unix-from
if line.startswith('From '):
if lineno == 0:
# Strip off the trailing newline
mo = NLCRE_eol.search(line)
if mo:
line = line[:-len(mo.group(0))]
self._cur.set_unixfrom(line)
continue
elif lineno == len(lines) - 1:
# Something looking like a unix-from at the end - it's
# probably the first line of the body, so push back the
# line and stop.
self._input.unreadline(line)
return
else:
# Weirdly placed unix-from line. Note this as a defect
# and ignore it.
defect = errors.MisplacedEnvelopeHeaderDefect(line)
self._cur.defects.append(defect)
continue
# Split the line on the colon separating field name from value.
# There will always be a colon, because if there wasn't the part of
# the parser that calls us would have started parsing the body.
i = line.find(':')
# If the colon is on the start of the line the header is clearly
# malformed, but we might be able to salvage the rest of the
# message. Track the error but keep going.
if i == 0:
defect = errors.InvalidHeaderDefect("Missing header name.")
self._cur.defects.append(defect)
continue
assert i>0, "_parse_headers fed line with no : and no leading WS"
lastheader = line[:i]
lastvalue = [line]
# Done with all the lines, so handle the last header.
if lastheader:
self._cur.set_raw(*self.policy.header_source_parse(lastvalue))
class BytesFeedParser(FeedParser):
"""Like FeedParser, but feed accepts bytes."""
def feed(self, data):
super().feed(data.decode('ascii', 'surrogateescape'))
| bsd-2-clause |
akchinSTC/systemml | projects/breast_cancer/breastcancer/preprocessing.py | 3 | 27672 | #-------------------------------------------------------------
#
# 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"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
#-------------------------------------------------------------
"""
Preprocessing -- Predicting Breast Cancer Proliferation Scores with
Apache SystemML
This module contains functions for the preprocessing phase of the
breast cancer project.
"""
import math
import os
import numpy as np
import openslide
from openslide.deepzoom import DeepZoomGenerator
import pandas as pd
from pyspark.ml.linalg import Vectors
import pyspark.sql.functions as F
from scipy.ndimage.morphology import binary_fill_holes
from skimage.color import rgb2gray
from skimage.feature import canny
from skimage.morphology import binary_closing, binary_dilation, disk
# Open Whole-Slide Image
def open_slide(slide_num, folder, training):
"""
Open a whole-slide image, given an image number.
Args:
slide_num: Slide image number as an integer.
folder: Directory in which the slides folder is stored, as a string.
This should contain either a `training_image_data` folder with
images in the format `TUPAC-TR-###.svs`, or a `testing_image_data`
folder with images in the format `TUPAC-TE-###.svs`.
training: Boolean for training or testing datasets.
Returns:
An OpenSlide object representing a whole-slide image.
"""
if training:
filename = os.path.join(folder, "training_image_data",
"TUPAC-TR-{}.svs".format(str(slide_num).zfill(3)))
else:
# Testing images
filename = os.path.join(folder, "testing_image_data",
"TUPAC-TE-{}.svs".format(str(slide_num).zfill(3)))
slide = openslide.open_slide(filename)
return slide
# Create Tile Generator
def create_tile_generator(slide, tile_size, overlap):
"""
Create a tile generator for the given slide.
This generator is able to extract tiles from the overall
whole-slide image.
Args:
slide: An OpenSlide object representing a whole-slide image.
tile_size: The width and height of a square tile to be generated.
overlap: Number of pixels by which to overlap the tiles.
Returns:
A DeepZoomGenerator object representing the tile generator. Each
extracted tile is a PIL Image with shape
(tile_size, tile_size, channels).
Note: This generator is not a true "Python generator function", but
rather is an object that is capable of extracting individual tiles.
"""
generator = DeepZoomGenerator(slide, tile_size=tile_size, overlap=overlap, limit_bounds=True)
return generator
# Determine 20x Magnification Zoom Level
def get_20x_zoom_level(slide, generator):
"""
Return the zoom level that corresponds to a 20x magnification.
The generator can extract tiles from multiple zoom levels,
downsampling by a factor of 2 per level from highest to lowest
resolution.
Args:
slide: An OpenSlide object representing a whole-slide image.
generator: A DeepZoomGenerator object representing a tile generator.
Note: This generator is not a true "Python generator function",
but rather is an object that is capable of extracting individual
tiles.
Returns:
Zoom level corresponding to a 20x magnification, or as close as
possible.
"""
highest_zoom_level = generator.level_count - 1 # 0-based indexing
try:
mag = int(slide.properties[openslide.PROPERTY_NAME_OBJECTIVE_POWER])
# `mag / 20` gives the downsampling factor between the slide's
# magnification and the desired 20x magnification.
# `(mag / 20) / 2` gives the zoom level offset from the highest
# resolution level, based on a 2x downsampling factor in the
# generator.
offset = math.floor((mag / 20) / 2)
level = highest_zoom_level - offset
except ValueError:
# In case the slide magnification level is unknown, just
# use the highest resolution.
level = highest_zoom_level
return level
# Generate Tile Indices For Whole-Slide Image.
def process_slide(slide_num, folder, training, tile_size, overlap):
"""
Generate all possible tile indices for a whole-slide image.
Given a slide number, tile size, and overlap, generate
all possible (slide_num, tile_size, overlap, zoom_level, col, row)
indices.
Args:
slide_num: Slide image number as an integer.
folder: Directory in which the slides folder is stored, as a string.
This should contain either a `training_image_data` folder with
images in the format `TUPAC-TR-###.svs`, or a `testing_image_data`
folder with images in the format `TUPAC-TE-###.svs`.
training: Boolean for training or testing datasets.
tile_size: The width and height of a square tile to be generated.
overlap: Number of pixels by which to overlap the tiles.
Returns:
A list of (slide_num, tile_size, overlap, zoom_level, col, row)
integer index tuples representing possible tiles to extract.
"""
# Open slide.
slide = open_slide(slide_num, folder, training)
# Create tile generator.
generator = create_tile_generator(slide, tile_size, overlap)
# Get 20x zoom level.
zoom_level = get_20x_zoom_level(slide, generator)
# Generate all possible (zoom_level, col, row) tile index tuples.
cols, rows = generator.level_tiles[zoom_level]
tile_indices = [(slide_num, tile_size, overlap, zoom_level, col, row)
for col in range(cols) for row in range(rows)]
return tile_indices
# Generate Tile From Tile Index
def process_tile_index(tile_index, folder, training):
"""
Generate a tile from a tile index.
Given a (slide_num, tile_size, overlap, zoom_level, col, row) tile
index, generate a (slide_num, tile) tuple.
Args:
tile_index: A (slide_num, tile_size, overlap, zoom_level, col, row)
integer index tuple representing a tile to extract.
folder: Directory in which the slides folder is stored, as a string.
This should contain either a `training_image_data` folder with
images in the format `TUPAC-TR-###.svs`, or a `testing_image_data`
folder with images in the format `TUPAC-TE-###.svs`.
training: Boolean for training or testing datasets.
Returns:
A (slide_num, tile) tuple, where slide_num is an integer, and tile
is a 3D NumPy array of shape (tile_size, tile_size, channels) in
RGB format.
"""
slide_num, tile_size, overlap, zoom_level, col, row = tile_index
# Open slide.
slide = open_slide(slide_num, folder, training)
# Create tile generator.
generator = create_tile_generator(slide, tile_size, overlap)
# Generate tile.
tile = np.asarray(generator.get_tile(zoom_level, (col, row)))
return (slide_num, tile)
# Filter Tile For Dimensions & Tissue Threshold
def optical_density(tile):
"""
Convert a tile to optical density values.
Args:
tile: A 3D NumPy array of shape (tile_size, tile_size, channels).
Returns:
A 3D NumPy array of shape (tile_size, tile_size, channels)
representing optical density values.
"""
tile = tile.astype(np.float64)
#od = -np.log10(tile/255 + 1e-8)
od = -np.log((tile+1)/240)
return od
def keep_tile(tile_tuple, tile_size, tissue_threshold):
"""
Determine if a tile should be kept.
This filters out tiles based on size and a tissue percentage
threshold, using a custom algorithm. If a tile has height &
width equal to (tile_size, tile_size), and contains greater
than or equal to the given percentage, then it will be kept;
otherwise it will be filtered out.
Args:
tile_tuple: A (slide_num, tile) tuple, where slide_num is an
integer, and tile is a 3D NumPy array of shape
(tile_size, tile_size, channels) in RGB format.
tile_size: The width and height of a square tile to be generated.
tissue_threshold: Tissue percentage threshold.
Returns:
A Boolean indicating whether or not a tile should be kept for
future usage.
"""
slide_num, tile = tile_tuple
if tile.shape[0:2] == (tile_size, tile_size):
tile_orig = tile
# Check 1
# Convert 3D RGB image to 2D grayscale image, from
# 0 (dense tissue) to 1 (plain background).
tile = rgb2gray(tile)
# 8-bit depth complement, from 1 (dense tissue)
# to 0 (plain background).
tile = 1 - tile
# Canny edge detection with hysteresis thresholding.
# This returns a binary map of edges, with 1 equal to
# an edge. The idea is that tissue would be full of
# edges, while background would not.
tile = canny(tile)
# Binary closing, which is a dilation followed by
# an erosion. This removes small dark spots, which
# helps remove noise in the background.
tile = binary_closing(tile, disk(10))
# Binary dilation, which enlarges bright areas,
# and shrinks dark areas. This helps fill in holes
# within regions of tissue.
tile = binary_dilation(tile, disk(10))
# Fill remaining holes within regions of tissue.
tile = binary_fill_holes(tile)
# Calculate percentage of tissue coverage.
percentage = tile.mean()
check1 = percentage >= tissue_threshold
# Check 2
# Convert to optical density values
tile = optical_density(tile_orig)
# Threshold at beta
beta = 0.15
tile = np.min(tile, axis=2) >= beta
# Apply morphology for same reasons as above.
tile = binary_closing(tile, disk(2))
tile = binary_dilation(tile, disk(2))
tile = binary_fill_holes(tile)
percentage = tile.mean()
check2 = percentage >= tissue_threshold
return check1 and check2
else:
return False
# Generate Samples From Tile
def process_tile(tile_tuple, sample_size, grayscale):
"""
Process a tile into a group of smaller samples.
Cut up a tile into smaller blocks of sample_size x sample_size pixels,
change the shape of each sample from (H, W, channels) to
(channels, H, W), then flatten each into a vector of length
channels*H*W.
Args:
tile_tuple: A (slide_num, tile) tuple, where slide_num is an
integer, and tile is a 3D NumPy array of shape
(tile_size, tile_size, channels).
sample_size: The new width and height of the square samples to be
generated.
grayscale: Whether or not to generate grayscale samples, rather
than RGB.
Returns:
A list of (slide_num, sample) tuples representing cut up tiles,
where each sample is a 3D NumPy array of shape
(sample_size_x, sample_size_y, channels).
"""
slide_num, tile = tile_tuple
if grayscale:
tile = rgb2gray(tile)[:, :, np.newaxis] # Grayscale
# Save disk space and future IO time by converting from [0,1] to [0,255],
# at the expense of some minor loss of information.
tile = np.round(tile * 255).astype("uint8")
x, y, ch = tile.shape
# 1. Reshape into a 5D array of (num_x, sample_size_x, num_y, sample_size_y, ch), where
# num_x and num_y are the number of chopped tiles on the x and y axes, respectively.
# 2. Swap sample_size_x and num_y axes to create
# (num_x, num_y, sample_size_x, sample_size_y, ch).
# 3. Combine num_x and num_y into single axis, returning
# (num_samples, sample_size_x, sample_size_y, ch).
samples = (tile.reshape((x // sample_size, sample_size, y // sample_size, sample_size, ch))
.swapaxes(1,2)
.reshape((-1, sample_size, sample_size, ch)))
samples = [(slide_num, sample) for sample in list(samples)]
return samples
# Normalize staining
def normalize_staining(sample_tuple, beta=0.15, alpha=1, light_intensity=255):
"""
Normalize the staining of H&E histology slides.
This function normalizes the staining of H&E histology slides.
References:
- Macenko, Marc, et al. "A method for normalizing histology slides
for quantitative analysis." Biomedical Imaging: From Nano to Macro,
2009. ISBI'09. IEEE International Symposium on. IEEE, 2009.
- http://wwwx.cs.unc.edu/~mn/sites/default/files/macenko2009.pdf
- https://github.com/mitkovetta/staining-normalization
Args:
sample_tuple: A (slide_num, sample) tuple, where slide_num is an
integer, and sample is a 3D NumPy array of shape (H,W,C).
Returns:
A (slide_num, sample) tuple, where the sample is a 3D NumPy array
of shape (H,W,C) that has been stain normalized.
"""
# Setup.
slide_num, sample = sample_tuple
x = np.asarray(sample)
h, w, c = x.shape
x = x.reshape(-1, c).astype(np.float64) # shape (H*W, C)
# Reference stain vectors and stain saturations. We will normalize all slides
# to these references. To create these, grab the stain vectors and stain
# saturations from a desirable slide.
# Values in reference implementation for use with eigendecomposition approach, natural log,
# and `light_intensity=240`.
#stain_ref = np.array([0.5626, 0.2159, 0.7201, 0.8012, 0.4062, 0.5581]).reshape(3,2)
#max_sat_ref = np.array([1.9705, 1.0308]).reshape(2,1)
# SVD w/ log10, and `light_intensity=255`.
stain_ref = (np.array([0.54598845, 0.322116, 0.72385198, 0.76419107, 0.42182333, 0.55879629])
.reshape(3,2))
max_sat_ref = np.array([0.82791151, 0.61137274]).reshape(2,1)
# Convert RGB to OD.
# Note: The original paper used log10, and the reference implementation used the natural log.
#OD = -np.log((x+1)/light_intensity) # shape (H*W, C)
OD = -np.log10(x/light_intensity + 1e-8)
# Remove data with OD intensity less than beta.
# I.e. remove transparent pixels.
# Note: This needs to be checked per channel, rather than
# taking an average over all channels for a given pixel.
OD_thresh = OD[np.all(OD >= beta, 1), :] # shape (K, C)
# Calculate eigenvectors.
# Note: We can either use eigenvector decomposition, or SVD.
#eigvals, eigvecs = np.linalg.eig(np.cov(OD_thresh.T)) # np.cov results in inf/nans
U, s, V = np.linalg.svd(OD_thresh, full_matrices=False)
# Extract two largest eigenvectors.
# Note: We swap the sign of the eigvecs here to be consistent
# with other implementations. Both +/- eigvecs are valid, with
# the same eigenvalue, so this is okay.
#top_eigvecs = eigvecs[:, np.argsort(eigvals)[-2:]] * -1
top_eigvecs = V[0:2, :].T * -1 # shape (C, 2)
# Project thresholded optical density values onto plane spanned by
# 2 largest eigenvectors.
proj = np.dot(OD_thresh, top_eigvecs) # shape (K, 2)
# Calculate angle of each point wrt the first plane direction.
# Note: the parameters are `np.arctan2(y, x)`
angles = np.arctan2(proj[:, 1], proj[:, 0]) # shape (K,)
# Find robust extremes (a and 100-a percentiles) of the angle.
min_angle = np.percentile(angles, alpha)
max_angle = np.percentile(angles, 100-alpha)
# Convert min/max vectors (extremes) back to optimal stains in OD space.
# This computes a set of axes for each angle onto which we can project
# the top eigenvectors. This assumes that the projected values have
# been normalized to unit length.
extreme_angles = np.array(
[[np.cos(min_angle), np.cos(max_angle)],
[np.sin(min_angle), np.sin(max_angle)]]
) # shape (2,2)
stains = np.dot(top_eigvecs, extreme_angles) # shape (C, 2)
# Merge vectors with hematoxylin first, and eosin second, as a heuristic.
if stains[0, 0] < stains[0, 1]:
stains[:, [0, 1]] = stains[:, [1, 0]] # swap columns
# Calculate saturations of each stain.
# Note: Here, we solve
# OD = VS
# S = V^{-1}OD
# where `OD` is the matrix of optical density values of our image,
# `V` is the matrix of stain vectors, and `S` is the matrix of stain
# saturations. Since this is an overdetermined system, we use the
# least squares solver, rather than a direct solve.
sats, _, _, _ = np.linalg.lstsq(stains, OD.T)
# Normalize stain saturations to have same pseudo-maximum based on
# a reference max saturation.
max_sat = np.percentile(sats, 99, axis=1, keepdims=True)
sats = sats / max_sat * max_sat_ref
# Compute optimal OD values.
OD_norm = np.dot(stain_ref, sats)
# Recreate image.
# Note: If the image is immediately converted to uint8 with `.astype(np.uint8)`, it will
# not return the correct values due to the initital values being outside of [0,255].
# To fix this, we round to the nearest integer, and then clip to [0,255], which is the
# same behavior as Matlab.
#x_norm = np.exp(OD_norm) * light_intensity # natural log approach
x_norm = 10**(-OD_norm) * light_intensity - 1e-8 # log10 approach
x_norm = np.clip(np.round(x_norm), 0, 255).astype(np.uint8)
x_norm = x_norm.astype(np.uint8)
x_norm = x_norm.T.reshape(h,w,c)
return (slide_num, x_norm)
def flatten_sample(sample_tuple):
"""
Flatten a (H,W,C) sample into a (C*H*W) row vector.
Transpose each sample from (H, W, channels) to (channels, H, W), then
flatten each into a vector of length channels*H*W.
Args:
sample_tuple: A (slide_num, sample) tuple, where slide_num is an
integer, and sample is a 3D NumPy array of shape (H,W,C).
Returns:
A (slide_num, sample) tuple, where the sample has been transposed
from (H,W,C) to (C,H,W), and flattened to a vector of length
(C*H*W).
"""
slide_num, sample = sample_tuple
# 1. Swap axes from (sample_size_x, sample_size_y, ch) to
# (ch, sample_size_x, sample_size_y).
# 2. Flatten sample into (ch*sample_size_x*sample_size_y).
flattened_sample = sample.transpose(2,0,1).reshape(-1)
return (slide_num, flattened_sample)
# Get Ground Truth Labels
def get_labels_df(folder):
"""
Create a DataFrame with the ground truth labels for each slide.
Args:
folder: Directory containing a `training_ground_truth.csv` file
containing the ground truth "tumor_score" and "molecular_score"
labels for each slide.
Returns:
A Pandas DataFrame containing the ground truth labels for each
slide.
"""
filepath = os.path.join(folder, "training_ground_truth.csv")
labels_df = pd.read_csv(filepath, names=["tumor_score", "molecular_score"], header=None)
labels_df["slide_num"] = labels_df.index + 1 # slide numbering starts at 1
labels_df.set_index("slide_num", drop=False, inplace=True) # use the slide num as index
return labels_df
# Process All Slides Into A Spark DataFrame
def preprocess(spark, slide_nums, folder="data", training=True, tile_size=1024, overlap=0,
tissue_threshold=0.9, sample_size=256, grayscale=False, normalize_stains=True,
num_partitions=20000):
"""
Preprocess a set of whole-slide images.
Preprocess a set of whole-slide images as follows:
1. Tile the slides into tiles of size (tile_size, tile_size, 3).
2. Filter the tiles to remove unnecessary tissue.
3. Cut the remaining tiles into samples of size
(sample_size, sample_size, ch), where `ch` is 1 if `grayscale`
is true, or 3 otherwise.
Args:
spark: SparkSession.
slide_nums: List of whole-slide numbers to process.
folder: Local directory in which the slides folder and ground truth
file is stored, as a string. This should contain a
`training_image_data` folder with images in the format
`TUPAC-TR-###.svs`, as well as a `training_ground_truth.csv` file
containing the ground truth "tumor_score" and "molecular_score"
labels for each slide. Alternatively, the folder should contain a
`testing_image_data` folder with images in the format
`TUPAC-TE-###.svs`.
training: Boolean for training or testing datasets.
tile_size: The width and height of a square tile to be generated.
overlap: Number of pixels by which to overlap the tiles.
tissue_threshold: Tissue percentage threshold for filtering.
sample_size: The new width and height of the square samples to be
generated.
grayscale: Whether or not to generate grayscale samples, rather
than RGB.
normalize_stains: Whether or not to apply stain normalization.
num_partitions: Number of partitions to use during processing.
Returns:
A Spark DataFrame in which each row contains the slide number, tumor
score, molecular score, and the sample stretched out into a Vector.
"""
slides = spark.sparkContext.parallelize(slide_nums)
# Create DataFrame of all tile locations and increase number of partitions
# to avoid OOM during subsequent processing.
tile_indices = (slides.flatMap(
lambda slide: process_slide(slide, folder, training, tile_size, overlap)))
# TODO: Explore computing the ideal paritition sizes based on projected number
# of tiles after filtering. I.e. something like the following:
#rows = tile_indices.count()
#part_size = 128
#channels = 1 if grayscale else 3
#row_mb = tile_size * tile_size * channels * 8 / 1024 / 1024 # size of one row in MB
#rows_per_part = round(part_size / row_mb)
#num_parts = rows / rows_per_part
tile_indices = tile_indices.repartition(num_partitions)
tile_indices.cache()
# Extract all tiles into a DataFrame, filter, cut into smaller samples, apply stain
# normalization, and flatten.
tiles = tile_indices.map(lambda tile_index: process_tile_index(tile_index, folder, training))
filtered_tiles = tiles.filter(lambda tile: keep_tile(tile, tile_size, tissue_threshold))
samples = filtered_tiles.flatMap(lambda tile: process_tile(tile, sample_size, grayscale))
if normalize_stains:
samples = samples.map(lambda sample: normalize_staining(sample))
samples = samples.map(lambda sample: flatten_sample(sample))
if training:
# Append labels
labels_df = get_labels_df(folder)
samples_with_labels = (samples.map(
lambda tup: (tup[0], int(labels_df.at[tup[0],"tumor_score"]),
float(labels_df.at[tup[0],"molecular_score"]), Vectors.dense(tup[1]))))
df = samples_with_labels.toDF(["slide_num", "tumor_score", "molecular_score", "sample"])
df = df.select(df.slide_num.astype("int"), df.tumor_score.astype("int"),
df.molecular_score, df["sample"])
else: # testing data -- no labels
df = samples.toDF(["slide_num", "sample"])
df = df.select(df.slide_num.astype("int"), df["sample"])
return df
# Split Into Separate Train & Validation DataFrames Based On Slide Number
def train_val_split(spark, df, slide_nums, folder, train_frac=0.8, add_row_indices=True, seed=None,
debug=False):
"""
Split a DataFrame of slide samples into training and validation sets.
Args:
spark: SparkSession.
df: A Spark DataFrame in which each row contains the slide number,
tumor score, molecular score, and the sample stretched out into
a Vector.
slide_nums: A list of slide numbers to sample from.
folder: Directory containing a `training_ground_truth.csv` file
containing the ground truth "tumor_score" and "molecular_score"
labels for each slide.
train_frac: Fraction of the data to assign to the training set, with
`1-frac` assigned to the valiation set.
add_row_indices: Boolean for whether or not to prepend an index
column contain the row index for use downstream by SystemML.
The column name will be "__INDEX".
Returns:
A Spark DataFrame in which each row contains the slide number, tumor
score, molecular score, and the sample stretched out into a Vector.
"""
# Create DataFrame of labels for the given slide numbers.
labels_df = get_labels_df(folder)
labels_df = labels_df.loc[slide_nums]
# Randomly split slides 80%/20% into train and validation sets.
train_nums_df = labels_df.sample(frac=train_frac, random_state=seed)
val_nums_df = labels_df.drop(train_nums_df.index)
train_nums = (spark.createDataFrame(train_nums_df)
.selectExpr("cast(slide_num as int)")
.coalesce(1))
val_nums = (spark.createDataFrame(val_nums_df)
.selectExpr("cast(slide_num as int)")
.coalesce(1))
# Note: Explicitly mark the smaller DataFrames as able to be broadcasted
# in order to have Catalyst choose the more efficient BroadcastHashJoin,
# rather than the costly SortMergeJoin.
train = df.join(F.broadcast(train_nums), on="slide_num")
val = df.join(F.broadcast(val_nums), on="slide_num")
if debug:
# DEBUG: Sanity checks.
assert len(pd.merge(train_nums_df, val_nums_df, on="slide_num")) == 0
assert train_nums.join(val_nums, on="slide_num").count() == 0
assert train.join(val, on="slide_num").count() == 0
# - Check distributions.
for pdf in train_nums_df, val_nums_df:
print(pdf.count())
print(pdf["tumor_score"].value_counts(sort=False))
print(pdf["tumor_score"].value_counts(normalize=True, sort=False), "\n")
# - Check total number of examples in each.
print(train.count(), val.count())
# - Check physical plans for broadcast join.
print(train.explain(), val.explain())
# Add row indices for use with SystemML.
if add_row_indices:
train = (train.rdd
.zipWithIndex()
.map(lambda r: (r[1] + 1, *r[0])) # flatten & convert index to 1-based indexing
.toDF(['__INDEX', 'slide_num', 'tumor_score', 'molecular_score', 'sample']))
train = train.select(train["__INDEX"].astype("int"), train.slide_num.astype("int"),
train.tumor_score.astype("int"), train.molecular_score, train["sample"])
val = (val.rdd
.zipWithIndex()
.map(lambda r: (r[1] + 1, *r[0])) # flatten & convert index to 1-based indexing
.toDF(['__INDEX', 'slide_num', 'tumor_score', 'molecular_score', 'sample']))
val = val.select(val["__INDEX"].astype("int"), val.slide_num.astype("int"),
val.tumor_score.astype("int"), val.molecular_score, val["sample"])
return train, val
# Save DataFrame
def save(df, filepath, sample_size, grayscale, mode="error", format="parquet", file_size=128):
"""
Save a preprocessed DataFrame with a constraint on the file sizes.
Args:
df: A Spark DataFrame.
filepath: Hadoop-supported path at which to save `df`.
sample_size: The width and height of the square samples.
grayscale: Whether or not to the samples are in grayscale format,
rather than RGB.
mode: Specifies the behavior of `df.write.mode` when the data
already exists. Options include:
* `append`: Append contents of this DataFrame to
existing data.
* `overwrite`: Overwrite existing data.
* `error`: Throw an exception if data already exists.
* `ignore`: Silently ignore this operation if data already
exists.
format: The format in which to save the DataFrame.
file_size: Size in MB of each saved file. 128 MB is an
empirically ideal size.
"""
channels = 1 if grayscale else 3
row_mb = sample_size * sample_size * channels * 8 / 1024 / 1024 # size of one row in MB
rows_per_file = round(file_size / row_mb)
df.write.option("maxRecordsPerFile", rows_per_file).mode(mode).save(filepath, format=format)
| apache-2.0 |
hcsturix74/django | django/middleware/clickjacking.py | 87 | 1988 | """
Clickjacking Protection Middleware.
This module provides a middleware that implements protection against a
malicious site loading resources from your site in a hidden frame.
"""
from django.conf import settings
class XFrameOptionsMiddleware(object):
"""
Middleware that sets the X-Frame-Options HTTP header in HTTP responses.
Does not set the header if it's already set or if the response contains
a xframe_options_exempt value set to True.
By default, sets the X-Frame-Options header to 'SAMEORIGIN', meaning the
response can only be loaded on a frame within the same site. To prevent the
response from being loaded in a frame in any site, set X_FRAME_OPTIONS in
your project's Django settings to 'DENY'.
Note: older browsers will quietly ignore this header, thus other
clickjacking protection techniques should be used if protection in those
browsers is required.
http://en.wikipedia.org/wiki/Clickjacking#Server_and_client
"""
def process_response(self, request, response):
# Don't set it if it's already in the response
if response.get('X-Frame-Options') is not None:
return response
# Don't set it if they used @xframe_options_exempt
if getattr(response, 'xframe_options_exempt', False):
return response
response['X-Frame-Options'] = self.get_xframe_options_value(request,
response)
return response
def get_xframe_options_value(self, request, response):
"""
Gets the value to set for the X_FRAME_OPTIONS header.
By default this uses the value from the X_FRAME_OPTIONS Django
settings. If not found in settings, defaults to 'SAMEORIGIN'.
This method can be overridden if needed, allowing it to vary based on
the request or response.
"""
return getattr(settings, 'X_FRAME_OPTIONS', 'SAMEORIGIN').upper()
| bsd-3-clause |
giantoak/docent-learner | src/admin/admin.py | 1 | 2189 | import cgi
import re
import json
configfile = "/var/www/html/docent-learner/var/config/config.json"
def application(environ, start_response):
status = '200 OK'
response_headers = [('Content-type', 'text/html; charset=utf-8')]
message = ""
config = {}
try:
config_file = open(configfile, 'r')
config_records = json.load(config_file)
config_file.close()
config = config_records
message += str(config) + "<br>"
except Exception, error:
message += "Config file error: " + str(error) + "<br>"
form_data = cgi.FieldStorage(environ=environ, fp=environ['wsgi.input'])
for key in form_data:
value = form_data.getvalue(key)
config[key] = value
if(len(form_data) > 1):
try:
config_file = open(configfile, 'w')
#config_file.write(unicode(json.dumps(config,ensure_ascii=False)))
json.dump(config, config_file)
config_file.close()
message += "Writing config file.<br>"
except:
message += "Unable to write config file.<br>"
imagequestions = ""
try:
imagequestions = str(config['imagequestions'])
except:
message += "Configuration was incomplete.<br>"
message += str(config)
html = "<html><h2>Docent Learner Administration</h2>"
form = "<form action=\"/docent-learner/dl/admin/admin.py\" method=\"post\">"
form += "<input type=\"hidden\" name=\"test\" value=\"bleh\">"
form += """
<br><br>
Configure the <a href='/docent-learner/dl/images.py'>image tagger</a><br>
<br>
Image Questions<br>
<textarea rows='20' cols='100' name='imagequestions'>%s</textarea>
""" % (imagequestions)
form += """
<br><br>
Image Mode: <br>
<input type="radio" name="imagemode" value="single" checked> Capture only one observation per image <br>
<input type="radio" name="imagemode" value="multiple"> Capture multiple observations silently <br>
<input type="radio" name="imagemode" value="gamify"> Capture multiple observations and gamify <br>
"""
form += "<br><br><input type=\"submit\" value=\"Save\"><br>"
form += "</form>"
html += form
html += "<br><br>"
html += "</html>"
start_response(status, response_headers)
return [html]
| apache-2.0 |
emijrp/pywikibot-core | tests/bot_tests.py | 6 | 13347 | # -*- coding: utf-8 -*-
"""Bot tests."""
#
# (C) Pywikibot team, 2015
#
# Distributed under the terms of the MIT license.
#
from __future__ import unicode_literals
__version__ = '$Id$'
#
import sys
import pywikibot
import pywikibot.bot
from tests.aspects import (
unittest, DefaultSiteTestCase, SiteAttributeTestCase, TestCase,
)
class FakeSaveBotTestCase(TestCase):
"""
An abstract test case which patches the bot class to not actually write.
It redirects the bot's _save_page to it's own C{bot_save} method. Currently
userPut, put_current and user_edit_entity call it. By default it'll call
the original method but replace the function called to actually save the
page by C{page_save}. It patches the bot class as soon as this class'
attribute bot is defined. It also sets the bot's 'always' option to True to
avoid user interaction.
The C{bot_save} method compares the save counter before the call and asserts
that it has increased by one after the call. It also stores locally in
C{save_called} if C{page_save} has been called. If C{bot_save} or
C{page_save} are implemented they should call super's method at some point
to make sure these assertions work. At C{tearDown} it checks that the pages
are saved often enough. The attribute C{default_assert_saves} defines the
number of saves which must happen and compares it to the difference using
the save counter. It is possible to define C{assert_saves} after C{setUp} to
overwrite the default value for certain tests. By default the number of
saves it asserts are 1. Additionally C{save_called} increases by 1 on each
call of C{page_save} and should be equal to C{assert_saves}.
This means if the bot class actually does other writes, like using
L{pywikibot.page.Page.save} manually, it'll still write.
"""
@property
def bot(self):
"""Get the current bot."""
return self._bot
@bot.setter
def bot(self, value):
"""Set and patch the current bot."""
assert value._save_page != self.bot_save, 'bot may not be patched.'
self._bot = value
self._bot.options['always'] = True
self._original = self._bot._save_page
self._bot._save_page = self.bot_save
self._old_counter = self._bot._save_counter
def setUp(self):
"""Set up test by reseting the counters."""
super(FakeSaveBotTestCase, self).setUp()
self.assert_saves = getattr(self, 'default_assert_saves', 1)
self.save_called = 0
def tearDown(self):
"""Tear down by asserting the counters."""
self.assertEqual(self._bot._save_counter,
self._old_counter + self.assert_saves)
self.assertEqual(self.save_called, self.assert_saves)
super(FakeSaveBotTestCase, self).tearDown()
def bot_save(self, page, func, *args, **kwargs):
"""Handle when bot's userPut was called."""
self.assertGreaterEqual(self._bot._save_counter, 0)
old_counter = self._bot._save_counter
old_local_cnt = self.save_called
result = self._original(page, self.page_save, *args, **kwargs)
self.assertEqual(self._bot._save_counter, old_counter + 1)
self.assertEqual(self.save_called, old_local_cnt + 1)
self.assertGreater(self._bot._save_counter, self._old_counter)
return result
def page_save(self, *args, **kwargs):
"""Handle when bot calls the page's save method."""
self.save_called += 1
class TestBotTreatExit(object):
"""Mixin to provide handling for treat and exit."""
def _treat(self, pages, post_treat=None):
"""
Get tests which are executed on each treat.
It uses pages as an iterator and compares the page given to the page
returned by pages iterator. It checks that the bot's _site and site
attributes are set to the page's site. If _treat_site is set with a Site
it compares it to that one too.
Afterwards it calls post_treat so it's possible to do additional checks.
"""
def treat(page):
self.assertEqual(page, next(self._page_iter))
if self._treat_site is None:
self.assertFalse(hasattr(self.bot, 'site'))
self.assertFalse(hasattr(self.bot, '_site'))
else:
self.assertIsNotNone(self.bot._site)
self.assertEqual(self.bot.site, self.bot._site)
if self._treat_site:
self.assertEqual(self.bot._site, self._treat_site)
self.assertEqual(page.site, self.bot.site)
if post_treat:
post_treat(page)
self._page_iter = iter(pages)
return treat
def _treat_page(self, pages=True, post_treat=None):
"""
Adjust to CurrentPageBot signature.
It uses almost the same logic as _treat but returns a wrapper function
which itself calls the function returned by _treat.
The pages may be set to True which sill use _treat_generator as the
source for the pages.
"""
def treat_page():
treat(self.bot.current_page)
if pages is True:
pages = self._treat_generator()
treat = self._treat(pages, post_treat)
return treat_page
def _exit(self, treated, written=0, exception=None):
"""Get tests which are executed on exit."""
def exit():
exc = sys.exc_info()[0]
if exc is AssertionError:
# When an AssertionError happened we shouldn't do these
# assertions as they are invalid anyway and hide the actual
# failed assertion
return
self.assertEqual(self.bot._treat_counter, treated)
self.assertEqual(self.bot._save_counter, written)
if exception:
self.assertIs(exc, exception)
else:
self.assertIsNone(exc)
self.assertRaises(StopIteration, next, self._page_iter)
return exit
class TestDrySiteBot(TestBotTreatExit, SiteAttributeTestCase):
"""Tests for the BaseBot subclasses."""
dry = True
sites = {
'de': {
'family': 'wikipedia',
'code': 'de'
},
'en': {
'family': 'wikipedia',
'code': 'en'
}
}
def _generator(self):
"""Generic generator."""
yield pywikibot.Page(self.de, 'Page 1')
yield pywikibot.Page(self.en, 'Page 2')
yield pywikibot.Page(self.de, 'Page 3')
yield pywikibot.Page(self.en, 'Page 4')
def test_SingleSiteBot_automatic(self):
"""Test SingleSiteBot class with no predefined site."""
self._treat_site = self.de
self.bot = pywikibot.bot.SingleSiteBot(site=None,
generator=self._generator())
self.bot.treat = self._treat([pywikibot.Page(self.de, 'Page 1'),
pywikibot.Page(self.de, 'Page 3')])
self.bot.exit = self._exit(2)
self.bot.run()
self.assertEqual(self.bot.site, self._treat_site)
def test_SingleSiteBot_specific(self):
"""Test SingleSiteBot class with predefined site."""
self._treat_site = self.en
self.bot = pywikibot.bot.SingleSiteBot(site=self.en,
generator=self._generator())
self.bot.treat = self._treat([pywikibot.Page(self.en, 'Page 2'),
pywikibot.Page(self.en, 'Page 4')])
self.bot.exit = self._exit(2)
self.bot.run()
self.assertEqual(self.bot.site, self._treat_site)
def test_MultipleSitesBot(self):
"""Test MultipleSitesBot class."""
# Assert no specific site
self._treat_site = False
self.bot = pywikibot.bot.MultipleSitesBot(generator=self._generator())
with self.assertRaises(AttributeError):
self.bot.site = self.de
with self.assertRaises(ValueError):
self.bot.site
if sys.version_info[0] == 2:
# The exc_info still contains the AttributeError :/
sys.exc_clear()
self.bot.treat = self._treat(self._generator())
self.bot.exit = self._exit(4)
self.bot.run()
with self.assertRaises(ValueError):
self.bot.site
if sys.version_info[0] == 2:
# The exc_info still contains the AttributeError :/
sys.exc_clear()
def test_Bot(self):
"""Test normal Bot class."""
# Assert no specific site
self._treat_site = False
self.bot = pywikibot.bot.Bot(generator=self._generator())
self.bot.treat = self._treat(self._generator())
self.bot.exit = self._exit(4)
self.bot.run()
def test_CurrentPageBot(self):
"""Test normal Bot class."""
def post_treat(page):
self.assertIs(self.bot.current_page, page)
# Assert no specific site
self._treat_site = None
self.bot = pywikibot.bot.CurrentPageBot(generator=self._generator())
self.bot.treat_page = self._treat_page(self._generator(), post_treat)
self.bot.exit = self._exit(4)
self.bot.run()
def test_Bot_ValueError(self):
"""Test normal Bot class with a ValueError in treat."""
def post_treat(page):
if page.title() == 'Page 3':
raise ValueError('Whatever')
self._treat_site = False
self.bot = pywikibot.bot.Bot(generator=self._generator())
self.bot.treat = self._treat([pywikibot.Page(self.de, 'Page 1'),
pywikibot.Page(self.en, 'Page 2'),
pywikibot.Page(self.de, 'Page 3')],
post_treat)
self.bot.exit = self._exit(2, exception=ValueError)
self.assertRaises(ValueError, self.bot.run)
def test_Bot_KeyboardInterrupt(self):
"""Test normal Bot class with a KeyboardInterrupt in treat."""
def post_treat(page):
if page.title() == 'Page 3':
raise KeyboardInterrupt('Whatever')
self._treat_site = False
self.bot = pywikibot.bot.Bot(generator=self._generator())
self.bot.treat = self._treat([pywikibot.Page(self.de, 'Page 1'),
pywikibot.Page(self.en, 'Page 2'),
pywikibot.Page(self.de, 'Page 3')],
post_treat)
# TODO: sys.exc_info is empty in Python 3
if sys.version_info[0] > 2:
exc = None
else:
exc = KeyboardInterrupt
self.bot.exit = self._exit(2, exception=exc)
self.bot.run()
# TODO: This could be written as dry tests probably by faking the important
# properties
class LiveBotTestCase(TestBotTreatExit, DefaultSiteTestCase):
"""Test bot classes which need to check the Page object live."""
def _treat_generator(self):
"""Yield the current page until it's None."""
while self._current_page:
yield self._current_page
def _missing_generator(self):
"""Yield pages and the last one does not exist."""
self._count = 1
self._current_page = list(self.site.allpages(total=1))[0]
yield self._current_page
while self._current_page.exists():
self._count += 1
self._current_page = pywikibot.Page(
self.site, self._current_page.title() + 'X')
yield self._current_page
self._current_page = None
def _exit(self, treated=None, written=0, exception=None):
"""Set the number of treated pages to _count."""
def exit():
t = self._count if treated is None else treated
super(LiveBotTestCase, self)._exit(t, written, exception)()
return exit
def test_ExistingPageBot(self):
"""Test ExistingPageBot class."""
def post_treat(page):
"""Verify the page exists."""
self.assertTrue(page.exists())
self._treat_site = None
self.bot = pywikibot.bot.ExistingPageBot(
generator=self._missing_generator())
self.bot.treat_page = self._treat_page(post_treat=post_treat)
self.bot.exit = self._exit()
self.bot.run()
def test_CreatingPageBot(self):
"""Test CreatingPageBot class."""
# This doesn't verify much (e.g. it could yield the first existing page)
# but the assertion in post_treat should verify that the page is valid
def treat_generator():
"""Yield just one current page (the last one)."""
yield self._current_page
def post_treat(page):
"""Verify the page is missing."""
self.assertFalse(page.exists())
self._treat_site = None
self.bot = pywikibot.bot.CreatingPageBot(
generator=self._missing_generator())
self.bot.treat_page = self._treat_page(treat_generator(), post_treat)
self.bot.exit = self._exit()
self.bot.run()
if __name__ == '__main__':
try:
unittest.main()
except SystemExit:
pass
| mit |
nanolearningllc/edx-platform-cypress | common/test/acceptance/pages/lms/discussion.py | 36 | 25473 | from contextlib import contextmanager
from bok_choy.javascript import wait_for_js
from bok_choy.page_object import PageObject
from bok_choy.promise import EmptyPromise, Promise
from .course_page import CoursePage
class DiscussionPageMixin(object):
def is_ajax_finished(self):
return self.browser.execute_script("return jQuery.active") == 0
class DiscussionThreadPage(PageObject, DiscussionPageMixin):
url = None
def __init__(self, browser, thread_selector):
super(DiscussionThreadPage, self).__init__(browser)
self.thread_selector = thread_selector
def _find_within(self, selector):
"""
Returns a query corresponding to the given CSS selector within the scope
of this thread page
"""
return self.q(css=self.thread_selector + " " + selector)
def is_browser_on_page(self):
return self.q(css=self.thread_selector).present
def _get_element_text(self, selector):
"""
Returns the text of the first element matching the given selector, or
None if no such element exists
"""
text_list = self._find_within(selector).text
return text_list[0] if text_list else None
def _is_element_visible(self, selector):
query = self._find_within(selector)
return query.present and query.visible
@contextmanager
def _secondary_action_menu_open(self, ancestor_selector):
"""
Given the selector for an ancestor of a secondary menu, return a context
manager that will open and close the menu
"""
self._find_within(ancestor_selector + " .action-more").click()
EmptyPromise(
lambda: self._is_element_visible(ancestor_selector + " .actions-dropdown"),
"Secondary action menu opened"
).fulfill()
yield
if self._is_element_visible(ancestor_selector + " .actions-dropdown"):
self._find_within(ancestor_selector + " .action-more").click()
EmptyPromise(
lambda: not self._is_element_visible(ancestor_selector + " .actions-dropdown"),
"Secondary action menu closed"
).fulfill()
def get_group_visibility_label(self):
"""
Returns the group visibility label shown for the thread.
"""
return self._get_element_text(".group-visibility-label")
def get_response_total_text(self):
"""Returns the response count text, or None if not present"""
return self._get_element_text(".response-count")
def get_num_displayed_responses(self):
"""Returns the number of responses actually rendered"""
return len(self._find_within(".discussion-response"))
def get_shown_responses_text(self):
"""Returns the shown response count text, or None if not present"""
return self._get_element_text(".response-display-count")
def get_load_responses_button_text(self):
"""Returns the load more responses button text, or None if not present"""
return self._get_element_text(".load-response-button")
def load_more_responses(self):
"""Clicks the load more responses button and waits for responses to load"""
self._find_within(".load-response-button").click()
EmptyPromise(
self.is_ajax_finished,
"Loading more Responses"
).fulfill()
def has_add_response_button(self):
"""Returns true if the add response button is visible, false otherwise"""
return self._is_element_visible(".add-response-btn")
def click_add_response_button(self):
"""
Clicks the add response button and ensures that the response text
field receives focus
"""
self._find_within(".add-response-btn").first.click()
EmptyPromise(
lambda: self._find_within(".discussion-reply-new textarea:focus").present,
"Response field received focus"
).fulfill()
@wait_for_js
def is_response_editor_visible(self, response_id):
"""Returns true if the response editor is present, false otherwise"""
return self._is_element_visible(".response_{} .edit-post-body".format(response_id))
@wait_for_js
def is_discussion_body_visible(self):
return self._is_element_visible(".post-body")
def is_mathjax_preview_available(self):
return self.q(css=".MathJax_Preview").text[0] == ""
def is_mathjax_rendered(self):
return self._is_element_visible(".MathJax")
def is_response_visible(self, comment_id):
"""Returns true if the response is viewable onscreen"""
return self._is_element_visible(".response_{} .response-body".format(comment_id))
def is_response_editable(self, response_id):
"""Returns true if the edit response button is present, false otherwise"""
with self._secondary_action_menu_open(".response_{} .discussion-response".format(response_id)):
return self._is_element_visible(".response_{} .discussion-response .action-edit".format(response_id))
def get_response_body(self, response_id):
return self._get_element_text(".response_{} .response-body".format(response_id))
def start_response_edit(self, response_id):
"""Click the edit button for the response, loading the editing view"""
with self._secondary_action_menu_open(".response_{} .discussion-response".format(response_id)):
self._find_within(".response_{} .discussion-response .action-edit".format(response_id)).first.click()
EmptyPromise(
lambda: self.is_response_editor_visible(response_id),
"Response edit started"
).fulfill()
def get_link_href(self):
"""Extracts href attribute of the referenced link"""
link_href = self._find_within(".post-body p a").attrs('href')
return link_href[0] if link_href else None
def get_response_vote_count(self, response_id):
return self._get_element_text(".response_{} .discussion-response .action-vote .vote-count".format(response_id))
def vote_response(self, response_id):
current_count = self._get_element_text(".response_{} .discussion-response .action-vote .vote-count".format(response_id))
self._find_within(".response_{} .discussion-response .action-vote".format(response_id)).first.click()
self.wait_for_ajax()
EmptyPromise(
lambda: current_count != self.get_response_vote_count(response_id),
"Response is voted"
).fulfill()
def is_response_reported(self, response_id):
return self._is_element_visible(".response_{} .discussion-response .post-label-reported".format(response_id))
def report_response(self, response_id):
with self._secondary_action_menu_open(".response_{} .discussion-response".format(response_id)):
self._find_within(".response_{} .discussion-response .action-report".format(response_id)).first.click()
self.wait_for_ajax()
EmptyPromise(
lambda: self.is_response_reported(response_id),
"Response is reported"
).fulfill()
def is_response_endorsed(self, response_id):
return "endorsed" in self._get_element_text(".response_{} .discussion-response .posted-details".format(response_id))
def endorse_response(self, response_id):
self._find_within(".response_{} .discussion-response .action-endorse".format(response_id)).first.click()
self.wait_for_ajax()
EmptyPromise(
lambda: self.is_response_endorsed(response_id),
"Response edit started"
).fulfill()
def set_response_editor_value(self, response_id, new_body):
"""Replace the contents of the response editor"""
self._find_within(".response_{} .discussion-response .wmd-input".format(response_id)).fill(new_body)
def submit_response_edit(self, response_id, new_response_body):
"""Click the submit button on the response editor"""
self._find_within(".response_{} .discussion-response .post-update".format(response_id)).first.click()
EmptyPromise(
lambda: (
not self.is_response_editor_visible(response_id) and
self.is_response_visible(response_id) and
self.get_response_body(response_id) == new_response_body
),
"Comment edit succeeded"
).fulfill()
def is_show_comments_visible(self, response_id):
"""Returns true if the "show comments" link is visible for a response"""
return self._is_element_visible(".response_{} .action-show-comments".format(response_id))
def show_comments(self, response_id):
"""Click the "show comments" link for a response"""
self._find_within(".response_{} .action-show-comments".format(response_id)).first.click()
EmptyPromise(
lambda: self._is_element_visible(".response_{} .comments".format(response_id)),
"Comments shown"
).fulfill()
def is_add_comment_visible(self, response_id):
"""Returns true if the "add comment" form is visible for a response"""
return self._is_element_visible("#wmd-input-comment-body-{}".format(response_id))
def is_comment_visible(self, comment_id):
"""Returns true if the comment is viewable onscreen"""
return self._is_element_visible("#comment_{} .response-body".format(comment_id))
def get_comment_body(self, comment_id):
return self._get_element_text("#comment_{} .response-body".format(comment_id))
def is_comment_deletable(self, comment_id):
"""Returns true if the delete comment button is present, false otherwise"""
with self._secondary_action_menu_open("#comment_{}".format(comment_id)):
return self._is_element_visible("#comment_{} .action-delete".format(comment_id))
def delete_comment(self, comment_id):
with self.handle_alert():
with self._secondary_action_menu_open("#comment_{}".format(comment_id)):
self._find_within("#comment_{} .action-delete".format(comment_id)).first.click()
EmptyPromise(
lambda: not self.is_comment_visible(comment_id),
"Deleted comment was removed"
).fulfill()
def is_comment_editable(self, comment_id):
"""Returns true if the edit comment button is present, false otherwise"""
with self._secondary_action_menu_open("#comment_{}".format(comment_id)):
return self._is_element_visible("#comment_{} .action-edit".format(comment_id))
def is_comment_editor_visible(self, comment_id):
"""Returns true if the comment editor is present, false otherwise"""
return self._is_element_visible(".edit-comment-body[data-id='{}']".format(comment_id))
def _get_comment_editor_value(self, comment_id):
return self._find_within("#wmd-input-edit-comment-body-{}".format(comment_id)).text[0]
def start_comment_edit(self, comment_id):
"""Click the edit button for the comment, loading the editing view"""
old_body = self.get_comment_body(comment_id)
with self._secondary_action_menu_open("#comment_{}".format(comment_id)):
self._find_within("#comment_{} .action-edit".format(comment_id)).first.click()
EmptyPromise(
lambda: (
self.is_comment_editor_visible(comment_id) and
not self.is_comment_visible(comment_id) and
self._get_comment_editor_value(comment_id) == old_body
),
"Comment edit started"
).fulfill()
def set_comment_editor_value(self, comment_id, new_body):
"""Replace the contents of the comment editor"""
self._find_within("#comment_{} .wmd-input".format(comment_id)).fill(new_body)
def submit_comment_edit(self, comment_id, new_comment_body):
"""Click the submit button on the comment editor"""
self._find_within("#comment_{} .post-update".format(comment_id)).first.click()
EmptyPromise(
lambda: (
not self.is_comment_editor_visible(comment_id) and
self.is_comment_visible(comment_id) and
self.get_comment_body(comment_id) == new_comment_body
),
"Comment edit succeeded"
).fulfill()
def cancel_comment_edit(self, comment_id, original_body):
"""Click the cancel button on the comment editor"""
self._find_within("#comment_{} .post-cancel".format(comment_id)).first.click()
EmptyPromise(
lambda: (
not self.is_comment_editor_visible(comment_id) and
self.is_comment_visible(comment_id) and
self.get_comment_body(comment_id) == original_body
),
"Comment edit was canceled"
).fulfill()
class DiscussionSortPreferencePage(CoursePage):
"""
Page that contain the discussion board with sorting options
"""
def __init__(self, browser, course_id):
super(DiscussionSortPreferencePage, self).__init__(browser, course_id)
self.url_path = "discussion/forum"
def is_browser_on_page(self):
"""
Return true if the browser is on the right page else false.
"""
return self.q(css="body.discussion .forum-nav-sort-control").present
def get_selected_sort_preference(self):
"""
Return the text of option that is selected for sorting.
"""
options = self.q(css="body.discussion .forum-nav-sort-control option")
return options.filter(lambda el: el.is_selected())[0].get_attribute("value")
def change_sort_preference(self, sort_by):
"""
Change the option of sorting by clicking on new option.
"""
self.q(css="body.discussion .forum-nav-sort-control option[value='{0}']".format(sort_by)).click()
def refresh_page(self):
"""
Reload the page.
"""
self.browser.refresh()
class DiscussionTabSingleThreadPage(CoursePage):
def __init__(self, browser, course_id, discussion_id, thread_id):
super(DiscussionTabSingleThreadPage, self).__init__(browser, course_id)
self.thread_page = DiscussionThreadPage(
browser,
"body.discussion .discussion-article[data-id='{thread_id}']".format(thread_id=thread_id)
)
self.url_path = "discussion/forum/{discussion_id}/threads/{thread_id}".format(
discussion_id=discussion_id, thread_id=thread_id
)
def is_browser_on_page(self):
return self.thread_page.is_browser_on_page()
def __getattr__(self, name):
return getattr(self.thread_page, name)
def close_open_thread(self):
with self.thread_page._secondary_action_menu_open(".forum-thread-main-wrapper"):
self._find_within(".forum-thread-main-wrapper .action-close").first.click()
@wait_for_js
def is_window_on_top(self):
"""
Check if window's scroll is at top
"""
return self.browser.execute_script("return $('html, body').offset().top") == 0
def _thread_is_rendered_successfully(self, thread_id):
return self.q(css=".discussion-article[data-id='{}']".format(thread_id)).visible
def click_and_open_thread(self, thread_id):
"""
Click specific thread on the list.
"""
thread_selector = "li[data-id='{}']".format(thread_id)
self.q(css=thread_selector).first.click()
EmptyPromise(
lambda: self._thread_is_rendered_successfully(thread_id),
"Thread has been rendered"
).fulfill()
def check_threads_rendered_successfully(self, thread_count):
"""
Count the number of threads available on page.
"""
return len(self.q(css=".forum-nav-thread").results) == thread_count
def check_window_is_on_top(self):
"""
Check window is on top of the page
"""
EmptyPromise(
self.is_window_on_top,
"Window is on top"
).fulfill()
class InlineDiscussionPage(PageObject):
url = None
def __init__(self, browser, discussion_id):
super(InlineDiscussionPage, self).__init__(browser)
self._discussion_selector = (
".discussion-module[data-discussion-id='{discussion_id}'] ".format(
discussion_id=discussion_id
)
)
def _find_within(self, selector):
"""
Returns a query corresponding to the given CSS selector within the scope
of this discussion page
"""
return self.q(css=self._discussion_selector + " " + selector)
def is_browser_on_page(self):
self.wait_for_ajax()
return self.q(css=self._discussion_selector).present
def is_discussion_expanded(self):
return self._find_within(".discussion").present
def expand_discussion(self):
"""Click the link to expand the discussion"""
self._find_within(".discussion-show").first.click()
EmptyPromise(
self.is_discussion_expanded,
"Discussion expanded"
).fulfill()
def get_num_displayed_threads(self):
return len(self._find_within(".discussion-thread"))
def has_thread(self, thread_id):
"""Returns true if this page is showing the thread with the specified id."""
return self._find_within('.discussion-thread#thread_{}'.format(thread_id)).present
def element_exists(self, selector):
return self.q(css=self._discussion_selector + " " + selector).present
def is_new_post_opened(self):
return self._find_within(".new-post-article").visible
def click_element(self, selector):
self.wait_for_element_presence(
"{discussion} {selector}".format(discussion=self._discussion_selector, selector=selector),
"{selector} is visible".format(selector=selector)
)
self._find_within(selector).click()
def click_cancel_new_post(self):
self.click_element(".cancel")
EmptyPromise(
lambda: not self.is_new_post_opened(),
"New post closed"
).fulfill()
def click_new_post_button(self):
self.click_element(".new-post-btn")
EmptyPromise(
self.is_new_post_opened,
"New post opened"
).fulfill()
@wait_for_js
def _is_element_visible(self, selector):
query = self._find_within(selector)
return query.present and query.visible
class InlineDiscussionThreadPage(DiscussionThreadPage):
def __init__(self, browser, thread_id):
super(InlineDiscussionThreadPage, self).__init__(
browser,
"body.courseware .discussion-module #thread_{thread_id}".format(thread_id=thread_id)
)
def expand(self):
"""Clicks the link to expand the thread"""
self._find_within(".forum-thread-expand").first.click()
EmptyPromise(
lambda: bool(self.get_response_total_text()),
"Thread expanded"
).fulfill()
def is_thread_anonymous(self):
return not self.q(css=".posted-details > .username").present
@wait_for_js
def check_if_selector_is_focused(self, selector):
"""
Check if selector is focused
"""
return self.browser.execute_script("return $('{}').is(':focus')".format(selector))
class DiscussionUserProfilePage(CoursePage):
TEXT_NEXT = u'Next >'
TEXT_PREV = u'< Previous'
PAGING_SELECTOR = "a.discussion-pagination[data-page-number]"
def __init__(self, browser, course_id, user_id, username, page=1):
super(DiscussionUserProfilePage, self).__init__(browser, course_id)
self.url_path = "discussion/forum/dummy/users/{}?page={}".format(user_id, page)
self.username = username
def is_browser_on_page(self):
return (
self.q(css='section.discussion-user-threads[data-course-id="{}"]'.format(self.course_id)).present
and
self.q(css='section.user-profile a.learner-profile-link').present
and
self.q(css='section.user-profile a.learner-profile-link').text[0] == self.username
)
@wait_for_js
def is_window_on_top(self):
return self.browser.execute_script("return $('html, body').offset().top") == 0
def get_shown_thread_ids(self):
elems = self.q(css="article.discussion-thread")
return [elem.get_attribute("id")[7:] for elem in elems]
def get_current_page(self):
def check_func():
try:
current_page = int(self.q(css="nav.discussion-paginator li.current-page").text[0])
except:
return False, None
return True, current_page
return Promise(
check_func, 'discussion-paginator current page has text', timeout=5,
).fulfill()
def _check_pager(self, text, page_number=None):
"""
returns True if 'text' matches the text in any of the pagination elements. If
page_number is provided, only return True if the element points to that result
page.
"""
elems = self.q(css=self.PAGING_SELECTOR).filter(lambda elem: elem.text == text)
if page_number:
elems = elems.filter(lambda elem: int(elem.get_attribute('data-page-number')) == page_number)
return elems.present
def get_clickable_pages(self):
return sorted([
int(elem.get_attribute('data-page-number'))
for elem in self.q(css=self.PAGING_SELECTOR)
if str(elem.text).isdigit()
])
def is_prev_button_shown(self, page_number=None):
return self._check_pager(self.TEXT_PREV, page_number)
def is_next_button_shown(self, page_number=None):
return self._check_pager(self.TEXT_NEXT, page_number)
def _click_pager_with_text(self, text, page_number):
"""
click the first pagination element with whose text is `text` and ensure
the resulting page number matches `page_number`.
"""
targets = [elem for elem in self.q(css=self.PAGING_SELECTOR) if elem.text == text]
targets[0].click()
EmptyPromise(
lambda: self.get_current_page() == page_number,
"navigated to desired page"
).fulfill()
def click_prev_page(self):
self._click_pager_with_text(self.TEXT_PREV, self.get_current_page() - 1)
EmptyPromise(
self.is_window_on_top,
"Window is on top"
).fulfill()
def click_next_page(self):
self._click_pager_with_text(self.TEXT_NEXT, self.get_current_page() + 1)
EmptyPromise(
self.is_window_on_top,
"Window is on top"
).fulfill()
def click_on_page(self, page_number):
self._click_pager_with_text(unicode(page_number), page_number)
EmptyPromise(
self.is_window_on_top,
"Window is on top"
).fulfill()
def click_on_sidebar_username(self):
self.wait_for_page()
self.q(css='.learner-profile-link').first.click()
class DiscussionTabHomePage(CoursePage, DiscussionPageMixin):
ALERT_SELECTOR = ".discussion-body .forum-nav .search-alert"
def __init__(self, browser, course_id):
super(DiscussionTabHomePage, self).__init__(browser, course_id)
self.url_path = "discussion/forum/"
def is_browser_on_page(self):
return self.q(css=".discussion-body section.home-header").present
def perform_search(self, text="dummy"):
self.q(css=".forum-nav-search-input").fill(text + chr(10))
EmptyPromise(
self.is_ajax_finished,
"waiting for server to return result"
).fulfill()
def get_search_alert_messages(self):
return self.q(css=self.ALERT_SELECTOR + " .message").text
def get_search_alert_links(self):
return self.q(css=self.ALERT_SELECTOR + " .link-jump")
def dismiss_alert_message(self, text):
"""
dismiss any search alert message containing the specified text.
"""
def _match_messages(text):
return self.q(css=".search-alert").filter(lambda elem: text in elem.text)
for alert_id in _match_messages(text).attrs("id"):
self.q(css="{}#{} a.dismiss".format(self.ALERT_SELECTOR, alert_id)).click()
EmptyPromise(
lambda: _match_messages(text).results == [],
"waiting for dismissed alerts to disappear"
).fulfill()
def click_new_post_button(self):
"""
Clicks the 'New Post' button.
"""
self.new_post_button.click()
EmptyPromise(
lambda: (
self.new_post_form
),
"New post action succeeded"
).fulfill()
@property
def new_post_button(self):
"""
Returns the new post button.
"""
elements = self.q(css="ol.course-tabs .new-post-btn")
return elements.first if elements.visible and len(elements) == 1 else None
@property
def new_post_form(self):
"""
Returns the new post form.
"""
elements = self.q(css=".forum-new-post-form")
return elements[0] if elements.visible and len(elements) == 1 else None
| agpl-3.0 |
salbrandi/patella | patella/tablereader.py | 1 | 1851 | """
This module is for reading the html tables that list world leaders off of varying webpages.
It is not very dynamic or robust, and has priority for updates.
More tables of FEs from countries around the world will be added so users can compare their data sets to different
world leaders.
"""
import pandas as pd
# A website with an html table to scrape for presidential term data
fe_url = 'http://www.enchantedlearning.com/history/us/pres/list.shtml'
fe_term_column = 2
header_row = 0
unique_text = 'Vice-President'
fe_table = pd.read_html(fe_url, match=unique_text, flavor='bs4', header=header_row,
index_col=fe_term_column, parse_dates=True)[0]
fe_names = []
index_list = fe_table.index.get_level_values(0).values.tolist() # slice the data frame index as a list
year_list = []
for term in index_list:
term_num = term.split('-')[0] # get the first year of the term number
year_list.append(term_num) # add it to the year list
fe_table['Year'] = year_list
fe_table.set_index('President', drop=False, inplace=True)
# Some formatting transformations are required for this table. This loop sets the fe names to only alpha chars
for item in fe_table.index.get_level_values(0).values.tolist():
fe_name = '' # reset the name
for char in item: # loop through each character to check if it is alpha-nonnumeric, and append it to a string
if char.isalpha() or char == ' ':
fe_name = fe_name + char
fe_names.append(fe_name) # append the string to the presidential names list
fe_table['President'] = fe_names # add the name list to the 'President' column of the fe dataframe
fe_table.set_index('Year', drop=True, inplace=True) # Set the index to the year column
# A simple getter function to return the fe dataframe when needed in other modules
def get_fe():
return fe_table
| mit |
dyoung418/tensorflow | tensorflow/tools/quantization/quantize_graph.py | 63 | 57187 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
r"""Transforms a float-trained graph into an equivalent quantized version.
An example of command-line usage is:
bazel build tensorflow/tools/quantization:quantize_graph \
&& bazel-bin/tensorflow/tools/quantization/quantize_graph \
--input=tensorflow_inception_graph.pb
--output_node_names="softmax2" --print_nodes --output=/tmp/quantized_graph.pb \
--mode=eightbit --logtostderr
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import re
import numpy as np
from tensorflow.core.framework import attr_value_pb2
from tensorflow.core.framework import graph_pb2
from tensorflow.core.framework import node_def_pb2
from tensorflow.python.client import session
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import graph_util
from tensorflow.python.framework import importer
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import array_ops
from tensorflow.python.platform import app
from tensorflow.python.platform import flags as flags_lib
from tensorflow.python.platform import gfile
flags = flags_lib
FLAGS = flags.FLAGS
flags.DEFINE_boolean("print_nodes", False, """Lists all nodes in the model.""")
flags.DEFINE_string("input", "", """TensorFlow 'GraphDef' file to load.""")
flags.DEFINE_string("output_node_names", "",
"""Output node names, comma separated.""")
flags.DEFINE_string("output", "", """File to save the output graph to.""")
flags.DEFINE_integer("bitdepth", 8,
"""How many bits to quantize the graph to.""")
flags.DEFINE_string("mode", "round",
"""What transformation to apply (round, quantize,"""
""" eightbit, weights, or weights_rounded).""")
flags.DEFINE_string("test_input_dims", "1,224,224,3",
"""The size of the input tensor to use when testing a"""
""" graph loaded from a file.""")
flags.DEFINE_boolean("strip_redundant_quantization", True,
"""Removes redundant dequantize/quantize pairs.""")
flags.DEFINE_boolean("quantized_input", False,
"If true, assume Placeholders are quantized with values "
"covering [--quantized_input_min,--quantized_input_max]. "
"Only supported when --mode=eightbit")
flags.DEFINE_float("quantized_input_min", 0,
"The minimum of the actual input range when "
"--quantized_input")
flags.DEFINE_float("quantized_input_max", 1,
"The maximum of the actual input range when "
"--quantized_input")
flags.DEFINE_float(
"quantized_fallback_min", None,
"The fallback 'min' value to use for layers which lack min-max "
"information. Note: this should be considered a coarse tool just good "
"enough for experimentation purposes, since graphs quantized in this way "
"would be very inaccurate.")
flags.DEFINE_float(
"quantized_fallback_max", None,
"The fallback 'max' value to use for layers which lack min-max "
"information. Note: this should be considered a coarse tool just good "
"enough for experimentation purposes, since graphs quantized in this way "
"would be very inaccurate.")
def print_input_nodes(current_node, nodes_map, indent, already_visited):
print(" " * indent + current_node.op + ":" + current_node.name)
already_visited[current_node.name] = True
for input_node_name in current_node.input:
if input_node_name in already_visited:
continue
input_node = nodes_map[input_node_name]
print_input_nodes(input_node, nodes_map, indent + 1, already_visited)
def create_node(op, name, inputs):
new_node = node_def_pb2.NodeDef()
new_node.op = op
new_node.name = name
for input_name in inputs:
new_node.input.extend([input_name])
return new_node
def create_constant_node(name, value, dtype, shape=None):
node = create_node("Const", name, [])
set_attr_dtype(node, "dtype", dtype)
set_attr_tensor(node, "value", value, dtype, shape)
return node
def copy_attr(node, key, attr_value):
try:
node.attr[key].CopyFrom(attr_value)
except KeyError:
pass
def set_attr_dtype(node, key, value):
try:
node.attr[key].CopyFrom(
attr_value_pb2.AttrValue(type=value.as_datatype_enum))
except KeyError:
pass
def set_attr_shape(node, key, value):
try:
node.attr[key].CopyFrom(
attr_value_pb2.AttrValue(shape=tensor_shape.as_shape(value).as_proto()))
except KeyError:
pass
def set_attr_tensor(node, key, value, dtype, shape=None):
try:
node.attr[key].CopyFrom(
attr_value_pb2.AttrValue(tensor=tensor_util.make_tensor_proto(
value, dtype=dtype, shape=shape)))
except KeyError:
pass
def set_attr_string(node, key, value):
try:
node.attr[key].CopyFrom(attr_value_pb2.AttrValue(s=value))
except KeyError:
pass
def set_attr_int_list(node, key, value):
list_value = attr_value_pb2.AttrValue.ListValue(i=value)
try:
node.attr[key].CopyFrom(attr_value_pb2.AttrValue(list=list_value))
except KeyError:
pass
def set_attr_bool(node, key, value):
try:
node.attr[key].CopyFrom(attr_value_pb2.AttrValue(b=value))
except KeyError:
pass
def set_attr_int(node, key, value):
try:
node.attr[key].CopyFrom(attr_value_pb2.AttrValue(i=value))
except KeyError:
pass
def set_attr_float(node, key, value):
try:
node.attr[key].CopyFrom(attr_value_pb2.AttrValue(f=value))
except KeyError:
pass
def node_name_from_input(node_name):
"""Strips off ports and other decorations to get the underlying node name."""
if node_name.startswith("^"):
node_name = node_name[1:]
m = re.search(r"(.*):\d+$", node_name)
if m:
node_name = m.group(1)
return node_name
def ensure_tensor_name_has_port(node_name):
"""Makes sure that a tensor name has :0 if no explicit port exists."""
m = re.search(r"(.*):\d+$", node_name)
if m:
name_with_port = node_name
else:
name_with_port = node_name + ":0"
return name_with_port
def unique_node_name_from_input(node_name):
"""Replaces invalid characters in input names to get a unique node name."""
return node_name.replace(":", "__port__").replace("^", "__hat__")
def quantize_array(arr, num_buckets):
"""Quantizes a numpy array.
This function maps each scalar in arr to the center of one of num_buckets
buckets. For instance,
quantize_array([0, 0.3, 0.6, 1], 2) => [0.25, 0.25, 0.75, 0.75]
Args:
arr: The numpy array to quantize.
num_buckets: The number of buckets to map "var" to.
Returns:
The quantized numpy array.
Raises:
ValueError: when num_buckets < 1.
"""
if num_buckets < 1:
raise ValueError("num_buckets must be >= 1")
arr_max = arr.max()
arr_min = arr.min()
if arr_max == arr_min:
return arr
bucket_width = (arr_max - arr_min) / num_buckets
# Map scalars to bucket indices. Take special care of max(arr).
bucket_indices = np.floor((arr - arr_min) / bucket_width)
bucket_indices[bucket_indices == num_buckets] = num_buckets - 1
# Map each scalar to the center of a bucket.
arr = arr_min + bucket_width * (bucket_indices + 0.5)
return arr
def quantize_weight_rounded(input_node):
"""Returns a replacement node for input_node containing bucketed floats."""
input_tensor = input_node.attr["value"].tensor
tensor_value = tensor_util.MakeNdarray(input_tensor)
shape = input_tensor.tensor_shape
# Currently, the parameter FLAGS.bitdepth is used to compute the
# number of buckets as 1 << FLAGS.bitdepth, meaning the number of
# buckets can only be a power of 2.
# This could be fixed by introducing a new parameter, num_buckets,
# which would allow for more flexibility in chosing the right model
# size/accuracy tradeoff. But I didn't want to add more parameters
# to this script than absolutely necessary.
num_buckets = 1 << FLAGS.bitdepth
tensor_value_rounded = quantize_array(tensor_value, num_buckets)
tensor_shape_list = tensor_util.TensorShapeProtoToList(shape)
return [
create_constant_node(
input_node.name,
tensor_value_rounded,
dtypes.float32,
shape=tensor_shape_list)
]
def quantize_weight_eightbit(input_node, quantization_mode):
"""Returns replacement nodes for input_node using the Dequantize op."""
base_name = input_node.name + "_"
quint8_const_name = base_name + "quint8_const"
min_name = base_name + "min"
max_name = base_name + "max"
float_tensor = tensor_util.MakeNdarray(input_node.attr["value"].tensor)
min_value = np.min(float_tensor.flatten())
max_value = np.max(float_tensor.flatten())
# Make sure that the range includes zero.
if min_value > 0.0:
min_value = 0.0
# min_value == max_value is a tricky case. It can occur for general
# tensors, and of course for scalars. The quantized ops cannot deal
# with this case, so we set max_value to something else.
# It's a tricky question what is the numerically best solution to
# deal with this degeneracy.
# TODO(petewarden): Better use a tolerance than a hard comparison?
if min_value == max_value:
if abs(min_value) < 0.000001:
max_value = min_value + 1.0
elif min_value > 0:
max_value = 2 * min_value
else:
max_value = min_value / 2.0
sess = session.Session()
with sess.as_default():
quantize_op = array_ops.quantize_v2(
float_tensor,
min_value,
max_value,
dtypes.quint8,
mode=quantization_mode)
quint8_tensor = quantize_op[0].eval()
shape = tensor_util.TensorShapeProtoToList(input_node.attr["value"]
.tensor.tensor_shape)
quint8_const_node = create_constant_node(
quint8_const_name, quint8_tensor, dtypes.quint8, shape=shape)
min_node = create_constant_node(min_name, min_value, dtypes.float32)
max_node = create_constant_node(max_name, max_value, dtypes.float32)
dequantize_node = create_node("Dequantize", input_node.name,
[quint8_const_name, min_name, max_name])
set_attr_dtype(dequantize_node, "T", dtypes.quint8)
set_attr_string(dequantize_node, "mode", quantization_mode)
return [quint8_const_node, min_node, max_node, dequantize_node]
EightbitizeRecursionState = collections.namedtuple(
"EightbitizeRecursionState",
["already_visited", "output_node_stack", "merged_with_fake_quant"])
class GraphRewriter(object):
"""Takes a float graph, and rewrites it in quantized form."""
def __init__(self,
input_graph,
mode,
quantized_input_range,
fallback_quantization_range=None):
"""Sets up the class to rewrite a float graph.
Args:
input_graph: A float graph to transform.
mode: A string controlling how quantization is performed -
round, quantize, eightbit, or weights.
quantized_input_range: if set, assume the input is
quantized and represents the range
[quantized_input_range[0], quantized_input_range[1]]
fallback_quantization_range: if set, then for nodes where the quantization
range can't be inferred from the graph, use the range
[fallback_quantization_range[0], fallback_quantization_range[1]) instead
of using a RequantizationRange node in the graph.
Raises:
ValueError: Two nodes with the same name were found in the graph.
"""
self.input_graph = input_graph
self.nodes_map = self.create_nodes_map(input_graph)
self.output_graph = None
self.mode = mode
self.final_node_renames = {}
if quantized_input_range:
self.input_range = (quantized_input_range[0], quantized_input_range[1])
if self.input_range[0] >= self.input_range[1]:
raise ValueError("Invalid quantized_input_range: [%s,%s]" %
self.input_range)
if self.mode != "eightbit":
raise ValueError(
"quantized_input_range can only be specified in eightbit mode")
else:
self.input_range = None
if fallback_quantization_range:
self.fallback_quantization_range = [
fallback_quantization_range[0], fallback_quantization_range[1]
]
if (self.fallback_quantization_range[0] >=
self.fallback_quantization_range[1]):
raise ValueError("Invalid fallback_quantization_range: [%s,%s]" %
self.fallback_quantization_range)
if self.mode != "eightbit":
raise ValueError("fallback_quantization_range can only be "
"specified in eightbit mode")
else:
self.fallback_quantization_range = None
# Data that is valid only during the recursive call to rewrite the graph.
self.state = None
def create_nodes_map(self, graph):
"""Builds a mapping of node names to their defs from the graph."""
nodes_map = {}
for node in graph.node:
if node.name not in nodes_map.keys():
nodes_map[node.name] = node
else:
raise ValueError("Duplicate node names detected.")
return nodes_map
def rewrite(self, output_node_names):
"""Triggers rewriting of the float graph.
Args:
output_node_names: A list of names of the nodes that produce the final
results.
Returns:
A quantized version of the float graph.
"""
self.output_graph = graph_pb2.GraphDef()
output_nodes = [
self.nodes_map[output_node_name]
for output_node_name in output_node_names
]
if self.mode == "round":
self.already_visited = {}
for output_node in output_nodes:
self.round_nodes_recursively(output_node)
elif self.mode == "quantize":
self.already_visited = {}
self.already_quantized = {}
for output_node in output_nodes:
self.quantize_nodes_recursively(output_node)
elif self.mode == "eightbit":
self.set_input_graph(graph_util.remove_training_nodes(self.input_graph))
output_nodes = [
self.nodes_map[output_node_name]
for output_node_name in output_node_names
]
self.state = EightbitizeRecursionState(
already_visited={}, output_node_stack=[], merged_with_fake_quant={})
for output_node in output_nodes:
self.eightbitize_nodes_recursively(output_node)
self.state = None
if self.input_range:
self.add_output_graph_node(
create_constant_node("quantized_input_min_value", self.input_range[
0], dtypes.float32, []))
self.add_output_graph_node(
create_constant_node("quantized_input_max_value", self.input_range[
1], dtypes.float32, []))
if self.fallback_quantization_range:
self.add_output_graph_node(
create_constant_node("fallback_quantization_min_value",
self.fallback_quantization_range[0],
dtypes.float32, []))
self.add_output_graph_node(
create_constant_node("fallback_quantization_max_value",
self.fallback_quantization_range[1],
dtypes.float32, []))
if FLAGS.strip_redundant_quantization:
self.output_graph = self.remove_redundant_quantization(
self.output_graph)
self.remove_dead_nodes(output_node_names)
self.apply_final_node_renames()
elif self.mode == "weights":
self.output_graph = self.quantize_weights(self.input_graph,
b"MIN_COMBINED")
self.remove_dead_nodes(output_node_names)
elif self.mode == "weights_rounded":
self.output_graph = self.quantize_weights(self.input_graph, self.mode)
self.remove_dead_nodes(output_node_names)
else:
print("Bad mode - " + self.mode + ".")
return self.output_graph
def round_nodes_recursively(self, current_node):
"""The entry point for simple rounding quantization."""
if (current_node.name in self.already_visited
) and self.already_visited[current_node.name]:
return
self.already_visited[current_node.name] = True
for input_node_name in current_node.input:
input_node_name = node_name_from_input(input_node_name)
input_node = self.nodes_map[input_node_name]
self.round_nodes_recursively(input_node)
nodes_to_quantize = ["Conv2D", "BiasAdd", "MatMul"]
if any(current_node.op in s for s in nodes_to_quantize):
new_node = node_def_pb2.NodeDef()
new_node.CopyFrom(current_node)
new_node.name = current_node.name + "_original"
self.add_output_graph_node(new_node)
levels = 1 << FLAGS.bitdepth
constant_name = current_node.name + "_round_depth"
constant_tensor = constant_op.constant(
levels, dtype=dtypes.int32, name=constant_name)
constant_node = constant_tensor.op.node_def
self.add_output_graph_node(constant_node)
quantize_node = node_def_pb2.NodeDef()
quantize_node.op = "RoundToSteps"
quantize_node.name = current_node.name
quantize_node.input.extend([current_node.name + "_original"])
quantize_node.input.extend([constant_node.name])
self.add_output_graph_node(quantize_node)
else:
new_node = node_def_pb2.NodeDef()
new_node.CopyFrom(current_node)
self.add_output_graph_node(new_node)
def quantize_nodes_recursively(self, current_node):
"""The entry point for quantizing nodes to eight bit and back."""
if self.already_visited[current_node.name]:
return
self.already_visited[current_node.name] = True
for input_node_name in current_node.input:
input_node_name = node_name_from_input(input_node_name)
input_node = self.nodes_map[input_node_name]
self.quantize_nodes_recursively(input_node)
nodes_to_quantize = ["Conv2D", "BiasAdd", "MatMul"]
if any(current_node.op in s for s in nodes_to_quantize):
for input_name in current_node.input:
input_name = node_name_from_input(input_name)
input_node = self.nodes_map[input_name]
self.quantize_node(input_node)
self.quantize_node(current_node)
else:
new_node = node_def_pb2.NodeDef()
new_node.CopyFrom(current_node)
self.add_output_graph_node(new_node)
def quantize_node(self, input_node):
"""Handles quantizing a single node."""
input_name = input_node.name
if input_name in self.already_quantized:
return
self.already_quantized[input_name] = True
original_input_name = input_name + "_original"
reshape_name = input_name + "_reshape"
reshape_dims_name = input_name + "_reshape_dims"
max_name = input_name + "_max"
min_name = input_name + "_min"
dims_name = input_name + "_dims"
quantize_name = input_name + "_quantize"
dequantize_name = input_name
original_input_node = node_def_pb2.NodeDef()
original_input_node.CopyFrom(input_node)
original_input_node.name = original_input_name
self.add_output_graph_node(original_input_node)
reshape_dims_node = create_constant_node(reshape_dims_name, -1,
dtypes.int32, [1])
self.add_output_graph_node(reshape_dims_node)
reshape_node = create_node("Reshape", reshape_name,
[original_input_name, reshape_dims_name])
set_attr_dtype(reshape_node, "T", dtypes.float32)
self.add_output_graph_node(reshape_node)
dims_node = create_constant_node(dims_name, 0, dtypes.int32, [1])
self.add_output_graph_node(dims_node)
max_node = create_node("Max", max_name, [reshape_name, dims_name])
set_attr_dtype(max_node, "T", dtypes.float32)
set_attr_bool(max_node, "keep_dims", False)
self.add_output_graph_node(max_node)
min_node = create_node("Min", min_name, [reshape_name, dims_name])
set_attr_dtype(min_node, "T", dtypes.float32)
set_attr_bool(min_node, "keep_dims", False)
self.add_output_graph_node(min_node)
quantize_node = create_node("Quantize", quantize_name,
[original_input_name, min_name, max_name])
set_attr_dtype(quantize_node, "T", dtypes.quint8)
set_attr_string(quantize_node, "mode", b"MIN_FIRST")
self.add_output_graph_node(quantize_node)
dequantize_node = create_node("Dequantize", dequantize_name,
[quantize_name, min_name, max_name])
set_attr_dtype(dequantize_node, "T", dtypes.quint8)
set_attr_string(dequantize_node, "mode", b"MIN_FIRST")
self.add_output_graph_node(dequantize_node)
def should_merge_with_fake_quant_node(self):
"""Should the current node merge with self.state.output_node_stack[-1]?"""
if not self.state.output_node_stack:
return False
top = self.state.output_node_stack[-1]
return top[1] == 0 and top[0].op in ["FakeQuantWithMinMaxVars"]
def should_quantize_const(self, node):
if not self.state.output_node_stack:
return False
top = self.state.output_node_stack[-1]
if not top[2]:
return False
dtype = dtypes.as_dtype(node.attr["dtype"].type)
assert dtype == dtypes.float32, (
"Failed to quantized constant %s of type %s" % (node.name, dtype))
return True
def eightbitize_nodes_recursively(self, current_node):
"""The entry point for transforming a graph into full eight bit."""
if current_node.name in self.state.already_visited:
if (self.should_merge_with_fake_quant_node() or
current_node.name in self.state.merged_with_fake_quant):
raise ValueError("Unsupported graph structure: output of node %s "
"is processed by a FakeQuant* node and should have "
"no other outputs.", current_node.name)
return
self.state.already_visited[current_node.name] = True
for i, input_node_name in enumerate(current_node.input):
quantize_input = False
if current_node.op in ("MatMul", "Conv2D", "BiasAdd", "MaxPool",
"AvgPool", "Relu", "Relu6",
"BatchNormWithGlobalNormalization"):
quantize_input = True
elif current_node.op == "Concat" and i > 0:
quantize_input = (
dtypes.as_dtype(current_node.attr["T"].type) == dtypes.float32)
elif current_node.op == "Reshape" and i == 0:
quantize_input = (
dtypes.as_dtype(current_node.attr["T"].type) == dtypes.float32)
self.state.output_node_stack.append((current_node, i, quantize_input))
input_node_name = node_name_from_input(input_node_name)
input_node = self.nodes_map[input_node_name]
self.eightbitize_nodes_recursively(input_node)
self.state.output_node_stack.pop()
if current_node.op == "MatMul":
self.eightbitize_mat_mul_node(current_node)
elif current_node.op == "Conv2D":
self.eightbitize_conv_node(current_node)
elif current_node.op == "BiasAdd":
self.eightbitize_bias_add_node(current_node)
elif current_node.op == "MaxPool" or current_node.op == "AvgPool":
self.eightbitize_single_input_tensor_node(current_node,
self.add_pool_function)
elif current_node.op == "Relu" or current_node.op == "Relu6":
self.eightbitize_single_input_tensor_node(current_node,
self.add_relu_function)
elif (current_node.op == "Concat" and
dtypes.as_dtype(current_node.attr["T"].type) == dtypes.float32):
self.eightbitize_concat_node(current_node)
elif current_node.op == "BatchNormWithGlobalNormalization":
self.eightbitize_batch_norm_node(current_node)
elif (current_node.op == "Reshape" and
dtypes.as_dtype(current_node.attr["T"].type) == dtypes.float32):
self.eightbitize_reshape_node(current_node)
elif (self.input_range and
current_node.op in ("Placeholder", "PlaceholderV2")):
self.eightbitize_placeholder_node(current_node)
elif current_node.op == "FakeQuantWithMinMaxVars":
# It will have been merged into the underlying node.
pass
elif current_node.op == "Const":
if self.should_quantize_const(current_node):
for n in quantize_weight_eightbit(current_node, b"MIN_FIRST"):
self.add_output_graph_node(n)
else:
new_node = node_def_pb2.NodeDef()
new_node.CopyFrom(current_node)
self.add_output_graph_node(new_node)
###################################################################
# Note: if more cases are added here, you may need to update the op
# name lists in the loop over children at the start of the function.
###################################################################
else:
new_node = node_def_pb2.NodeDef()
new_node.CopyFrom(current_node)
self.add_output_graph_node(new_node)
if (self.should_merge_with_fake_quant_node() and
current_node.name not in self.state.merged_with_fake_quant):
raise ValueError(
"FakeQuant* node %s failed to merge with node %s of type %s" %
(self.state.output_node_stack[-1][0], current_node.name,
current_node.op))
def add_eightbit_prologue_nodes(self, original_node):
"""Adds input conversion nodes to handle quantizing the underlying node."""
namespace_prefix = original_node.name + "_eightbit"
reshape_dims_name, reduction_dims_name = self.add_common_quantization_nodes(
namespace_prefix)
input_names = []
min_max_names = []
for original_input_name in original_node.input:
quantize_input_name, min_input_name, max_input_name = (
self.eightbitize_input_to_node(namespace_prefix, original_input_name,
reshape_dims_name,
reduction_dims_name))
input_names.append(quantize_input_name)
min_max_names.append(min_input_name)
min_max_names.append(max_input_name)
all_input_names = []
all_input_names.extend(input_names)
all_input_names.extend(min_max_names)
return all_input_names
def add_common_quantization_nodes(self, namespace_prefix):
"""Builds constant nodes needed for quantization of inputs."""
reshape_dims_name = namespace_prefix + "_reshape_dims"
reduction_dims_name = namespace_prefix + "_reduction_dims"
reshape_dims_node = create_constant_node(reshape_dims_name, -1,
dtypes.int32, [1])
self.add_output_graph_node(reshape_dims_node)
reduction_dims_node = create_constant_node(reduction_dims_name, 0,
dtypes.int32, [1])
self.add_output_graph_node(reduction_dims_node)
return reshape_dims_name, reduction_dims_name
def eightbitize_input_to_node(self, namespace_prefix, original_input_name,
reshape_dims_name, reduction_dims_name):
"""Takes one float input to an op, and converts it to quantized form."""
unique_input_name = unique_node_name_from_input(original_input_name)
reshape_input_name = namespace_prefix + "_reshape_" + unique_input_name
min_input_name = namespace_prefix + "_min_" + unique_input_name
max_input_name = namespace_prefix + "_max_" + unique_input_name
quantize_input_name = namespace_prefix + "_quantize_" + unique_input_name
reshape_input_node = create_node("Reshape", reshape_input_name,
[original_input_name, reshape_dims_name])
set_attr_dtype(reshape_input_node, "T", dtypes.float32)
self.add_output_graph_node(reshape_input_node)
min_input_node = create_node("Min", min_input_name,
[reshape_input_name, reduction_dims_name])
set_attr_dtype(min_input_node, "T", dtypes.float32)
set_attr_bool(min_input_node, "keep_dims", False)
self.add_output_graph_node(min_input_node)
max_input_node = create_node("Max", max_input_name,
[reshape_input_name, reduction_dims_name])
set_attr_dtype(max_input_node, "T", dtypes.float32)
set_attr_bool(max_input_node, "keep_dims", False)
self.add_output_graph_node(max_input_node)
quantize_input_node = create_node(
"QuantizeV2", quantize_input_name,
[original_input_name, min_input_name, max_input_name])
set_attr_dtype(quantize_input_node, "T", dtypes.quint8)
set_attr_string(quantize_input_node, "mode", b"MIN_FIRST")
self.add_output_graph_node(quantize_input_node)
min_output_name = quantize_input_name + ":1"
max_output_name = quantize_input_name + ":2"
return quantize_input_name, min_output_name, max_output_name
def add_quantize_down_nodes(self, original_node, quantized_output_name):
quantized_outputs = [
quantized_output_name, quantized_output_name + ":1",
quantized_output_name + ":2"
]
min_max_inputs = None
if self.should_merge_with_fake_quant_node():
# Use the inputs to the FakeQuantWithMinMaxVars node as the inputs to
# Requantize.
fake_quant_node = self.state.output_node_stack[-1][0]
min_max_inputs = [fake_quant_node.input[1], fake_quant_node.input[2]]
assert original_node.name not in self.state.merged_with_fake_quant
self.state.merged_with_fake_quant[original_node.name] = True
elif self.fallback_quantization_range:
min_max_inputs = [
"fallback_quantization_min_value:0",
"fallback_quantization_max_value:0"
]
else:
# Add a RequantizationRange node for finding the min and max values.
requant_range_node = create_node(
"RequantizationRange", original_node.name + "_eightbit_requant_range",
quantized_outputs)
set_attr_dtype(requant_range_node, "Tinput", dtypes.qint32)
self.add_output_graph_node(requant_range_node)
min_max_inputs = [
requant_range_node.name + ":0", requant_range_node.name + ":1"
]
requantize_node = create_node("Requantize",
original_node.name + "_eightbit_requantize",
quantized_outputs + min_max_inputs)
set_attr_dtype(requantize_node, "Tinput", dtypes.qint32)
set_attr_dtype(requantize_node, "out_type", dtypes.quint8)
self.add_output_graph_node(requantize_node)
return requantize_node.name
def add_dequantize_result_node(self,
quantized_output_name,
original_node_name,
min_tensor_index=1):
min_max_inputs = [
"%s:%s" % (quantized_output_name, min_tensor_index),
"%s:%s" % (quantized_output_name, (min_tensor_index + 1))
]
dequantize_name = original_node_name
if self.should_merge_with_fake_quant_node():
fake_quant_node = self.state.output_node_stack[-1][0]
if original_node_name not in self.state.merged_with_fake_quant:
min_max_inputs = [fake_quant_node.input[1], fake_quant_node.input[2]]
self.state.merged_with_fake_quant[original_node_name] = True
dequantize_name = fake_quant_node.name
dequantize_node = create_node(
"Dequantize", dequantize_name,
[quantized_output_name, min_max_inputs[0], min_max_inputs[1]])
set_attr_dtype(dequantize_node, "T", dtypes.quint8)
set_attr_string(dequantize_node, "mode", b"MIN_FIRST")
self.add_output_graph_node(dequantize_node)
def eightbitize_mat_mul_node(self, original_node):
"""Replaces a MatMul node with the eight bit equivalent sub-graph."""
quantized_mat_mul_name = original_node.name + "_eightbit_quantized_mat_mul"
all_input_names = self.add_eightbit_prologue_nodes(original_node)
quantized_mat_mul_node = create_node("QuantizedMatMul",
quantized_mat_mul_name,
all_input_names)
set_attr_dtype(quantized_mat_mul_node, "T1", dtypes.quint8)
set_attr_dtype(quantized_mat_mul_node, "T2", dtypes.quint8)
set_attr_dtype(quantized_mat_mul_node, "Toutput", dtypes.qint32)
copy_attr(quantized_mat_mul_node, "transpose_a",
original_node.attr["transpose_a"])
copy_attr(quantized_mat_mul_node, "transpose_b",
original_node.attr["transpose_b"])
self.add_output_graph_node(quantized_mat_mul_node)
quantize_down_name = self.add_quantize_down_nodes(original_node,
quantized_mat_mul_name)
self.add_dequantize_result_node(quantize_down_name, original_node.name)
def eightbitize_conv_node(self, original_node):
"""Replaces a Conv2D node with the eight bit equivalent sub-graph."""
all_input_names = self.add_eightbit_prologue_nodes(original_node)
quantized_conv_name = original_node.name + "_eightbit_quantized_conv"
quantized_conv_node = create_node("QuantizedConv2D", quantized_conv_name,
all_input_names)
copy_attr(quantized_conv_node, "strides", original_node.attr["strides"])
copy_attr(quantized_conv_node, "padding", original_node.attr["padding"])
set_attr_dtype(quantized_conv_node, "Tinput", dtypes.quint8)
set_attr_dtype(quantized_conv_node, "Tfilter", dtypes.quint8)
set_attr_dtype(quantized_conv_node, "out_type", dtypes.qint32)
self.add_output_graph_node(quantized_conv_node)
quantize_down_name = self.add_quantize_down_nodes(original_node,
quantized_conv_name)
self.add_dequantize_result_node(quantize_down_name, original_node.name)
def eightbitize_bias_add_node(self, original_node):
"""Replaces a BiasAdd node with the eight bit equivalent sub-graph."""
quantized_bias_add_name = (
original_node.name + "_eightbit_quantized_bias_add")
all_input_names = self.add_eightbit_prologue_nodes(original_node)
quantized_bias_add_node = create_node("QuantizedBiasAdd",
quantized_bias_add_name,
all_input_names)
set_attr_dtype(quantized_bias_add_node, "T1", dtypes.quint8)
set_attr_dtype(quantized_bias_add_node, "T2", dtypes.quint8)
set_attr_dtype(quantized_bias_add_node, "out_type", dtypes.qint32)
self.add_output_graph_node(quantized_bias_add_node)
quantize_down_name = self.add_quantize_down_nodes(original_node,
quantized_bias_add_name)
self.add_dequantize_result_node(quantize_down_name, original_node.name)
def eightbitize_single_input_tensor_node(self, original_node,
add_op_function):
"""Replaces a single-tensor node with the eight bit equivalent sub-graph.
Converts a node like this:
Shape(f) Input(f)
| |
+--------v v
Operation
|
v
(f)
Into a quantized equivalent:
Input(f) ReshapeDims
+------v v-------------+
| Reshape
| |
| | ReductionDims
| +-----+ |
| | +---c---------+
| v v v v-------+
| Min Max
| +----+ |
v v v--------+
Quantize
|
v
QuantizedOperation
| | |
v v v
Dequantize
|
v
(f)
Args:
original_node: Float node to be converted.
add_op_function: Function to create the actual node.
Returns:
Subgraph representing the quantized version of the original node.
"""
quantized_op_name = original_node.name + "_eightbit_quantized"
quantized_op_type = "Quantized" + original_node.op
all_input_names = self.add_eightbit_prologue_nodes(original_node)
quantized_op_node = create_node(quantized_op_type, quantized_op_name,
all_input_names)
add_op_function(original_node, quantized_op_node)
self.add_output_graph_node(quantized_op_node)
self.add_dequantize_result_node(quantized_op_name, original_node.name)
def add_pool_function(self, original_node, quantized_op_node):
set_attr_dtype(quantized_op_node, "T", dtypes.quint8)
copy_attr(quantized_op_node, "ksize", original_node.attr["ksize"])
copy_attr(quantized_op_node, "strides", original_node.attr["strides"])
copy_attr(quantized_op_node, "padding", original_node.attr["padding"])
def add_relu_function(self, unused_arg_node, quantized_op_node):
set_attr_dtype(quantized_op_node, "Tinput", dtypes.quint8)
def eightbitize_concat_node(self, original_node):
"""Replaces a Concat node with the eight bit equivalent sub-graph.
Converts a node like this:
Shape(f) Input0(f) Input1(f)
| | |
+--------v v v----------+
Concat
|
v
(f)
Into a quantized equivalent:
Shape(f) Input0(f) ReshapeDims Input1(f)
| +------v v--------------+------------------v v------+
| | Reshape Reshape |
| | | | |
| | | ReductionDims | |
| | +------+ | +--------+ |
| | | +---c---------+-----------c-----+ | |
| | +v v v v-------+---------v v v v+ |
| | Min Max Min Max |
| | +----+ | | +-----+ |
| v v v--------+ +----------v v v
| Quantize Quantize
| +------------------+ +----------------------+
+-------------------------------+ | |
v v v
QuantizedConcat
| | |
v v v
Dequantize
|
v
(f)
Args:
original_node: Float node to be converted.
Returns:
Subgraph representing the quantized version of the original node.
"""
namespace_prefix = original_node.name + "_eightbit"
quantized_concat_name = namespace_prefix + "_quantized_concat"
reshape_dims_name, reduction_dims_name = self.add_common_quantization_nodes(
namespace_prefix)
shape_input_name = original_node.input[0]
original_inputs = original_node.input[1:]
input_names = []
min_names = []
max_names = []
for original_input_name in original_inputs:
quantize_input_name, min_input_name, max_input_name = (
self.eightbitize_input_to_node(namespace_prefix, original_input_name,
reshape_dims_name,
reduction_dims_name))
input_names.append(quantize_input_name)
min_names.append(min_input_name)
max_names.append(max_input_name)
all_input_names = [shape_input_name]
all_input_names.extend(input_names)
all_input_names.extend(min_names)
all_input_names.extend(max_names)
quantized_concat_node = create_node("QuantizedConcat",
quantized_concat_name, all_input_names)
set_attr_int(quantized_concat_node, "N", len(original_inputs))
set_attr_dtype(quantized_concat_node, "T", dtypes.quint8)
self.add_output_graph_node(quantized_concat_node)
self.add_dequantize_result_node(quantized_concat_name, original_node.name)
def eightbitize_placeholder_node(self, current_node):
"""Replaces a placeholder node with a quint8 placeholder node+dequantize."""
name = current_node.name
# Convert the placeholder into a quantized type.
output_node = node_def_pb2.NodeDef()
output_node.CopyFrom(current_node)
set_attr_dtype(output_node, "dtype", dtypes.quint8)
output_node.name += "_original_input"
self.add_output_graph_node(output_node)
# Add a dequantize to convert back to float.
dequantize_node = create_node("Dequantize", name, [
output_node.name, "quantized_input_min_value",
"quantized_input_max_value"
])
set_attr_dtype(dequantize_node, "T", dtypes.quint8)
set_attr_string(dequantize_node, "mode", b"MIN_FIRST")
self.add_output_graph_node(dequantize_node)
# For the descent over the graph to work, the dequantize node must be named
# current_node.name. However, for the feeding of the graph to work, the
# placeholder must have the name current_node.name; so record a final set
# of renames to apply after all processing has been done.
self.final_node_renames[output_node.name] = name
self.final_node_renames[dequantize_node.name] = name + "_dequantize"
def eightbitize_reshape_node(self, original_node):
"""Replaces a Reshape node with the eight bit equivalent sub-graph.
Args:
original_node: Float node to be converted.
Returns:
Subgraph representing the quantized version of the original node.
"""
namespace_prefix = original_node.name + "_eightbit"
quantized_reshape_name = namespace_prefix + "_quantized_reshape"
reshape_dims_name, reduction_dims_name = self.add_common_quantization_nodes(
namespace_prefix)
shape_input_name = original_node.input[1]
quantize_input_name, min_input_name, max_input_name = (
self.eightbitize_input_to_node(namespace_prefix, original_node.input[0],
reshape_dims_name, reduction_dims_name))
quantized_reshape_node = create_node(
"QuantizedReshape", quantized_reshape_name,
[quantize_input_name, shape_input_name, min_input_name, max_input_name])
set_attr_dtype(quantized_reshape_node, "T", dtypes.quint8)
self.add_output_graph_node(quantized_reshape_node)
self.add_dequantize_result_node(quantized_reshape_name, original_node.name)
def eightbitize_batch_norm_node(self, original_node):
"""Replaces a MatMul node with the eight bit equivalent sub-graph."""
namespace_prefix = original_node.name + "_eightbit"
original_input_name = original_node.input[0]
original_mean_name = original_node.input[1]
original_variance_name = original_node.input[2]
original_beta_name = original_node.input[3]
original_gamma_name = original_node.input[4]
quantized_batch_norm_name = namespace_prefix + "_quantized_batch_norm"
reshape_dims_name, reduction_dims_name = self.add_common_quantization_nodes(
namespace_prefix)
quantize_input_name, min_input_name, max_input_name = (
self.eightbitize_input_to_node(namespace_prefix, original_input_name,
reshape_dims_name, reduction_dims_name))
quantize_mean_name, min_mean_name, max_mean_name = (
self.eightbitize_input_to_node(namespace_prefix, original_mean_name,
reshape_dims_name, reduction_dims_name))
quantize_variance_name, min_variance_name, max_variance_name = (
self.eightbitize_input_to_node(namespace_prefix, original_variance_name,
reshape_dims_name, reduction_dims_name))
quantize_beta_name, min_beta_name, max_beta_name = (
self.eightbitize_input_to_node(namespace_prefix, original_beta_name,
reshape_dims_name, reduction_dims_name))
quantize_gamma_name, min_gamma_name, max_gamma_name = (
self.eightbitize_input_to_node(namespace_prefix, original_gamma_name,
reshape_dims_name, reduction_dims_name))
quantized_batch_norm_node = create_node(
"QuantizedBatchNormWithGlobalNormalization", quantized_batch_norm_name,
[
quantize_input_name, min_input_name, max_input_name,
quantize_mean_name, min_mean_name, max_mean_name,
quantize_variance_name, min_variance_name, max_variance_name,
quantize_beta_name, min_beta_name, max_beta_name,
quantize_gamma_name, min_gamma_name, max_gamma_name
])
set_attr_dtype(quantized_batch_norm_node, "Tinput", dtypes.quint8)
set_attr_dtype(quantized_batch_norm_node, "out_type", dtypes.qint32)
copy_attr(quantized_batch_norm_node, "scale_after_normalization",
original_node.attr["scale_after_normalization"])
copy_attr(quantized_batch_norm_node, "variance_epsilon",
original_node.attr["variance_epsilon"])
self.add_output_graph_node(quantized_batch_norm_node)
quantize_down_name = self.add_quantize_down_nodes(original_node,
quantized_batch_norm_name)
self.add_dequantize_result_node(quantize_down_name, original_node.name)
def add_output_graph_node(self, output_node):
"""Inserts one node into the new graph."""
self.output_graph.node.extend([output_node])
def remove_redundant_quantization(self, old_graph):
"""Removes unneeded pairs of quantize/dequantize ops from the graph.
This is a bit of a tricky function, because it's attempting to spot the
pattern of dequantizing from eight-bit up to float, and then immediately
quantizing back down to eight bits again, that's introduced by previous
passes that do 'key-hole' conversions of individual nodes but have to
convert back to float to match the previous output interface, since they
don't know that the next op can handle quantized tensors.
It works by:
- Looking for Quantize nodes.
- Checking to see if their first input is a Dequantize node.
- Seeing if their min/max inputs come from Min/Max nodes.
- Making sure those Min/Max nodes are being fed from the same Dequantize.
- Or that the Min is indirectly being fed from the same Dequantize as Max.
- Making sure the Dequantize is going through a Reshape (which we add
during the previous pass when we create the quantize sub-graph).
- Looking for the dims Const op for the Min/Max dims.
If all of these conditions are met, then it's a sub-graph pattern that
we know how to optimize out (and is likely the common one we've introduced).
We then rewire the graph to skip it entirely, and then rely on the dead node
removal pass to get rid of any nodes that are no longer needed.
Args:
old_graph: The model we'll be stripping redundant nodes from.
Returns:
A graph with the unnecessary nodes removed.
Raises:
ValueError: Two nodes with the same name were found in the graph.
"""
old_nodes_map = self.create_nodes_map(old_graph)
self.output_graph = graph_pb2.GraphDef()
inputs_to_rename = {}
# We go through all the nodes, looking for any that match the patterns we
# know how to optimize away.
for node in old_graph.node:
# We always start with a Quantize node, and examine its inputs to see if
# they are in a form that can be removed.
if node.op not in ["Quantize", "QuantizeV2"]:
continue
dequantize_node_name = node_name_from_input(node.input[0])
if dequantize_node_name not in old_nodes_map:
raise ValueError("Input node name '" + dequantize_node_name +
"' not found in node '" + node.name + "'")
dequantize_node = old_nodes_map[dequantize_node_name]
# Do we have a Dequantize feeding in, with the same type as the Quantize?
if dequantize_node.op != "Dequantize":
continue
if node.attr["T"] != dequantize_node.attr["T"]:
continue
# Now look at the other inputs, and ensure they're Min/Max nodes.
min_node_name = node_name_from_input(node.input[1])
max_node_name = node_name_from_input(node.input[2])
min_node = old_nodes_map[min_node_name]
max_node = old_nodes_map[max_node_name]
is_min_right_type = (min_node.op in ["Min", "Dequantize"])
is_max_right_type = (max_node.op in ["Max", "Dequantize"])
if not is_min_right_type or not is_max_right_type:
print("Didn't find expected types on inputs : %s, %s." % (min_node.op,
max_node.op))
continue
min_node_input_name = node_name_from_input(min_node.input[0])
max_node_input_name = node_name_from_input(max_node.input[0])
# There are two different patterns for Min nodes we can recognize, one
# where the input comes directly from the same one as the Max, and
# another where we run it through another Min first, so check for both.
is_same_input = False
if min_node_input_name == max_node_input_name:
is_same_input = True
else:
first_min_node_input = old_nodes_map[min_node_input_name]
if first_min_node_input.op == "Concat":
second_min_node_name = node_name_from_input(
first_min_node_input.input[1])
second_min_node = old_nodes_map[second_min_node_name]
if second_min_node.op == "Min":
second_min_node_input_name = node_name_from_input(
second_min_node.input[0])
is_same_input = (second_min_node_input_name == max_node_input_name)
if not is_same_input:
print("Different min/max inputs: " + min_node_input_name)
continue
# We recognize this pattern, so mark the graph edges to be rewired to
# route around it entirely, since we know it's a no-op.
dequantize_source_name = node_name_from_input(dequantize_node.input[0])
node_tensor_name = ensure_tensor_name_has_port(node.name)
min_tensor_name = node.name + ":1"
max_tensor_name = node.name + ":2"
inputs_to_rename[node_tensor_name] = dequantize_source_name
inputs_to_rename[min_tensor_name] = dequantize_node.input[1]
inputs_to_rename[max_tensor_name] = dequantize_node.input[2]
# Finally we apply all the rewiring we've marked to the graph.
for node in old_graph.node:
for index, input_full_name in enumerate(node.input):
input_name = ensure_tensor_name_has_port(input_full_name)
if input_name in inputs_to_rename:
node.input[index] = inputs_to_rename[input_name]
self.add_output_graph_node(node)
return self.output_graph
def apply_final_node_renames(self):
"""Applies node renames in self.final_node_renames to self.output_graph."""
old_graph = self.output_graph
self.output_graph = graph_pb2.GraphDef()
for node in old_graph.node:
node.name = self.final_node_renames.get(node.name, node.name)
for index, input_name in enumerate(node.input):
node_name = node_name_from_input(input_name)
input_full_name = ensure_tensor_name_has_port(input_name)
if node_name in self.final_node_renames:
node.input[index] = "%s%s" % (self.final_node_renames[node_name],
input_full_name[len(node_name):])
self.add_output_graph_node(node)
return self.output_graph
def remove_dead_nodes(self, output_names):
"""Removes nodes that are no longer needed for inference from the graph."""
old_output_graph = self.output_graph
self.output_graph = graph_util.extract_sub_graph(old_output_graph,
output_names)
def quantize_weights(self, input_graph, quantization_mode):
"""Quantize float Const ops.
There are two modes of operations, both replace float Const ops with
quantized values.
1. If quantization_mode is "weights_rounded", this function replaces float
Const ops with quantized float Const ops - same as the original op, but
float values being mapped to the center of one of 1<<FLAGS.bitdepth buckets.
This does not change the raw model size, but compression algorithms such as
zip (as used for compressing apks) or bzip2 will achieve a very good
compression ratio.
2. For other quantization modes ("MIN_COMBINED" or "MIN_FIRST"), float
Const ops are quantized and replaced by a tuple of four ops to perform
the dequantization at runtime:
* eight-bit Const (bucket indices, same shape as original float Const op
* two float Const ops (min and max value of original float Const op)
* Dequantize op to convert the eight-bit consts to float tensors.
The quantization mode is important because we see accuracy problems when
quantizing weights for different situations depending on the algorithm
used. We haven't figured out exactly what the underlying cause is yet,
unfortunately.
Args:
input_graph: A GraphDef of the model containing float Const ops.
quantization_mode: How to quantize and dequantize the values.
Returns:
A GraphDef of the converted graph.
Raises:
ValueError: If quantization_mode is unsupported.
"""
output_graph = graph_pb2.GraphDef()
for input_node in input_graph.node:
should_quantize = False
if input_node.op == "Const":
dtype = dtypes.as_dtype(input_node.attr["dtype"].type)
if dtype == dtypes.float32:
should_quantize = True
if should_quantize:
if quantization_mode == "weights_rounded":
output_graph.node.extend(quantize_weight_rounded(input_node))
elif quantization_mode in (b"MIN_COMBINED", b"MIN_FIRST"):
output_graph.node.extend(
quantize_weight_eightbit(input_node, quantization_mode))
else:
raise ValueError("Unsupported quantization mode %s." %
quantization_mode)
else:
output_node = node_def_pb2.NodeDef()
output_node.CopyFrom(input_node)
output_graph.node.extend([output_node])
return output_graph
def set_input_graph(self, new_input_graph):
self.input_graph = new_input_graph
self.nodes_map = self.create_nodes_map(self.input_graph)
def main(unused_args):
if not gfile.Exists(FLAGS.input):
print("Input graph file '" + FLAGS.input + "' does not exist!")
return -1
known_modes = [
"round", "quantize", "eightbit", "weights", "test", "weights_rounded"
]
if not any(FLAGS.mode in s for s in known_modes):
print("mode is '" + FLAGS.mode + "', not in " + ", ".join(known_modes) +
".")
return -1
tf_graph = graph_pb2.GraphDef()
with gfile.Open(FLAGS.input, "rb") as f:
data = f.read()
tf_graph.ParseFromString(data)
graph = ops.Graph()
with graph.as_default():
importer.import_graph_def(tf_graph, input_map={}, name="")
quantized_input_range = None
if FLAGS.quantized_input:
quantized_input_range = [
FLAGS.quantized_input_min, FLAGS.quantized_input_max
]
fallback_quantization_range = None
if (FLAGS.quantized_fallback_min is not None or
FLAGS.quantized_fallback_max is not None):
assert FLAGS.quantized_fallback_min is not None
assert FLAGS.quantized_fallback_max is not None
fallback_quantization_range = [
FLAGS.quantized_fallback_min, FLAGS.quantized_fallback_max
]
rewriter = GraphRewriter(tf_graph, FLAGS.mode, quantized_input_range,
fallback_quantization_range)
output_graph = rewriter.rewrite(FLAGS.output_node_names.split(","))
f = gfile.FastGFile(FLAGS.output, "wb")
f.write(output_graph.SerializeToString())
return 0
if __name__ == "__main__":
app.run()
| apache-2.0 |
yograterol/Simulated-Annealing | recocido_simulado.py | 1 | 3700 | """
Implementacion del algoritmo de recocido simulado
para la materia electiva Computacion Emergente
@author Yohan Graterol <yograterol@fedoraproject.org> 2013
"""
from collections import deque
from math import exp
try:
from numpy.random import (permutation, random_sample)
from numpy import (log, matrix, array, add)
except ImportError:
from numpypy.random import (permutation, random_sample)
from numpypy import (log, matrix, array, add)
from copy import deepcopy
from random import randint
from time import time
class LoadData(object):
__slots__ = ['data', 'matrix']
file_name = 'tsp29.txt'
def __init__(self, file_name=None):
if file_name:
self.file_name = file_name
self.load_data()
def load_data(self):
tmp_file = open(self.file_name)
self.data = tmp_file.readlines()
self.data.append('0 0')
tmp_file.close()
def create_matrix(self):
self.matrix = list()
total_line = len(self.data)
for line in self.data:
line = deque(map(lambda x: int(x), line.split()))
for i in range(total_line - len(line)):
line.appendleft(0)
self.matrix.append(list(line))
self.matrix = array(self.matrix)
self.matrix = add(self.matrix, self.matrix.transpose())
class SimulatedAnnealing(object):
__slots__ = ['matrix', 'T', 't', 't_final', 'step', 'cities', 'firts_vc',
'Vc', 'Vn', 'Vc_eval', 'Vn_eval', 'alpha']
def __init__(self, T=1000, alpha=0.9899, t_final=0.001, t=1, cities=29, step=200):
data = LoadData()
data.create_matrix()
self.matrix = data.matrix
self.T = T
#self.t = t
self.t_final = t_final
self.alpha = alpha
self.cities = cities
self.Vc = None
self.firts_vc = range(self.cities)
self.step = step
#import pandas
#print pandas.DataFrame(self.matrix, range(self.cities), range(self.cities))
def tsp(self):
self.Vc = self.generate_solution()
self.Vc_eval = self.eval_solution(self.Vc)
while(self.T > self.t_final):
for i in range(self.step):
self.Vn = self.generate_solution(self.Vc)
self.Vn_eval = self.eval_solution(self.Vn)
delta = self.Vn_eval - self.Vc_eval
if delta < 0:
self.Vc = self.Vn
self.Vc_eval = self.Vn_eval
elif random_sample() < exp(-delta/self.T):
self.Vc = self.Vn
self.Vc_eval = self.Vn_eval
self.T *= self.alpha
#self.T *= self.reduce_temp(self.t)
#self.t += 1
def reduce_temp(self, t):
return self.alpha / log(1 + t)
def generate_solution(self, Vc=None):
if Vc is None:
Vn = list(permutation(self.firts_vc))
return Vn
Vn = deepcopy(Vc)
i1 = randint(0, self.cities - 1)
i2 = randint(0, self.cities - 1)
while(i1 == i2):
i2 = randint(0, self.cities - 1)
Vn[i1], Vn[i2] = Vn[i2], Vn[i1]
return Vn
def eval_solution(self, Vn):
km = 0
for c in range(len(Vn) - 1):
i = Vn[c]
j = Vn[c + 1]
km += self.matrix[i][j]
km += self.matrix[Vn[0]][Vn[self.cities - 1]]
return km
def print_result(self):
print self.Vc
print self.eval_solution(self.Vc)
if __name__ == '__main__':
start = time()
tsp = SimulatedAnnealing()
tsp.tsp()
print "Resultado optimo"
tsp.print_result()
print "Tiempo: ", time() - start
| bsd-3-clause |
suttond/MODOI | ase/phasediagram.py | 2 | 20868 | from __future__ import division, print_function
import fractions
import functools
import re
import numpy as np
from scipy.spatial import ConvexHull, Delaunay
import ase.units as units
from ase.atoms import string2symbols
from ase.utils import hill
_solvated = []
def parse_formula(formula):
aq = formula.endswith('(aq)')
if aq:
formula = formula[:-4]
charge = formula.count('+') - formula.count('-')
if charge:
formula = formula.rstrip('+-')
count = {}
for symbol in string2symbols(formula):
count[symbol] = count.get(symbol, 0) + 1
return count, charge, aq
def float2str(x):
f = fractions.Fraction(x).limit_denominator(100)
n = f.numerator
d = f.denominator
if abs(n / d - f) > 1e-6:
return '{0:.3f}'.format(f)
if d == 0:
return '0'
if f.denominator == 1:
return str(n)
return '{0}/{1}'.format(f.numerator, f.denominator)
def solvated(symbols):
"""Extract solvation energies from database.
symbols: str
Extract only those molecules that contain the chemical elements
given by the symbols string (plus water and H+).
Data from:
Johnson JW, Oelkers EH, Helgeson HC (1992)
Comput Geosci 18(7):899.
doi:10.1016/0098-3004(92)90029-Q
and:
Pourbaix M (1966)
Atlas of electrochemical equilibria in aqueous solutions.
No. v. 1 in Atlas of Electrochemical Equilibria in Aqueous Solutions.
Pergamon Press, New York.
Returns list of (name, energy) tuples.
"""
if isinstance(symbols, str):
symbols = set(string2symbols(symbols))
if len(_solvated) == 0:
for line in _aqueous.splitlines():
energy, formula = line.split(',')
name = formula + '(aq)'
count, charge, aq = parse_formula(name)
energy = float(energy) * 0.001 * units.kcal / units.mol
_solvated.append((name, count, charge, aq, energy))
references = []
for name, count, charge, aq, energy in _solvated:
for symbol in count:
if symbol not in 'HO' and symbol not in symbols:
break
else:
references.append((name, energy))
return references
def bisect(A, X, Y, f):
a = []
for i in [0, -1]:
for j in [0, -1]:
if A[i, j] == -1:
A[i, j] = f(X[i], Y[j])
a.append(A[i, j])
if np.ptp(a) == 0:
A[:] = a[0]
return
if a[0] == a[1]:
A[0] = a[0]
if a[1] == a[3]:
A[:, -1] = a[1]
if a[3] == a[2]:
A[-1] = a[3]
if a[2] == a[0]:
A[:, 0] = a[2]
if not (A == -1).any():
return
i = len(X) // 2
j = len(Y) // 2
bisect(A[:i + 1, :j + 1], X[:i + 1], Y[:j + 1], f)
bisect(A[:i + 1, j:], X[:i + 1], Y[j:], f)
bisect(A[i:, :j + 1], X[i:], Y[:j + 1], f)
bisect(A[i:, j:], X[i:], Y[j:], f)
def print_results(results):
total_energy = 0.0
print('reference coefficient energy')
print('------------------------------------')
for name, coef, energy in results:
total_energy += coef * energy
if abs(coef) < 1e-7:
continue
print('{0:14}{1:>10}{2:12.3f}'.format(name, float2str(coef), energy))
print('------------------------------------')
print('Total energy: {0:22.3f}'.format(total_energy))
print('------------------------------------')
class Pourbaix:
def __init__(self, references, formula=None, T=300.0, **kwargs):
"""Pourbaix object.
references: list of (name, energy) tuples
Examples of names: ZnO2, H+(aq), H2O(aq), Zn++(aq), ...
formula: str
Stoichiometry. Example: ``'ZnO'``. Can also be given as
keyword arguments: ``Pourbaix(refs, Zn=1, O=1)``.
T: float
Temperature in Kelvin.
"""
if formula:
assert not kwargs
kwargs = parse_formula(formula)[0]
self.kT = units.kB * T
self.references = []
for name, energy in references:
if name == 'O':
continue
count, charge, aq = parse_formula(name)
for symbol in count:
if aq:
if not (symbol in 'HO' or symbol in kwargs):
break
else:
if symbol not in kwargs:
break
else:
self.references.append((count, charge, aq, energy, name))
self.references.append(({}, -1, False, 0.0, 'e-')) # an electron
self.count = kwargs
if 'O' not in self.count:
self.count['O'] = 0
self.N = {'e-': 0, 'H': 1}
for symbol in kwargs:
if symbol not in self.N:
self.N[symbol] = len(self.N)
def decompose(self, U, pH, verbose=True, concentration=1e-6):
"""Decompose material.
U: float
Potential in eV.
pH: float
pH value.
verbose: bool
Default is True.
concentration: float
Concentration of solvated references.
Returns optimal coefficients and energy.
"""
alpha = np.log(10) * self.kT
entropy = -np.log(concentration) * self.kT
# We want to minimize np.dot(energies, x) under the constraints:
#
# np.dot(x, eq2) == eq1
#
# with bounds[i,0] <= x[i] <= bounds[i, 1].
#
# First two equations are charge and number of hydrogens, and
# the rest are the remaining species.
eq1 = [0, 0] + list(self.count.values())
eq2 = []
energies = []
bounds = []
names = []
for count, charge, aq, energy, name in self.references:
eq = np.zeros(len(self.N))
eq[0] = charge
for symbol, n in count.items():
eq[self.N[symbol]] = n
eq2.append(eq)
if name in ['H2O(aq)', 'H+(aq)', 'e-']:
bounds.append((-np.inf, np.inf))
if name == 'e-':
energy = -U
elif name == 'H+(aq)':
energy = -pH * alpha
else:
bounds.append((0, 1))
if aq:
energy -= entropy
if verbose:
print('{0:<5}{1:10}{2:10.3f}'.format(len(energies),
name, energy))
energies.append(energy)
names.append(name)
try:
from scipy.optimize import linprog
except ImportError:
from ase.utils._linprog import linprog
result = linprog(energies, None, None, np.transpose(eq2), eq1, bounds)
if verbose:
print_results(zip(names, result.x, energies))
return result.x, result.fun
def diagram(self, U, pH, plot=True, show=True):
"""Calculate Pourbaix diagram.
U: list of float
Potentials in eV.
pH: list of float
pH values.
plot: bool
Create plot.
show: bool
Show plot.
"""
a = np.empty((len(U), len(pH)), int)
a[:] = -1
colors = {}
f = functools.partial(self.colorfunction, colors=colors)
bisect(a, U, pH, f)
compositions = [None] * len(colors)
names = [ref[-1] for ref in self.references]
for indices, color in colors.items():
compositions[color] = ' + '.join(names[i] for i in indices
if names[i] not in
['H2O(aq)', 'H+(aq)', 'e-'])
text = []
for i, name in enumerate(compositions):
b = (a == i)
x = np.dot(b.sum(1), U) / b.sum()
y = np.dot(b.sum(0), pH) / b.sum()
name = re.sub('(\S)([+-]+)', r'\1$^{\2}$', name)
name = re.sub('(\d+)', r'$_{\1}$', name)
text.append((x, y, name))
if plot:
import matplotlib.pyplot as plt
import matplotlib.cm as cm
plt.pcolormesh(pH, U, a, cmap=cm.Accent)
for x, y, name in text:
plt.text(y, x, name, horizontalalignment='center')
plt.xlabel('pH')
plt.ylabel('potential [eV]')
plt.xlim(min(pH), max(pH))
plt.ylim(min(U), max(U))
if show:
plt.show()
return a, compositions, text
def colorfunction(self, U, pH, colors):
coefs, energy = self.decompose(U, pH, verbose=False)
indices = tuple(sorted(np.where(abs(coefs) > 1e-7)[0]))
color = colors.get(indices)
if color is None:
color = len(colors)
colors[indices] = color
return color
class PhaseDiagram:
def __init__(self, references, filter='', verbose=True):
"""Phase-diagram.
references: list of (name, energy) tuples
List of references. The names can also be dicts like
``{'Zn': 1, 'O': 2}`` which would be equivalent to ``'ZnO2'``.
filter: str or list of str
Use only those references that match the given filter.
Example: ``filter='ZnO'`` will select those that
contain zinc or oxygen.
verbose: bool
Write information.
"""
filter = parse_formula(filter)[0]
self.verbose = verbose
self.species = {}
self.references = []
for name, energy in references:
if isinstance(name, str):
count = parse_formula(name)[0]
else:
count = name
name = hill(count)
if filter and any(symbol not in filter for symbol in count):
continue
natoms = 0
for symbol, n in count.items():
natoms += n
if symbol not in self.species:
self.species[symbol] = len(self.species)
self.references.append((count, energy, name, natoms))
if verbose:
print('Species:', ', '.join(self.species))
print('References:', len(self.references))
for i, (count, energy, name, natoms) in enumerate(self.references):
print('{0:<5}{1:10}{2:10.3f}'.format(i, name, energy))
self.points = np.zeros((len(self.references), len(self.species) + 1))
for s, (count, energy, name, natoms) in enumerate(self.references):
for symbol, n in count.items():
self.points[s, self.species[symbol]] = n / natoms
self.points[s, -1] = energy / natoms
hull = ConvexHull(self.points[:, 1:])
# Find relevant vertices:
ok = hull.equations[:, -2] < 0
vertices = set()
for simplex in hull.simplices[ok]:
vertices.update(simplex)
self.vertices = np.array(list(vertices))
if verbose:
print('Simplices:', ok.sum())
# Create triangulation:
if len(self.species) == 2:
D = Delaunay1D # scipy's Delaunay doesn't like 1-d!
else:
D = Delaunay
self.tri = D(self.points[self.vertices, 1:-1])
def decompose(self, formula=None, **kwargs):
"""Find the combination of the references with the lowest energy.
formula: str
Stoichiometry. Example: ``'ZnO'``. Can also be given as
keyword arguments: ``decompose(Zn=1, O=1)``.
Example::
pd = PhaseDiagram(...)
pd.decompose(Zn=1, O=3)
Returns energy, indices of references and coefficients."""
if formula:
assert not kwargs
kwargs = parse_formula(formula)[0]
point = np.zeros(len(self.species))
natoms = 0
for symbol, n in kwargs.items():
point[self.species[symbol]] = n
natoms += n
i = self.tri.find_simplex(point[1:] / natoms)
indices = self.vertices[self.tri.simplices[i]]
points = self.points[indices]
scaledcoefs = np.linalg.solve(points[:, :-1].T, point)
energy = np.dot(scaledcoefs, points[:, -1])
coefs = []
results = []
for coef, s in zip(scaledcoefs, indices):
count, e, name, natoms = self.references[s]
coef /= natoms
coefs.append(coef)
results.append((name, coef, e))
if self.verbose:
print_results(results)
return energy, indices, np.array(coefs)
def plot(self):
"""Plot datapoints and convex hull.
Works only for 2 and 3 components systems.
"""
if len(self.species) == 2:
self.plot2d()
elif len(self.species) == 3:
self.plot3d()
else:
raise ValueError('...')
def plot2d(self):
import matplotlib.pyplot as plt
x, y = self.points[:, 1:].T
xsymbol = [symbol for symbol, id in self.species.items() if id == 1][0]
plt.plot(x, y, 'or')
for i, j in self.tri.simplices:
plt.plot([x[i], x[j]], [y[i], y[j]], '-g')
for count, energy, name, natoms in self.references:
name = re.sub('(\d+)', r'$_{\1}$', name)
plt.text(count.get(xsymbol, 0) / natoms, energy / natoms, name,
horizontalalignment='center', verticalalignment='bottom')
plt.xlabel(xsymbol)
plt.ylabel('energy')
plt.show()
class Delaunay1D:
"""Simple 1-d implementation."""
def __init__(self, points):
self.points = points[:, 0]
a = self.points.argsort()
self.simplices = np.array([a[:-1], a[1:]]).T
def find_simplex(self, point):
p = point[0]
for i, s in enumerate(self.simplices[:, 1]):
if p < self.points[s]:
return i
return i + 1
_aqueous = """\
-525700,SiF6--
-514100,Rh(SO4)3----
-504800,Ru(SO4)3----
-499900,Pd(SO4)3----
-495200,Ru(SO4)3---
-485700,H4P2O7
-483700,Rh(SO4)3---
-483600,H3P2O7-
-480400,H2P2O7--
-480380,Pt(SO4)3----
-471400,HP2O7---
-458700,P2O7----
-447500,LaF4-
-437600,LaH2PO4++
-377900,LaF3
-376299,Ca(HSiO3)+
-370691,BeF4--
-355400,BF4-
-353025,Mg(HSiO3)+
-346900,LaSO4+
-334100,Rh(SO4)2--
-325400,Ru(SO4)2--
-319640,Pd(SO4)2--
-317900,Ru(SO4)2-
-312970,Cr2O7--
-312930,CaSO4
-307890,NaHSiO3
-307800,LaF2+
-307000,LaHCO3++
-306100,Rh(SO4)2-
-302532,BeF3-
-300670,Pt(SO4)2--
-299900,LaCO3+
-289477,MgSO4
-288400,LaCl4-
-281500,HZrO3-
-279200,HHfO3-
-276720,Sr(HCO3)+
-275700,Ba(HCO3)+
-273830,Ca(HCO3)+
-273100,H3PO4
-270140,H2PO4-
-266500,S2O8--
-264860,Sr(CO3)
-264860,SrCO3
-263830,Ba(CO3)
-263830,BaCO3
-262850,Ca(CO3)
-262850,CaCO3
-260310,HPO4--
-257600,LaCl3
-250200,Mg(HCO3)+
-249200,H3VO4
-248700,S4O6--
-246640,KSO4-
-243990,H2VO4-
-243500,PO4---
-243400,KHSO4
-242801,HSiO3-
-241700,HYO2
-241476,NaSO4-
-239700,HZrO2+
-239300,LaO2H
-238760,Mg(CO3)
-238760,MgCO3
-237800,HHfO2+
-236890,Ag(CO3)2---
-236800,HNbO3
-236600,LaF++
-235640,MnSO4
-233400,ZrO2
-233000,HVO4--
-231600,HScO2
-231540,B(OH)3
-231400,HfO2
-231386,BeF2
-231000,S2O6--
-229000,S3O6--
-229000,S5O6--
-228460,HTiO3-
-227400,YO2-
-227100,NbO3-
-226700,LaCl2+
-223400,HWO4-
-221700,LaO2-
-218500,WO4--
-218100,ScO2-
-214900,VO4---
-210000,YOH++
-208900,LaOH++
-207700,HAlO2
-206400,HMoO4-
-204800,H3PO3
-202350,H2PO3-
-202290,SrF+
-201807,BaF+
-201120,BaF+
-200400,MoO4--
-200390,CaF+
-199190,SiO2
-198693,AlO2-
-198100,YO+
-195900,LaO+
-195800,LaCl++
-194000,CaCl2
-194000,HPO3--
-191300,LaNO3++
-190400,ZrOH+++
-189000,HfOH+++
-189000,S2O5--
-187600,ZrO++
-186000,HfO++
-183700,HCrO4-
-183600,ScO+
-183100,H3AsO4
-180630,HSO4-
-180010,H2AsO4-
-177930,SO4--
-177690,MgF+
-174800,CrO4--
-173300,SrOH+
-172300,BaOH+
-172200,HBeO2-
-171300,CaOH+
-170790,HAsO4--
-166000,ReO4-
-165800,SrCl+
-165475,Al(OH)++
-165475,AlOH++
-164730,BaCl+
-164000,La+++
-163800,Y+++
-163100,CaCl+
-162240,BO2-
-158493,BeF+
-158188,AlO+
-155700,VOOH+
-155164,CdF2
-154970,AsO4---
-153500,Rh(SO4)
-152900,BeO2--
-152370,HSO5-
-151540,RuCl6---
-149255,MgOH+
-147400,H2S2O4
-146900,HS2O4-
-146081,CdCl4--
-145521,BeCl2
-145200,Ru(SO4)
-145056,PbF2
-143500,S2O4--
-140330,H2AsO3-
-140300,VO2+
-140282,HCO3-
-140200,Sc+++
-139900,BeOH+
-139700,MgCl+
-139200,Ru(SO4)+
-139000,Pd(SO4)
-138160,HF2-
-138100,HCrO2
-138000,TiO++
-137300,HGaO2
-136450,RbF
-134760,Sr++
-134030,Ba++
-133270,Zr++++
-133177,PbCl4--
-132600,Hf++++
-132120,Ca++
-129310,ZnCl3-
-128700,GaO2-
-128600,BeO
-128570,NaF
-128000,H2S2O3
-127500,Rh(SO4)+
-127200,HS2O3-
-126191,CO3--
-126130,HSO3-
-125300,CrO2-
-125100,H3PO2
-124900,S2O3--
-123641,MnF+
-122400,H2PO2-
-121000,HMnO2-
-120700,RuCl5--
-120400,MnO4--
-120300,Pt(SO4)
-119800,HInO2
-116300,SO3--
-115971,CdCl3-
-115609,Al+++
-115316,BeCl+
-112280,AgCl4---
-111670,TiO2++
-111500,VOH++
-111430,Ag(CO3)-
-110720,HZnO2-
-108505,Mg++
-108100,HSeO4-
-108000,LiOH
-107600,MnO4-
-106988,HgCl4--
-106700,InO2-
-106700,VO++
-106100,VO+
-105500,SeO4--
-105100,RbOH
-105000,CsOH
-104500,KOH
-104109,ZnF+
-103900,PdCl4--
-103579,CuCl4--
-102600,MnO2--
-102150,PbCl3-
-101850,H2SeO3
-101100,HFeO2
-100900,CsCl
-100500,CrOH++
-99900,NaOH
-99800,VOH+
-99250,LiCl
-98340,HSeO3-
-98300,ZnCl2
-97870,RbCl
-97400,HSbO2
-97300,HSnO2-
-97300,MnOH+
-97016,InF++
-96240,HAsO2
-95430,KCl
-95400,HFeO2-
-94610,CsBr
-93290,ZnO2--
-93250,RhCl4--
-92910,NaCl
-92800,CrO+
-92250,CO2
-91210,PtCl4--
-91157,FeF+
-91100,GaOH++
-91010,RbBr
-90550,Be++
-90010,KBr
-89963,CuCl3--
-89730,RuCl4-
-88400,SeO3--
-88000,FeO2-
-87373,CdF+
-86600,GaO+
-86500,HCdO2-
-86290,MnCl+
-85610,NaBr
-84851,CdCl2
-83900,RuCl4--
-83650,AsO2-
-83600,Ti+++
-83460,CsI
-83400,HCoO2-
-82710,AgCl3--
-82400,SbO2-
-81980,HNiO2-
-81732,CoF+
-81500,MnO
-81190,ZnOH+
-81000,HPbO2-
-79768,NiF+
-79645,FeF++
-79300,HBiO2
-78900,RbI
-77740,KI
-77700,La++
-77500,RhCl4-
-75860,PbF+
-75338,CuCl3-
-75216,TlF
-75100,Ti++
-74600,InOH++
-74504,HgCl3-
-73480,FeCl2
-72900,NaI
-71980,SO2
-71662,HF
-71600,RuO4--
-71200,PbCl2
-69933,Li+
-69810,PdCl3-
-69710,Cs+
-69400,InO+
-67811,AuCl3--
-67800,Rb+
-67510,K+
-67420,ZnO
-67340,F-
-67300,CdO2--
-66850,ZnCl+
-65850,FeOH+
-65550,TlOH
-64200,NiO2--
-63530,RhCl3-
-63200,CoO2--
-62591,Na+
-61700,BiO2-
-61500,CdOH+
-60100,HCuO2-
-59226,InCl++
-58600,SnOH+
-58560,RuCl3
-58038,CuCl2-
-57900,V+++
-57800,FeOH++
-57760,PtCl3-
-57600,HTlO2
-56690,H2O
-56025,CoOH+
-55100,Mn++
-54380,RuCl3-
-53950,PbOH+
-53739,CuF+
-53600,SnO
-53100,FeO+
-53030,FeCl+
-52850,NiOH+
-52627,CdCl+
-52000,V++
-51560,AgCl2-
-50720,FeO
-49459,AgF
-49300,Cr+++
-47500,CdO
-46190,RhCl3
-46142,CuCl2
-45200,HHgO2-
-45157,CoCl+
-44000,CoO
-42838,HgCl2
-41600,TlO2-
-41200,CuO2--
-40920,NiCl+
-39815,TlCl
-39400,Cr++
-39350,PbO
-39340,NiO
-39050,PbCl+
-38000,Ga+++
-37518,FeCl++
-36781,AuCl2-
-35332,AuCl4-
-35200,Zn++
-35160,PdCl2
-33970,RhCl2
-32300,BiOH++
-31700,HIO3
-31379,Cl-
-30600,IO3-
-30410,HCl
-30204,HgF+
-30200,CuOH+
-29300,BiO+
-28682,CO
-26507,NO3-
-26440,RuCl2+
-25590,Br3-
-25060,RuCl2
-24870,Br-
-24730,HNO3
-23700,HIO
-23400,In+++
-23280,OCN-
-23000,CoOH++
-22608,CuCl
-22290,PtCl2
-21900,AgOH
-21870,Fe++
-20800,CuO
-20300,Mn+++
-20058,Pb(HS)2
-19700,HBrO
-19100,HClO
-19100,ScOH++
-18990,NH4+
-18971,Pb(HS)3-
-18560,Cd++
-18290,Rh(OH)+
-17450,AgCl
-16250,CuCl+
-14780,RhCl2+
-14000,IO4-
-13130,Pd(OH)+
-13000,Co++
-12700,HgOH+
-12410,I-
-12300,I3-
-12190,Ru(OH)++
-12100,HNO2
-11500,PdO
-10900,Ni++
-10470,Ru(OH)+
-10450,RuO+
-9200,IO-
-8900,HgO
-8800,ClO-
-8000,BrO-
-7740,Tl+
-7738,AgNO3
-7700,NO2-
-7220,RhO
-6673,H2S
-6570,Sn++
-6383,NH3
-5710,Pb++
-5500,AgO-
-4500,TlOH++
-4120,Fe+++
-3380,RhCl+
-3200,TlO+
-3184,AuCl
-2155,HgCl+
-2040,ClO4-
-1900,ClO3-
-1130,PtO
-820,Rh(OH)++
0,Ag(HS)2-
0,H+
230,RuO
1400,HClO2
1560,Pt(OH)+
2429,Au(HS)2-
2500,PdCl+
2860,HS-
3140,RhO+
3215,Xe
3554,Kr
3890,Ar
4100,ClO2-
4347,N2
4450,BrO3-
4565,Ne
4658,He
5210,RuCl+
7100,RuCl++
8600,H2N2O2
9375,TlCl++
10500,HSe-
11950,Cu+
15675,Cu++
15700,S5--
16500,S4--
17600,S3--
18200,HN2O2-
18330,RhCl++
18380,PtCl+
18427,Ag+
19000,S2--
19500,SeCN-
19700,N2H5+
21100,N2H6++
22160,SCN-
22880,Bi+++
27700,Rh++
28200,BrO4-
28600,HCN
32000,Co+++
33200,N2O2--
35900,Ru++
36710,Hg2++
39360,Hg++
41200,CN-
41440,Ru+++
42200,Pd++
51300,Tl+++
52450,Rh+++
61600,Pt++
64300,Ag++
103600,Au+++"""
| lgpl-3.0 |
wilebeast/FireFox-OS | B2G/gecko/media/webrtc/trunk/tools/gyp/test/win/gyptest-cl-buffer-security-check.py | 344 | 1612 | #!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Make sure buffer security check setting is extracted properly.
"""
import TestGyp
import sys
if sys.platform == 'win32':
test = TestGyp.TestGyp(formats=['msvs', 'ninja'])
CHDIR = 'compiler-flags'
test.run_gyp('buffer-security-check.gyp', chdir=CHDIR)
test.build('buffer-security-check.gyp', chdir=CHDIR)
def GetDisassemblyOfMain(exe):
# The standard library uses buffer security checks independent of our
# buffer security settings, so we extract just our code (i.e. main()) to
# check against.
full_path = test.built_file_path(exe, chdir=CHDIR)
output = test.run_dumpbin('/disasm', full_path)
result = []
in_main = False
for line in output.splitlines():
if line == '_main:':
in_main = True
elif in_main:
# Disassembly of next function starts.
if line.startswith('_'):
break
result.append(line)
return '\n'.join(result)
# Buffer security checks are on by default, make sure security_cookie
# appears in the disassembly of our code.
if 'security_cookie' not in GetDisassemblyOfMain('test_bsc_unset.exe'):
test.fail_test()
# Explicitly on.
if 'security_cookie' not in GetDisassemblyOfMain('test_bsc_on.exe'):
test.fail_test()
# Explicitly off, shouldn't be a reference to the security cookie.
if 'security_cookie' in GetDisassemblyOfMain('test_bsc_off.exe'):
test.fail_test()
test.pass_test()
| apache-2.0 |
utn-frm-si/reservas | app_reservas/models/imagenCarrusel.py | 2 | 1561 | # coding=utf-8
import os
from django.db import models
def establecer_destino_archivo_imagen(instance, filename):
"""
Establece la ruta de destino para el archivo de imagen cargado a la instancia.
"""
# Almacena el archivo en:
# 'app_reservas/carruseles/<carrusel>/<imagen>'
ruta_archivos_ubicacion = 'app_reservas/carruseles/{}/'.format(
instance.carrusel.slug,
)
return os.path.join(ruta_archivos_ubicacion, filename)
class ImagenCarrusel(models.Model):
# Atributos
orden = models.PositiveSmallIntegerField(
default=1,
verbose_name='Orden',
help_text='Orden de la imagen en el carrusel.',
)
imagen = models.ImageField(
upload_to=establecer_destino_archivo_imagen,
verbose_name='Imagen',
help_text='Archivo de imagen.',
)
# Relaciones
carrusel = models.ForeignKey(
'CarruselImagenes',
related_name='imagenes',
verbose_name='Carrusel',
)
class Meta:
"""
Información de la clase.
"""
app_label = 'app_reservas'
ordering = ['carrusel', 'orden']
verbose_name = 'Imagen de carrusel'
verbose_name_plural = 'Imágenes de carrusel'
def __str__(self):
"""
Representación de la instancia.
"""
return "Imagen {0:d} del carrusel '{1!s}'".format(
self.orden,
self.carrusel,
)
def get_url(self):
"""
Retorna la URL de la imagen.
"""
return self.imagen.url
| mit |
Netflix-Skunkworks/napalm-base | test/unit/validate/test_unit.py | 1 | 10802 | """Tests for the validate methods."""
import pytest
from napalm_base import validate
_compare_getter = [
(
{"list": ["\d{2}", 1, 2]},
[1, 2, 33],
{u'complies': True, u'extra': [], u'missing': [], u'present': ['\d{2}', 1, 2]}
),
(
{"list": [1, 2, 3]},
[1, 2, 3, 4, 5],
{u'complies': True, u'extra': [], u'missing': [], u'present': [1, 2, 3]}
),
(
{"list": [2, 1, 3]},
[3, 2, 1],
{u'complies': True, u'extra': [], u'missing': [], u'present': [2, 1, 3]}
),
(
{"list": [1, 2, {"list": [1, 2]}]},
[1, 2, [1, 2]],
# {u'complies': True, u'extra': [], u'missing': [], u'present': [1, 2, [1, 2]]}
{u'complies': True,
u'extra': [],
u'missing': [],
u'present': [1, 2, {'list': [1, 2]}]}
),
(
{"list": ['\d{2}', 4, 3]},
[1, 2, 3],
{u'complies': False, u'extra': [], u'missing': ['\d{2}', 4], u'present': [3]}
),
(
{"list": [{"list": [1, 2]}, 3]},
[1, 2, 3],
{u'complies': False,
u'extra': [],
u'missing': [{'list': [1, 2]}],
u'present': [3]}
),
(
{"_mode": "strict", "list": [1, 2, 3]},
[1, 2, 3],
{u'complies': True, u'extra': [], u'missing': [], u'present': [1, 2, 3]}
),
(
{"_mode": "strict", "list": [1, 2, 3]},
[1, 2, 3, 4, 5],
{u'complies': False, u'extra': [4, 5], u'missing': [], u'present': [1, 2, 3]}
),
(
{"_mode": "strict", "list": [2, 1, 3]},
[3, 2, 1],
{u'complies': True, u'extra': [], u'missing': [], u'present': [2, 1, 3]}
),
(
{"_mode": "strict", "list": [1, 2, {"_mode": "strict", "list": [1, 2]}]},
[1, 2, [1, 2]],
# {u'complies': True, u'extra': [], u'missing': [], u'present': [1, 2, [1, 2]]}
{u'complies': True,
u'extra': [],
u'missing': [],
u'present': [1, 2, {'list': [1, 2]}]}
),
(
{"_mode": "strict", "list": [4, 3]},
[1, 2, 3],
{u'complies': False, u'extra': [1, 2], u'missing': [4], u'present': [3]}
),
(
{"_mode": "strict", "list": [{"_mode": "strict", "list": [1, 2]}, 3]},
[1, 2, 3],
{u'complies': False,
u'extra': [1, 2],
u'missing': [{'list': [1, 2]}],
u'present': [3]}
),
(
{'a': 1, 'b': 2, 'c': 3},
{'a': 1, 'b': 2, 'c': 3},
{u'complies': True,
u'extra': [],
u'missing': [],
u'present': {'a': {u'complies': True, u'nested': False},
'b': {u'complies': True, u'nested': False},
'c': {u'complies': True, u'nested': False}}}
),
(
{'a': 1, 'b': 2, 'c': 3},
{'a': 2, 'b': 2, 'c': 3},
{u'complies': False,
u'extra': [],
u'missing': [],
u'present': {'a': {u'actual_value': 2, u'complies': False, u'nested': False},
'b': {u'complies': True, u'nested': False},
'c': {u'complies': True, u'nested': False}}}
),
(
{'a': 1, 'b': 2, 'c': 3},
{'b': 1, 'c': 3},
{u'complies': False,
u'extra': [],
u'missing': ['a'],
u'present': {'b': {u'actual_value': 1, u'complies': False, u'nested': False},
'c': {u'complies': True, u'nested': False}}}
),
(
{'a': 1, 'b': 2, 'c': {"A": 1, "B": 2}},
{'a': 1, 'b': 2, 'c': {"A": 1, "B": 2}},
{u'complies': True,
u'extra': [],
u'missing': [],
u'present': {'a': {u'complies': True, u'nested': False},
'b': {u'complies': True, u'nested': False},
'c': {u'complies': True, u'nested': True}}}
),
(
{'a': 1, 'b': 2, 'c': {"A": 1, "B": 2}},
{'a': 1, 'b': 2, 'd': {"A": 1, "B": 2}},
{u'complies': False,
u'extra': [],
u'missing': ['c'],
u'present': {'a': {u'complies': True, u'nested': False},
'b': {u'complies': True, u'nested': False}}}
),
(
{'a': 1, 'b': 2, 'c': {"A": 3, "B": 2}},
{'a': 1, 'b': 2, 'c': {"A": 1, "B": 2}},
{u'complies': False,
u'extra': [],
u'missing': [],
u'present': {'a': {u'complies': True, u'nested': False},
'b': {u'complies': True, u'nested': False},
'c': {u'complies': False,
u'diff': {u'complies': False,
u'extra': [],
u'missing': [],
u'present': {'A': {u'actual_value': 1,
u'complies': False,
u'nested': False},
'B': {u'complies': True,
u'nested': False}}},
u'nested': True}}}
),
(
{'a': 1, 'b': 2, 'c': {"A": 3, "B": 2}},
{'a': 1, 'b': 2, 'c': {"A": 1}},
{u'complies': False,
u'extra': [],
u'missing': [],
u'present': {'a': {u'complies': True, u'nested': False},
'b': {u'complies': True, u'nested': False},
'c': {u'complies': False,
u'diff': {u'complies': False,
u'extra': [],
u'missing': ['B'],
u'present': {'A': {u'actual_value': 1,
u'complies': False,
u'nested': False}}},
u'nested': True}}}
),
(
{"_mode": "strict", 'a': 1, 'b': 2, 'c': 3},
{'a': 1, 'b': 2, 'c': 3},
{u'complies': True,
u'extra': [],
u'missing': [],
u'present': {'a': {u'complies': True, u'nested': False},
'b': {u'complies': True, u'nested': False},
'c': {u'complies': True, u'nested': False}}}
),
(
{"_mode": "strict", 'a': 1, 'b': 2, 'c': 3},
{'a': 2, 'b': 2, 'c': 3},
{u'complies': False,
u'extra': [],
u'missing': [],
u'present': {'a': {u'actual_value': 2, u'complies': False, u'nested': False},
'b': {u'complies': True, u'nested': False},
'c': {u'complies': True, u'nested': False}}}
),
(
{"_mode": "strict", 'a': 1, 'b': 2, 'c': 3},
{'b': 1, 'c': 3},
{u'complies': False,
u'extra': [],
u'missing': ['a'],
u'present': {'b': {u'actual_value': 1, u'complies': False, u'nested': False},
'c': {u'complies': True, u'nested': False}}}
),
(
{"_mode": "strict", 'a': 1, 'b': 2, 'c': {"_mode": "strict", "A": 1, "B": 2}},
{'a': 1, 'b': 2, 'c': {"A": 1, "B": 2}},
{u'complies': True,
u'extra': [],
u'missing': [],
u'present': {'a': {u'complies': True, u'nested': False},
'b': {u'complies': True, u'nested': False},
'c': {u'complies': True, u'nested': True}}}
),
(
{"_mode": "strict", 'a': 1, 'b': 2, 'c': {"_mode": "strict", "A": 1, "B": 2}},
{'a': 1, 'b': 2, 'd': {"A": 1, "B": 2}},
{u'complies': False,
u'extra': ['d'],
u'missing': ['c'],
u'present': {'a': {u'complies': True, u'nested': False},
'b': {u'complies': True, u'nested': False}}}
),
(
{"_mode": "strict", 'a': 1, 'b': 2, 'c': {"_mode": "strict", "A": 3, "B": 2}},
{'a': 1, 'b': 2, 'c': {"A": 1, "B": 2}},
{u'complies': False,
u'extra': [],
u'missing': [],
u'present': {'a': {u'complies': True, u'nested': False},
'b': {u'complies': True, u'nested': False},
'c': {u'complies': False,
u'diff': {u'complies': False,
u'extra': [],
u'missing': [],
u'present': {'A': {u'actual_value': 1,
u'complies': False,
u'nested': False},
'B': {u'complies': True,
u'nested': False}}},
u'nested': True}}}
),
(
{"_mode": "strict", 'a': 1, 'b': 2, 'c': {"_mode": "strict", "A": 3, "B": 2}},
{'a': 1, 'b': 2, 'c': {"A": 1, "C": 4}},
{u'complies': False,
u'extra': [],
u'missing': [],
u'present': {'a': {u'complies': True, u'nested': False},
'b': {u'complies': True, u'nested': False},
'c': {u'complies': False,
u'diff': {u'complies': False,
u'extra': ['C'],
u'missing': ['B'],
u'present': {'A': {u'actual_value': 1,
u'complies': False,
u'nested': False}}},
u'nested': True}}}
),
(
{"_mode": "strict", 'a': 1, 'b': 2, 'c': {"_mode": "strict", "A": 3, "B": 2}},
{'a': 1, 'b': 2, 'c': {"A": 1, "C": 4}},
{u'complies': False,
u'extra': [],
u'missing': [],
u'present': {'a': {u'complies': True, u'nested': False},
'b': {u'complies': True, u'nested': False},
'c': {u'complies': False,
u'diff': {u'complies': False,
u'extra': ['C'],
u'missing': ['B'],
u'present': {'A': {u'actual_value': 1,
u'complies': False,
u'nested': False}}},
u'nested': True}}}
),
]
class TestValidate:
"""Wraps tests."""
@pytest.mark.parametrize('src, dst, result', _compare_getter)
def test__compare_getter_list(self, src, dst, result):
"""Test for _compare_getter_list."""
assert validate._compare_getter(src, dst) == result
| apache-2.0 |
AccelAI/accel.ai | flask-aws/lib/python2.7/site-packages/boto/sdb/db/property.py | 17 | 24935 | # Copyright (c) 2006,2007,2008 Mitch Garnaat http://garnaat.org/
#
# 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 rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import datetime
from key import Key
from boto.utils import Password
from boto.sdb.db.query import Query
import re
import boto
import boto.s3.key
from boto.sdb.db.blob import Blob
class Property(object):
data_type = str
type_name = ''
name = ''
verbose_name = ''
def __init__(self, verbose_name=None, name=None, default=None,
required=False, validator=None, choices=None, unique=False):
self.verbose_name = verbose_name
self.name = name
self.default = default
self.required = required
self.validator = validator
self.choices = choices
if self.name:
self.slot_name = '_' + self.name
else:
self.slot_name = '_'
self.unique = unique
def __get__(self, obj, objtype):
if obj:
obj.load()
return getattr(obj, self.slot_name)
else:
return None
def __set__(self, obj, value):
self.validate(value)
# Fire off any on_set functions
try:
if obj._loaded and hasattr(obj, "on_set_%s" % self.name):
fnc = getattr(obj, "on_set_%s" % self.name)
value = fnc(value)
except Exception:
boto.log.exception("Exception running on_set_%s" % self.name)
setattr(obj, self.slot_name, value)
def __property_config__(self, model_class, property_name):
self.model_class = model_class
self.name = property_name
self.slot_name = '_' + self.name
def default_validator(self, value):
if isinstance(value, basestring) or value == self.default_value():
return
if not isinstance(value, self.data_type):
raise TypeError('Validation Error, %s.%s expecting %s, got %s' % (self.model_class.__name__, self.name, self.data_type, type(value)))
def default_value(self):
return self.default
def validate(self, value):
if self.required and value is None:
raise ValueError('%s is a required property' % self.name)
if self.choices and value and not value in self.choices:
raise ValueError('%s not a valid choice for %s.%s' % (value, self.model_class.__name__, self.name))
if self.validator:
self.validator(value)
else:
self.default_validator(value)
return value
def empty(self, value):
return not value
def get_value_for_datastore(self, model_instance):
return getattr(model_instance, self.name)
def make_value_from_datastore(self, value):
return value
def get_choices(self):
if callable(self.choices):
return self.choices()
return self.choices
def validate_string(value):
if value is None:
return
elif isinstance(value, basestring):
if len(value) > 1024:
raise ValueError('Length of value greater than maxlength')
else:
raise TypeError('Expecting String, got %s' % type(value))
class StringProperty(Property):
type_name = 'String'
def __init__(self, verbose_name=None, name=None, default='',
required=False, validator=validate_string,
choices=None, unique=False):
super(StringProperty, self).__init__(verbose_name, name, default, required,
validator, choices, unique)
class TextProperty(Property):
type_name = 'Text'
def __init__(self, verbose_name=None, name=None, default='',
required=False, validator=None, choices=None,
unique=False, max_length=None):
super(TextProperty, self).__init__(verbose_name, name, default, required,
validator, choices, unique)
self.max_length = max_length
def validate(self, value):
value = super(TextProperty, self).validate(value)
if not isinstance(value, basestring):
raise TypeError('Expecting Text, got %s' % type(value))
if self.max_length and len(value) > self.max_length:
raise ValueError('Length of value greater than maxlength %s' % self.max_length)
class PasswordProperty(StringProperty):
"""
Hashed property whose original value can not be
retrieved, but still can be compared.
Works by storing a hash of the original value instead
of the original value. Once that's done all that
can be retrieved is the hash.
The comparison
obj.password == 'foo'
generates a hash of 'foo' and compares it to the
stored hash.
Underlying data type for hashing, storing, and comparing
is boto.utils.Password. The default hash function is
defined there ( currently sha512 in most cases, md5
where sha512 is not available )
It's unlikely you'll ever need to use a different hash
function, but if you do, you can control the behavior
in one of two ways:
1) Specifying hashfunc in PasswordProperty constructor
import hashlib
class MyModel(model):
password = PasswordProperty(hashfunc=hashlib.sha224)
2) Subclassing Password and PasswordProperty
class SHA224Password(Password):
hashfunc=hashlib.sha224
class SHA224PasswordProperty(PasswordProperty):
data_type=MyPassword
type_name="MyPassword"
class MyModel(Model):
password = SHA224PasswordProperty()
"""
data_type = Password
type_name = 'Password'
def __init__(self, verbose_name=None, name=None, default='', required=False,
validator=None, choices=None, unique=False, hashfunc=None):
"""
The hashfunc parameter overrides the default hashfunc in boto.utils.Password.
The remaining parameters are passed through to StringProperty.__init__"""
super(PasswordProperty, self).__init__(verbose_name, name, default, required,
validator, choices, unique)
self.hashfunc = hashfunc
def make_value_from_datastore(self, value):
p = self.data_type(value, hashfunc=self.hashfunc)
return p
def get_value_for_datastore(self, model_instance):
value = super(PasswordProperty, self).get_value_for_datastore(model_instance)
if value and len(value):
return str(value)
else:
return None
def __set__(self, obj, value):
if not isinstance(value, self.data_type):
p = self.data_type(hashfunc=self.hashfunc)
p.set(value)
value = p
super(PasswordProperty, self).__set__(obj, value)
def __get__(self, obj, objtype):
return self.data_type(super(PasswordProperty, self).__get__(obj, objtype), hashfunc=self.hashfunc)
def validate(self, value):
value = super(PasswordProperty, self).validate(value)
if isinstance(value, self.data_type):
if len(value) > 1024:
raise ValueError('Length of value greater than maxlength')
else:
raise TypeError('Expecting %s, got %s' % (type(self.data_type), type(value)))
class BlobProperty(Property):
data_type = Blob
type_name = "blob"
def __set__(self, obj, value):
if value != self.default_value():
if not isinstance(value, Blob):
oldb = self.__get__(obj, type(obj))
id = None
if oldb:
id = oldb.id
b = Blob(value=value, id=id)
value = b
super(BlobProperty, self).__set__(obj, value)
class S3KeyProperty(Property):
data_type = boto.s3.key.Key
type_name = 'S3Key'
validate_regex = "^s3:\/\/([^\/]*)\/(.*)$"
def __init__(self, verbose_name=None, name=None, default=None,
required=False, validator=None, choices=None, unique=False):
super(S3KeyProperty, self).__init__(verbose_name, name, default, required,
validator, choices, unique)
def validate(self, value):
value = super(S3KeyProperty, self).validate(value)
if value == self.default_value() or value == str(self.default_value()):
return self.default_value()
if isinstance(value, self.data_type):
return
match = re.match(self.validate_regex, value)
if match:
return
raise TypeError('Validation Error, expecting %s, got %s' % (self.data_type, type(value)))
def __get__(self, obj, objtype):
value = super(S3KeyProperty, self).__get__(obj, objtype)
if value:
if isinstance(value, self.data_type):
return value
match = re.match(self.validate_regex, value)
if match:
s3 = obj._manager.get_s3_connection()
bucket = s3.get_bucket(match.group(1), validate=False)
k = bucket.get_key(match.group(2))
if not k:
k = bucket.new_key(match.group(2))
k.set_contents_from_string("")
return k
else:
return value
def get_value_for_datastore(self, model_instance):
value = super(S3KeyProperty, self).get_value_for_datastore(model_instance)
if value:
return "s3://%s/%s" % (value.bucket.name, value.name)
else:
return None
class IntegerProperty(Property):
data_type = int
type_name = 'Integer'
def __init__(self, verbose_name=None, name=None, default=0, required=False,
validator=None, choices=None, unique=False, max=2147483647, min=-2147483648):
super(IntegerProperty, self).__init__(verbose_name, name, default, required, validator, choices, unique)
self.max = max
self.min = min
def validate(self, value):
value = int(value)
value = super(IntegerProperty, self).validate(value)
if value > self.max:
raise ValueError('Maximum value is %d' % self.max)
if value < self.min:
raise ValueError('Minimum value is %d' % self.min)
return value
def empty(self, value):
return value is None
def __set__(self, obj, value):
if value == "" or value is None:
value = 0
return super(IntegerProperty, self).__set__(obj, value)
class LongProperty(Property):
data_type = long
type_name = 'Long'
def __init__(self, verbose_name=None, name=None, default=0, required=False,
validator=None, choices=None, unique=False):
super(LongProperty, self).__init__(verbose_name, name, default, required, validator, choices, unique)
def validate(self, value):
value = long(value)
value = super(LongProperty, self).validate(value)
min = -9223372036854775808
max = 9223372036854775807
if value > max:
raise ValueError('Maximum value is %d' % max)
if value < min:
raise ValueError('Minimum value is %d' % min)
return value
def empty(self, value):
return value is None
class BooleanProperty(Property):
data_type = bool
type_name = 'Boolean'
def __init__(self, verbose_name=None, name=None, default=False, required=False,
validator=None, choices=None, unique=False):
super(BooleanProperty, self).__init__(verbose_name, name, default, required, validator, choices, unique)
def empty(self, value):
return value is None
class FloatProperty(Property):
data_type = float
type_name = 'Float'
def __init__(self, verbose_name=None, name=None, default=0.0, required=False,
validator=None, choices=None, unique=False):
super(FloatProperty, self).__init__(verbose_name, name, default, required, validator, choices, unique)
def validate(self, value):
value = float(value)
value = super(FloatProperty, self).validate(value)
return value
def empty(self, value):
return value is None
class DateTimeProperty(Property):
"""This class handles both the datetime.datetime object
And the datetime.date objects. It can return either one,
depending on the value stored in the database"""
data_type = datetime.datetime
type_name = 'DateTime'
def __init__(self, verbose_name=None, auto_now=False, auto_now_add=False, name=None,
default=None, required=False, validator=None, choices=None, unique=False):
super(DateTimeProperty, self).__init__(verbose_name, name, default, required, validator, choices, unique)
self.auto_now = auto_now
self.auto_now_add = auto_now_add
def default_value(self):
if self.auto_now or self.auto_now_add:
return self.now()
return super(DateTimeProperty, self).default_value()
def validate(self, value):
if value is None:
return
if isinstance(value, datetime.date):
return value
return super(DateTimeProperty, self).validate(value)
def get_value_for_datastore(self, model_instance):
if self.auto_now:
setattr(model_instance, self.name, self.now())
return super(DateTimeProperty, self).get_value_for_datastore(model_instance)
def now(self):
return datetime.datetime.utcnow()
class DateProperty(Property):
data_type = datetime.date
type_name = 'Date'
def __init__(self, verbose_name=None, auto_now=False, auto_now_add=False, name=None,
default=None, required=False, validator=None, choices=None, unique=False):
super(DateProperty, self).__init__(verbose_name, name, default, required, validator, choices, unique)
self.auto_now = auto_now
self.auto_now_add = auto_now_add
def default_value(self):
if self.auto_now or self.auto_now_add:
return self.now()
return super(DateProperty, self).default_value()
def validate(self, value):
value = super(DateProperty, self).validate(value)
if value is None:
return
if not isinstance(value, self.data_type):
raise TypeError('Validation Error, expecting %s, got %s' % (self.data_type, type(value)))
def get_value_for_datastore(self, model_instance):
if self.auto_now:
setattr(model_instance, self.name, self.now())
val = super(DateProperty, self).get_value_for_datastore(model_instance)
if isinstance(val, datetime.datetime):
val = val.date()
return val
def now(self):
return datetime.date.today()
class TimeProperty(Property):
data_type = datetime.time
type_name = 'Time'
def __init__(self, verbose_name=None, name=None,
default=None, required=False, validator=None, choices=None, unique=False):
super(TimeProperty, self).__init__(verbose_name, name, default, required, validator, choices, unique)
def validate(self, value):
value = super(TimeProperty, self).validate(value)
if value is None:
return
if not isinstance(value, self.data_type):
raise TypeError('Validation Error, expecting %s, got %s' % (self.data_type, type(value)))
class ReferenceProperty(Property):
data_type = Key
type_name = 'Reference'
def __init__(self, reference_class=None, collection_name=None,
verbose_name=None, name=None, default=None, required=False, validator=None, choices=None, unique=False):
super(ReferenceProperty, self).__init__(verbose_name, name, default, required, validator, choices, unique)
self.reference_class = reference_class
self.collection_name = collection_name
def __get__(self, obj, objtype):
if obj:
value = getattr(obj, self.slot_name)
if value == self.default_value():
return value
# If the value is still the UUID for the referenced object, we need to create
# the object now that is the attribute has actually been accessed. This lazy
# instantiation saves unnecessary roundtrips to SimpleDB
if isinstance(value, basestring):
value = self.reference_class(value)
setattr(obj, self.name, value)
return value
def __set__(self, obj, value):
"""Don't allow this object to be associated to itself
This causes bad things to happen"""
if value is not None and (obj.id == value or (hasattr(value, "id") and obj.id == value.id)):
raise ValueError("Can not associate an object with itself!")
return super(ReferenceProperty, self).__set__(obj, value)
def __property_config__(self, model_class, property_name):
super(ReferenceProperty, self).__property_config__(model_class, property_name)
if self.collection_name is None:
self.collection_name = '%s_%s_set' % (model_class.__name__.lower(), self.name)
if hasattr(self.reference_class, self.collection_name):
raise ValueError('duplicate property: %s' % self.collection_name)
setattr(self.reference_class, self.collection_name,
_ReverseReferenceProperty(model_class, property_name, self.collection_name))
def check_uuid(self, value):
# This does a bit of hand waving to "type check" the string
t = value.split('-')
if len(t) != 5:
raise ValueError
def check_instance(self, value):
try:
obj_lineage = value.get_lineage()
cls_lineage = self.reference_class.get_lineage()
if obj_lineage.startswith(cls_lineage):
return
raise TypeError('%s not instance of %s' % (obj_lineage, cls_lineage))
except:
raise ValueError('%s is not a Model' % value)
def validate(self, value):
if self.validator:
self.validator(value)
if self.required and value is None:
raise ValueError('%s is a required property' % self.name)
if value == self.default_value():
return
if not isinstance(value, basestring):
self.check_instance(value)
class _ReverseReferenceProperty(Property):
data_type = Query
type_name = 'query'
def __init__(self, model, prop, name):
self.__model = model
self.__property = prop
self.collection_name = prop
self.name = name
self.item_type = model
def __get__(self, model_instance, model_class):
"""Fetches collection of model instances of this collection property."""
if model_instance is not None:
query = Query(self.__model)
if isinstance(self.__property, list):
props = []
for prop in self.__property:
props.append("%s =" % prop)
return query.filter(props, model_instance)
else:
return query.filter(self.__property + ' =', model_instance)
else:
return self
def __set__(self, model_instance, value):
"""Not possible to set a new collection."""
raise ValueError('Virtual property is read-only')
class CalculatedProperty(Property):
def __init__(self, verbose_name=None, name=None, default=None,
required=False, validator=None, choices=None,
calculated_type=int, unique=False, use_method=False):
super(CalculatedProperty, self).__init__(verbose_name, name, default, required,
validator, choices, unique)
self.calculated_type = calculated_type
self.use_method = use_method
def __get__(self, obj, objtype):
value = self.default_value()
if obj:
try:
value = getattr(obj, self.slot_name)
if self.use_method:
value = value()
except AttributeError:
pass
return value
def __set__(self, obj, value):
"""Not possible to set a new AutoID."""
pass
def _set_direct(self, obj, value):
if not self.use_method:
setattr(obj, self.slot_name, value)
def get_value_for_datastore(self, model_instance):
if self.calculated_type in [str, int, bool]:
value = self.__get__(model_instance, model_instance.__class__)
return value
else:
return None
class ListProperty(Property):
data_type = list
type_name = 'List'
def __init__(self, item_type, verbose_name=None, name=None, default=None, **kwds):
if default is None:
default = []
self.item_type = item_type
super(ListProperty, self).__init__(verbose_name, name, default=default, required=True, **kwds)
def validate(self, value):
if self.validator:
self.validator(value)
if value is not None:
if not isinstance(value, list):
value = [value]
if self.item_type in (int, long):
item_type = (int, long)
elif self.item_type in (str, unicode):
item_type = (str, unicode)
else:
item_type = self.item_type
for item in value:
if not isinstance(item, item_type):
if item_type == (int, long):
raise ValueError('Items in the %s list must all be integers.' % self.name)
else:
raise ValueError('Items in the %s list must all be %s instances' %
(self.name, self.item_type.__name__))
return value
def empty(self, value):
return value is None
def default_value(self):
return list(super(ListProperty, self).default_value())
def __set__(self, obj, value):
"""Override the set method to allow them to set the property to an instance of the item_type instead of requiring a list to be passed in"""
if self.item_type in (int, long):
item_type = (int, long)
elif self.item_type in (str, unicode):
item_type = (str, unicode)
else:
item_type = self.item_type
if isinstance(value, item_type):
value = [value]
elif value is None: # Override to allow them to set this to "None" to remove everything
value = []
return super(ListProperty, self).__set__(obj, value)
class MapProperty(Property):
data_type = dict
type_name = 'Map'
def __init__(self, item_type=str, verbose_name=None, name=None, default=None, **kwds):
if default is None:
default = {}
self.item_type = item_type
super(MapProperty, self).__init__(verbose_name, name, default=default, required=True, **kwds)
def validate(self, value):
value = super(MapProperty, self).validate(value)
if value is not None:
if not isinstance(value, dict):
raise ValueError('Value must of type dict')
if self.item_type in (int, long):
item_type = (int, long)
elif self.item_type in (str, unicode):
item_type = (str, unicode)
else:
item_type = self.item_type
for key in value:
if not isinstance(value[key], item_type):
if item_type == (int, long):
raise ValueError('Values in the %s Map must all be integers.' % self.name)
else:
raise ValueError('Values in the %s Map must all be %s instances' %
(self.name, self.item_type.__name__))
return value
def empty(self, value):
return value is None
def default_value(self):
return {}
| mit |
ShassAro/ShassAro | DockerAdmin/dockerVirtualEnv/lib/python2.7/site-packages/django/db/backends/utils.py | 52 | 6379 | from __future__ import unicode_literals
import datetime
import decimal
import hashlib
import logging
from time import time
from django.conf import settings
from django.utils.encoding import force_bytes
from django.utils.timezone import utc
logger = logging.getLogger('django.db.backends')
class CursorWrapper(object):
def __init__(self, cursor, db):
self.cursor = cursor
self.db = db
WRAP_ERROR_ATTRS = frozenset(['fetchone', 'fetchmany', 'fetchall', 'nextset'])
def __getattr__(self, attr):
cursor_attr = getattr(self.cursor, attr)
if attr in CursorWrapper.WRAP_ERROR_ATTRS:
return self.db.wrap_database_errors(cursor_attr)
else:
return cursor_attr
def __iter__(self):
return iter(self.cursor)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
# Ticket #17671 - Close instead of passing thru to avoid backend
# specific behavior. Catch errors liberally because errors in cleanup
# code aren't useful.
try:
self.close()
except self.db.Database.Error:
pass
# The following methods cannot be implemented in __getattr__, because the
# code must run when the method is invoked, not just when it is accessed.
def callproc(self, procname, params=None):
self.db.validate_no_broken_transaction()
self.db.set_dirty()
with self.db.wrap_database_errors:
if params is None:
return self.cursor.callproc(procname)
else:
return self.cursor.callproc(procname, params)
def execute(self, sql, params=None):
self.db.validate_no_broken_transaction()
self.db.set_dirty()
with self.db.wrap_database_errors:
if params is None:
return self.cursor.execute(sql)
else:
return self.cursor.execute(sql, params)
def executemany(self, sql, param_list):
self.db.validate_no_broken_transaction()
self.db.set_dirty()
with self.db.wrap_database_errors:
return self.cursor.executemany(sql, param_list)
class CursorDebugWrapper(CursorWrapper):
# XXX callproc isn't instrumented at this time.
def execute(self, sql, params=None):
start = time()
try:
return super(CursorDebugWrapper, self).execute(sql, params)
finally:
stop = time()
duration = stop - start
sql = self.db.ops.last_executed_query(self.cursor, sql, params)
self.db.queries.append({
'sql': sql,
'time': "%.3f" % duration,
})
logger.debug('(%.3f) %s; args=%s' % (duration, sql, params),
extra={'duration': duration, 'sql': sql, 'params': params}
)
def executemany(self, sql, param_list):
start = time()
try:
return super(CursorDebugWrapper, self).executemany(sql, param_list)
finally:
stop = time()
duration = stop - start
try:
times = len(param_list)
except TypeError: # param_list could be an iterator
times = '?'
self.db.queries.append({
'sql': '%s times: %s' % (times, sql),
'time': "%.3f" % duration,
})
logger.debug('(%.3f) %s; args=%s' % (duration, sql, param_list),
extra={'duration': duration, 'sql': sql, 'params': param_list}
)
###############################################
# Converters from database (string) to Python #
###############################################
def typecast_date(s):
return datetime.date(*map(int, s.split('-'))) if s else None # returns None if s is null
def typecast_time(s): # does NOT store time zone information
if not s:
return None
hour, minutes, seconds = s.split(':')
if '.' in seconds: # check whether seconds have a fractional part
seconds, microseconds = seconds.split('.')
else:
microseconds = '0'
return datetime.time(int(hour), int(minutes), int(seconds), int(float('.' + microseconds) * 1000000))
def typecast_timestamp(s): # does NOT store time zone information
# "2005-07-29 15:48:00.590358-05"
# "2005-07-29 09:56:00-05"
if not s:
return None
if ' ' not in s:
return typecast_date(s)
d, t = s.split()
# Extract timezone information, if it exists. Currently we just throw
# it away, but in the future we may make use of it.
if '-' in t:
t, tz = t.split('-', 1)
tz = '-' + tz
elif '+' in t:
t, tz = t.split('+', 1)
tz = '+' + tz
else:
tz = ''
dates = d.split('-')
times = t.split(':')
seconds = times[2]
if '.' in seconds: # check whether seconds have a fractional part
seconds, microseconds = seconds.split('.')
else:
microseconds = '0'
tzinfo = utc if settings.USE_TZ else None
return datetime.datetime(int(dates[0]), int(dates[1]), int(dates[2]),
int(times[0]), int(times[1]), int(seconds),
int((microseconds + '000000')[:6]), tzinfo)
def typecast_decimal(s):
if s is None or s == '':
return None
return decimal.Decimal(s)
###############################################
# Converters from Python to database (string) #
###############################################
def rev_typecast_decimal(d):
if d is None:
return None
return str(d)
def truncate_name(name, length=None, hash_len=4):
"""Shortens a string to a repeatable mangled version with the given length.
"""
if length is None or len(name) <= length:
return name
hsh = hashlib.md5(force_bytes(name)).hexdigest()[:hash_len]
return '%s%s' % (name[:length - hash_len], hsh)
def format_number(value, max_digits, decimal_places):
"""
Formats a number into a string with the requisite number of digits and
decimal places.
"""
if isinstance(value, decimal.Decimal):
context = decimal.getcontext().copy()
context.prec = max_digits
return "{0:f}".format(value.quantize(decimal.Decimal(".1") ** decimal_places, context=context))
else:
return "%.*f" % (decimal_places, value)
| gpl-2.0 |
TeamEOS/external_skia | tools/find_bad_images_in_skps.py | 172 | 7405 | #!/usr/bin/env python
# Copyright 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
This script will take as an argument either a list of skp files or a
set of directories that contains skp files. It will then test each
skp file with the `render_pictures` program. If that program either
spits out any unexpected output or doesn't return 0, I will flag that
skp file as problematic. We then extract all of the embedded images
inside the skp and test each one of them against the
SkImageDecoder::DecodeFile function. Again, we consider any
extraneous output or a bad return value an error. In the event of an
error, we retain the image and print out information about the error.
The output (on stdout) is formatted as a csv document.
A copy of each bad image is left in a directory created by
tempfile.mkdtemp().
"""
import glob
import os
import re
import shutil
import subprocess
import sys
import tempfile
import threading
import test_rendering # skia/trunk/tools. reuse FindPathToProgram()
USAGE = """
Usage:
{command} SKP_FILE [SKP_FILES]
{command} SKP_DIR [SKP_DIRS]\n
Environment variables:
To run multiple worker threads, set NUM_THREADS.
To use a different temporary storage location, set TMPDIR.
"""
def execute_program(args, ignores=None):
"""
Execute a process and waits for it to complete. Returns all
output (stderr and stdout) after (optional) filtering.
@param args is passed into subprocess.Popen().
@param ignores (optional) is a list of regular expression strings
that will be ignored in the output.
@returns a tuple (returncode, output)
"""
if ignores is None:
ignores = []
else:
ignores = [re.compile(ignore) for ignore in ignores]
proc = subprocess.Popen(
args,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
output = ''.join(
line for line in proc.stdout
if not any(bool(ignore.match(line)) for ignore in ignores))
returncode = proc.wait()
return (returncode, output)
def list_files(paths):
"""
Accepts a list of directories or filenames on the command line.
We do not choose to recurse into directories beyond one level.
"""
class NotAFileException(Exception):
pass
for path in paths:
for globbedpath in glob.iglob(path): # useful on win32
if os.path.isdir(globbedpath):
for filename in os.listdir(globbedpath):
newpath = os.path.join(globbedpath, filename)
if os.path.isfile(newpath):
yield newpath
elif os.path.isfile(globbedpath):
yield globbedpath
else:
raise NotAFileException('{} is not a file'.format(globbedpath))
class BadImageFinder(object):
def __init__(self, directory=None):
self.render_pictures = test_rendering.FindPathToProgram(
'render_pictures')
self.test_image_decoder = test_rendering.FindPathToProgram(
'test_image_decoder')
assert os.path.isfile(self.render_pictures)
assert os.path.isfile(self.test_image_decoder)
if directory is None:
self.saved_image_dir = tempfile.mkdtemp(prefix='skia_skp_test_')
else:
assert os.path.isdir(directory)
self.saved_image_dir = directory
self.bad_image_count = 0
def process_files(self, skp_files):
for path in skp_files:
self.process_file(path)
def process_file(self, skp_file):
assert self.saved_image_dir is not None
assert os.path.isfile(skp_file)
args = [self.render_pictures, '--readPath', skp_file]
ignores = ['^process_in', '^deserializ', '^drawing...', '^Non-defaul']
returncode, output = execute_program(args, ignores)
if (returncode == 0) and not output:
return
temp_image_dir = tempfile.mkdtemp(prefix='skia_skp_test___')
args = [ self.render_pictures, '--readPath', skp_file,
'--writePath', temp_image_dir, '--writeEncodedImages']
subprocess.call(args, stderr=open(os.devnull,'w'),
stdout=open(os.devnull,'w'))
for image_name in os.listdir(temp_image_dir):
image_path = os.path.join(temp_image_dir, image_name)
assert(os.path.isfile(image_path))
args = [self.test_image_decoder, image_path]
returncode, output = execute_program(args, [])
if (returncode == 0) and not output:
os.remove(image_path)
continue
try:
shutil.move(image_path, self.saved_image_dir)
except (shutil.Error,):
# If this happens, don't stop the entire process,
# just warn the user.
os.remove(image_path)
sys.stderr.write('{0} is a repeat.\n'.format(image_name))
self.bad_image_count += 1
if returncode == 2:
returncode = 'SkImageDecoder::DecodeFile returns false'
elif returncode == 0:
returncode = 'extra verbosity'
assert output
elif returncode == -11:
returncode = 'segmentation violation'
else:
returncode = 'returncode: {}'.format(returncode)
output = output.strip().replace('\n',' ').replace('"','\'')
suffix = image_name[-3:]
output_line = '"{0}","{1}","{2}","{3}","{4}"\n'.format(
returncode, suffix, skp_file, image_name, output)
sys.stdout.write(output_line)
sys.stdout.flush()
os.rmdir(temp_image_dir)
return
def main(main_argv):
if not main_argv or main_argv[0] in ['-h', '-?', '-help', '--help']:
sys.stderr.write(USAGE.format(command=__file__))
return 1
if 'NUM_THREADS' in os.environ:
number_of_threads = int(os.environ['NUM_THREADS'])
if number_of_threads < 1:
number_of_threads = 1
else:
number_of_threads = 1
os.environ['skia_images_png_suppressDecoderWarnings'] = 'true'
os.environ['skia_images_jpeg_suppressDecoderWarnings'] = 'true'
temp_dir = tempfile.mkdtemp(prefix='skia_skp_test_')
sys.stderr.write('Directory for bad images: {}\n'.format(temp_dir))
sys.stdout.write('"Error","Filetype","SKP File","Image File","Output"\n')
sys.stdout.flush()
finders = [
BadImageFinder(temp_dir) for index in xrange(number_of_threads)]
arguments = [[] for index in xrange(number_of_threads)]
for index, item in enumerate(list_files(main_argv)):
## split up the given targets among the worker threads
arguments[index % number_of_threads].append(item)
threads = [
threading.Thread(
target=BadImageFinder.process_files, args=(finder,argument))
for finder, argument in zip(finders, arguments)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
number = sum(finder.bad_image_count for finder in finders)
sys.stderr.write('Number of bad images found: {}\n'.format(number))
return 0
if __name__ == '__main__':
exit(main(sys.argv[1:]))
# LocalWords: skp stdout csv
| bsd-3-clause |
nfcpy/ndeflib | tests/test_text.py | 1 | 3339 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division
import ndef
import pytest
import _test_record_base
def pytest_generate_tests(metafunc):
_test_record_base.generate_tests(metafunc)
class TestTextRecord(_test_record_base._TestRecordBase):
RECORD = ndef.text.TextRecord
ATTRIB = "text, language, encoding"
test_init_args_data = [
((), ('', 'en', 'UTF-8')),
((None, None, None), ('', 'en', 'UTF-8')),
(('Hello',), ('Hello', 'en', 'UTF-8')),
(('Hello', 'en',), ('Hello', 'en', 'UTF-8')),
(('Hello', 'en', 'UTF-8'), ('Hello', 'en', 'UTF-8')),
(('Hello', 'de', 'UTF-16'), ('Hello', 'de', 'UTF-16')),
(('Hello', 63*'a'), ('Hello', 63*'a', 'UTF-8')),
((u'Hallo', u'de',), ('Hallo', 'de', 'UTF-8')),
((b'Hallo', b'de',), ('Hallo', 'de', 'UTF-8')),
]
test_init_kwargs_data = [
(('T', 'de', 'UTF-16'), "text='T', language='de', encoding='UTF-16'"),
]
test_init_fail_data = [
((1,), ".text accepts str or bytes, but not int"),
(('', ''), ".language must be 1..63 characters, got 0"),
(('', 64*'a'), ".language must be 1..63 characters, got 64"),
(('', 'a', 'X'), ".encoding may be 'UTF-8' or 'UTF-16', but not 'X'"),
(('', 0,), ".language accepts str or bytes, but not int"),
(('', 'a', 0), ".encoding may be 'UTF-8' or 'UTF-16', but not '0'"),
]
test_decode_valid_data = [
('02656e', ("", "en", "UTF-8")),
('026465', ("", "de", "UTF-8")),
('02656e48656c6c6f', ("Hello", "en", "UTF-8")),
('82656efffe480065006c006c006f00', ("Hello", "en", "UTF-16")),
('02656cce94', (u"\u0394", "el", "UTF-8")),
('82656cfffe9403', (u"\u0394", "el", "UTF-16")),
]
test_decode_error_data = [
("82656e54", "can't be decoded as UTF-16"),
("02656efffe5400", "can't be decoded as UTF-8"),
("00", "language code length can not be zero"),
("01", "language code length exceeds payload"),
]
test_decode_relax = None
test_encode_error = None
test_format_args_data = [
((), "'', 'en', 'UTF-8'"),
(('a',), "'a', 'en', 'UTF-8'"),
(('a', 'de'), "'a', 'de', 'UTF-8'"),
]
test_format_str_data = [
((),
"NDEF Text Record ID '' Text '' Language 'en' Encoding 'UTF-8'"),
(('T'),
"NDEF Text Record ID '' Text 'T' Language 'en' Encoding 'UTF-8'"),
(('T', 'de'),
"NDEF Text Record ID '' Text 'T' Language 'de' Encoding 'UTF-8'"),
]
text_messages = [
('D101075402656e54455854',
[ndef.TextRecord('TEXT', 'en', 'UTF-8')]),
('9101075402656e54585431 5101075402656e54585432',
[ndef.TextRecord('TXT1', 'en', 'UTF-8'),
ndef.TextRecord('TXT2', 'en', 'UTF-8')]),
]
@pytest.mark.parametrize("encoded, message", text_messages)
def test_message_decode(encoded, message):
octets = bytes(bytearray.fromhex(encoded))
print(list(ndef.message_decoder(octets)))
assert list(ndef.message_decoder(octets)) == message
@pytest.mark.parametrize("encoded, message", text_messages)
def test_message_encode(encoded, message):
octets = bytes(bytearray.fromhex(encoded))
print(list(ndef.message_encoder(message)))
assert b''.join(list(ndef.message_encoder(message))) == octets
| isc |
LIMXTEC/DMDv3 | qa/rpc-tests/mempool_coinbase_spends.py | 143 | 3850 | #!/usr/bin/env python2
# Copyright (c) 2014 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test re-org scenarios with a mempool that contains transactions
# that spend (directly or indirectly) coinbase transactions.
#
from test_framework import BitcoinTestFramework
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
from util import *
import os
import shutil
# Create one-input, one-output, no-fee transaction:
class MempoolCoinbaseTest(BitcoinTestFramework):
alert_filename = None # Set by setup_network
def setup_network(self):
args = ["-checkmempool", "-debug=mempool"]
self.nodes = []
self.nodes.append(start_node(0, self.options.tmpdir, args))
self.nodes.append(start_node(1, self.options.tmpdir, args))
connect_nodes(self.nodes[1], 0)
self.is_network_split = False
self.sync_all
def create_tx(self, from_txid, to_address, amount):
inputs = [{ "txid" : from_txid, "vout" : 0}]
outputs = { to_address : amount }
rawtx = self.nodes[0].createrawtransaction(inputs, outputs)
signresult = self.nodes[0].signrawtransaction(rawtx)
assert_equal(signresult["complete"], True)
return signresult["hex"]
def run_test(self):
start_count = self.nodes[0].getblockcount()
# Mine three blocks. After this, nodes[0] blocks
# 101, 102, and 103 are spend-able.
new_blocks = self.nodes[1].setgenerate(True, 4)
self.sync_all()
node0_address = self.nodes[0].getnewaddress()
node1_address = self.nodes[1].getnewaddress()
# Three scenarios for re-orging coinbase spends in the memory pool:
# 1. Direct coinbase spend : spend_101
# 2. Indirect (coinbase spend in chain, child in mempool) : spend_102 and spend_102_1
# 3. Indirect (coinbase and child both in chain) : spend_103 and spend_103_1
# Use invalidatblock to make all of the above coinbase spends invalid (immature coinbase),
# and make sure the mempool code behaves correctly.
b = [ self.nodes[0].getblockhash(n) for n in range(102, 105) ]
coinbase_txids = [ self.nodes[0].getblock(h)['tx'][0] for h in b ]
spend_101_raw = self.create_tx(coinbase_txids[0], node1_address, 50)
spend_102_raw = self.create_tx(coinbase_txids[1], node0_address, 50)
spend_103_raw = self.create_tx(coinbase_txids[2], node0_address, 50)
# Broadcast and mine spend_102 and 103:
spend_102_id = self.nodes[0].sendrawtransaction(spend_102_raw)
spend_103_id = self.nodes[0].sendrawtransaction(spend_103_raw)
self.nodes[0].setgenerate(True, 1)
# Create 102_1 and 103_1:
spend_102_1_raw = self.create_tx(spend_102_id, node1_address, 50)
spend_103_1_raw = self.create_tx(spend_103_id, node1_address, 50)
# Broadcast and mine 103_1:
spend_103_1_id = self.nodes[0].sendrawtransaction(spend_103_1_raw)
self.nodes[0].setgenerate(True, 1)
# ... now put spend_101 and spend_102_1 in memory pools:
spend_101_id = self.nodes[0].sendrawtransaction(spend_101_raw)
spend_102_1_id = self.nodes[0].sendrawtransaction(spend_102_1_raw)
self.sync_all()
assert_equal(set(self.nodes[0].getrawmempool()), set([ spend_101_id, spend_102_1_id ]))
# Use invalidateblock to re-org back and make all those coinbase spends
# immature/invalid:
for node in self.nodes:
node.invalidateblock(new_blocks[0])
self.sync_all()
# mempool should be empty.
assert_equal(set(self.nodes[0].getrawmempool()), set())
if __name__ == '__main__':
MempoolCoinbaseTest().main()
| mit |
billwanjohi/ansible-modules-core | utilities/assert.py | 80 | 1392 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2012 Dag Wieers <dag@wieers.com>
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = '''
---
module: assert
short_description: Fail with custom message
description:
- This module asserts that a given expression is true and can be a simpler alternative to the 'fail' module in some cases.
version_added: "1.5"
options:
that:
description:
- "A string expression of the same form that can be passed to the 'when' statement"
- "Alternatively, a list of string expressions"
required: true
author: Michael DeHaan
'''
EXAMPLES = '''
- assert: { that: "ansible_os_family != 'RedHat'" }
- assert:
that:
- "'foo' in some_command_result.stdout"
- "number_of_the_counting == 3"
'''
| gpl-3.0 |
todaychi/hue | apps/oozie/src/oozie/migrations/0016_auto__add_field_coordinator_job_properties.py | 36 | 23680 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Coordinator.job_properties'
db.add_column('oozie_coordinator', 'job_properties', self.gf('django.db.models.fields.TextField')(default='[]'), keep_default=False)
try:
from oozie.models import Coordinator
Coordinator.objects.all().update(job_properties='[]')
except Exception, e:
import logging
logging.warn(e)
def backwards(self, orm):
# Deleting field 'Coordinator.job_properties'
db.delete_column('oozie_coordinator', 'job_properties')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'oozie.coordinator': {
'Meta': {'object_name': 'Coordinator', '_ormbases': ['oozie.Job']},
'concurrency': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
'end': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 16, 9, 46, 22, 231292)'}),
'execution': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}),
'frequency_number': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'}),
'frequency_unit': ('django.db.models.fields.CharField', [], {'default': "'days'", 'max_length': '20'}),
'job_properties': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'job_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Job']", 'unique': 'True', 'primary_key': 'True'}),
'start': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 13, 9, 46, 22, 231260)'}),
'throttle': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
'timeout': ('django.db.models.fields.SmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
'timezone': ('django.db.models.fields.CharField', [], {'default': "'America/Los_Angeles'", 'max_length': '24'}),
'workflow': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oozie.Workflow']", 'null': 'True'})
},
'oozie.datainput': {
'Meta': {'object_name': 'DataInput'},
'coordinator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oozie.Coordinator']"}),
'dataset': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Dataset']", 'unique': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '40'})
},
'oozie.dataoutput': {
'Meta': {'object_name': 'DataOutput'},
'coordinator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oozie.Coordinator']"}),
'dataset': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Dataset']", 'unique': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '40'})
},
'oozie.dataset': {
'Meta': {'object_name': 'Dataset'},
'advanced_end_instance': ('django.db.models.fields.CharField', [], {'default': "'0'", 'max_length': '128', 'blank': 'True'}),
'advanced_start_instance': ('django.db.models.fields.CharField', [], {'default': "'0'", 'max_length': '128'}),
'coordinator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oozie.Coordinator']"}),
'description': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '1024', 'blank': 'True'}),
'done_flag': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '64', 'blank': 'True'}),
'frequency_number': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'}),
'frequency_unit': ('django.db.models.fields.CharField', [], {'default': "'days'", 'max_length': '20'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'instance_choice': ('django.db.models.fields.CharField', [], {'default': "'default'", 'max_length': '10'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'start': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 13, 9, 46, 22, 232054)'}),
'timezone': ('django.db.models.fields.CharField', [], {'default': "'America/Los_Angeles'", 'max_length': '24'}),
'uri': ('django.db.models.fields.CharField', [], {'default': "'/data/${YEAR}${MONTH}${DAY}'", 'max_length': '1024'})
},
'oozie.decision': {
'Meta': {'object_name': 'Decision'},
'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'})
},
'oozie.decisionend': {
'Meta': {'object_name': 'DecisionEnd'},
'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'})
},
'oozie.distcp': {
'Meta': {'object_name': 'DistCp'},
'job_properties': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'job_xml': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '512', 'blank': 'True'}),
'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}),
'params': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'prepares': ('django.db.models.fields.TextField', [], {'default': "'[]'"})
},
'oozie.email': {
'Meta': {'object_name': 'Email'},
'body': ('django.db.models.fields.TextField', [], {'default': "''"}),
'cc': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}),
'subject': ('django.db.models.fields.TextField', [], {'default': "''"}),
'to': ('django.db.models.fields.TextField', [], {'default': "''"})
},
'oozie.end': {
'Meta': {'object_name': 'End'},
'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'})
},
'oozie.fork': {
'Meta': {'object_name': 'Fork'},
'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'})
},
'oozie.fs': {
'Meta': {'object_name': 'Fs'},
'chmods': ('django.db.models.fields.TextField', [], {'default': "'[]'", 'blank': 'True'}),
'deletes': ('django.db.models.fields.TextField', [], {'default': "'[]'", 'blank': 'True'}),
'mkdirs': ('django.db.models.fields.TextField', [], {'default': "'[]'", 'blank': 'True'}),
'moves': ('django.db.models.fields.TextField', [], {'default': "'[]'", 'blank': 'True'}),
'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}),
'touchzs': ('django.db.models.fields.TextField', [], {'default': "'[]'", 'blank': 'True'})
},
'oozie.generic': {
'Meta': {'object_name': 'Generic'},
'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}),
'xml': ('django.db.models.fields.TextField', [], {'default': "''"})
},
'oozie.history': {
'Meta': {'object_name': 'History'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'job': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oozie.Job']"}),
'oozie_job_id': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'properties': ('django.db.models.fields.TextField', [], {}),
'submission_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'submitter': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'oozie.hive': {
'Meta': {'object_name': 'Hive'},
'archives': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'files': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'job_properties': ('django.db.models.fields.TextField', [], {'default': '\'[{"name":"oozie.hive.defaults","value":"hive-site.xml"}]\''}),
'job_xml': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '512', 'blank': 'True'}),
'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}),
'params': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'prepares': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'script_path': ('django.db.models.fields.CharField', [], {'max_length': '256'})
},
'oozie.java': {
'Meta': {'object_name': 'Java'},
'archives': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'args': ('django.db.models.fields.CharField', [], {'max_length': '4096', 'blank': 'True'}),
'files': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'jar_path': ('django.db.models.fields.CharField', [], {'max_length': '512'}),
'java_opts': ('django.db.models.fields.CharField', [], {'max_length': '256', 'blank': 'True'}),
'job_properties': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'job_xml': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '512', 'blank': 'True'}),
'main_class': ('django.db.models.fields.CharField', [], {'max_length': '256'}),
'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}),
'prepares': ('django.db.models.fields.TextField', [], {'default': "'[]'"})
},
'oozie.job': {
'Meta': {'object_name': 'Job'},
'deployment_dir': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'blank': 'True'}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_shared': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True', 'blank': 'True'}),
'last_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'parameters': ('django.db.models.fields.TextField', [], {'default': '\'[{"name":"oozie.use.system.libpath","value":"true"}]\''}),
'schema_version': ('django.db.models.fields.CharField', [], {'max_length': '128'})
},
'oozie.join': {
'Meta': {'object_name': 'Join'},
'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'})
},
'oozie.kill': {
'Meta': {'object_name': 'Kill'},
'message': ('django.db.models.fields.CharField', [], {'default': "'Action failed, error message[${wf:errorMessage(wf:lastErrorNode())}]'", 'max_length': '256'}),
'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'})
},
'oozie.link': {
'Meta': {'object_name': 'Link'},
'child': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'parent_node'", 'to': "orm['oozie.Node']"}),
'comment': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '1024', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'child_node'", 'to': "orm['oozie.Node']"})
},
'oozie.mapreduce': {
'Meta': {'object_name': 'Mapreduce'},
'archives': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'files': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'jar_path': ('django.db.models.fields.CharField', [], {'max_length': '512'}),
'job_properties': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'job_xml': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '512', 'blank': 'True'}),
'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True'}),
'prepares': ('django.db.models.fields.TextField', [], {'default': "'[]'"})
},
'oozie.node': {
'Meta': {'object_name': 'Node'},
'children': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'parents'", 'symmetrical': 'False', 'through': "orm['oozie.Link']", 'to': "orm['oozie.Node']"}),
'description': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '1024', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'node_type': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'workflow': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oozie.Workflow']"})
},
'oozie.pig': {
'Meta': {'object_name': 'Pig'},
'archives': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'files': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'job_properties': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'job_xml': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '512', 'blank': 'True'}),
'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}),
'params': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'prepares': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'script_path': ('django.db.models.fields.CharField', [], {'max_length': '256'})
},
'oozie.shell': {
'Meta': {'object_name': 'Shell'},
'archives': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'capture_output': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'command': ('django.db.models.fields.CharField', [], {'max_length': '256'}),
'files': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'job_properties': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'job_xml': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '512', 'blank': 'True'}),
'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}),
'params': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'prepares': ('django.db.models.fields.TextField', [], {'default': "'[]'"})
},
'oozie.sqoop': {
'Meta': {'object_name': 'Sqoop'},
'archives': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'files': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'job_properties': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'job_xml': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '512', 'blank': 'True'}),
'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}),
'params': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'prepares': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'script_path': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'})
},
'oozie.ssh': {
'Meta': {'object_name': 'Ssh'},
'capture_output': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'command': ('django.db.models.fields.CharField', [], {'max_length': '256'}),
'host': ('django.db.models.fields.CharField', [], {'max_length': '256'}),
'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}),
'params': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'user': ('django.db.models.fields.CharField', [], {'max_length': '64'})
},
'oozie.start': {
'Meta': {'object_name': 'Start'},
'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True'})
},
'oozie.streaming': {
'Meta': {'object_name': 'Streaming'},
'archives': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'files': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'job_properties': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'mapper': ('django.db.models.fields.CharField', [], {'max_length': '512'}),
'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}),
'reducer': ('django.db.models.fields.CharField', [], {'max_length': '512'})
},
'oozie.subworkflow': {
'Meta': {'object_name': 'SubWorkflow'},
'job_properties': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'node_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Node']", 'unique': 'True', 'primary_key': 'True'}),
'propagate_configuration': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
'sub_workflow': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oozie.Workflow']"})
},
'oozie.workflow': {
'Meta': {'object_name': 'Workflow', '_ormbases': ['oozie.Job']},
'end': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'end_workflow'", 'null': 'True', 'to': "orm['oozie.End']"}),
'is_single': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'job_properties': ('django.db.models.fields.TextField', [], {'default': "'[]'"}),
'job_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['oozie.Job']", 'unique': 'True', 'primary_key': 'True'}),
'job_xml': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '512', 'blank': 'True'}),
'start': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'start_workflow'", 'null': 'True', 'to': "orm['oozie.Start']"})
}
}
complete_apps = ['oozie']
| apache-2.0 |
upgrades-migrations/preupgrade-assistant | preupg/script_api.py | 2 | 23078 | # -*- coding: utf-8 -*-
"""
python API for content writers
USAGE
*****
Best way is to import all functions from this module:
from script_api import *
These functions are available:
* logging functions -- log_*
* log message to stdout
* logging risk functions -- log_*_risk
* log risk level -- so administrator know how risky is to inplace upgrade
* get_dest_dir -- get dir for storing configuration files
* exit_* -- terminate execution with appropriate exit code
"""
from __future__ import unicode_literals, print_function
import os
import sys
import re
import shutil
import errno
try:
import configparser
except ImportError:
import ConfigParser as configparser
from preupg import settings
from preupg.utils import FileHelper, ProcessHelper
__all__ = (
'log_debug',
'log_info',
'log_warning',
'log_error',
'log_extreme_risk',
'log_high_risk',
'log_medium_risk',
'log_slight_risk',
'get_dest_dir',
'exit_error',
'exit_fail',
'exit_fixed',
'exit_informational',
'exit_not_applicable',
'exit_informational',
'exit_pass',
'check_rpm_to',
'check_applies_to',
'solution_file',
'switch_to_content',
'service_is_enabled',
'is_dist_native',
'get_dist_native_list',
'is_pkg_installed',
'add_pkg_to_kickstart',
'deploy_hook',
'PREUPGRADE_CACHE',
'VALUE_RPM_QA',
'VALUE_ALLCHANGED',
'VALUE_CONFIGCHANGED',
'VALUE_PASSWD',
'VALUE_CHKCONFIG',
'VALUE_GROUP',
'VALUE_RPMTRACKEDFILES',
'VALUE_ALLMYFILES',
'VALUE_EXECUTABLES',
'VALUE_RPM_RHSIGNED',
'VALUE_TMP_PREUPGRADE',
'MODULE_PATH',
'COMMON_DIR',
'SOLUTION_FILE',
'POSTUPGRADE_DIR',
'KICKSTART_DIR',
'KICKSTART_README',
'KICKSTART_SCRIPTS',
'KICKSTART_POSTUPGRADE',
'MIGRATE',
'UPGRADE',
'HOME_DIRECTORY_FILE',
'USER_CONFIG_FILE',
'PREUPG_API_VERSION',
'DEVEL_MODE',
'DIST_NATIVE',
'SPECIAL_PKG_LIST',
'NOAUTO_POSTUPGRADE_D',
)
# These variables and functions will be available
# for Bash preupgrade-assistant modules.
#
CACHE = "/var/cache/preupgrade"
#
# Directory with logs gathered by preupgrade-assistant
#
PREUPGRADE_CACHE = os.path.join(CACHE, "common")
#
# Preupgrade-assistant configuration file
#
PREUPGRADE_CONFIG = settings.PREUPG_CONFIG_FILE
#
# Full path log file with to all installed packages
#
VALUE_RPM_QA = os.path.join(PREUPGRADE_CACHE, "rpm_qa.log")
#
# Full path log file with to all changed files
#
VALUE_ALLCHANGED = os.path.join(PREUPGRADE_CACHE, "rpm_Va.log")
#
# Full path to log file with all /etc changed configuration files
#
VALUE_CONFIGCHANGED = os.path.join(PREUPGRADE_CACHE, "rpm_etc_Va.log")
#
# Full path to log file with all users gathered by getent
#
VALUE_PASSWD = os.path.join(PREUPGRADE_CACHE, "passwd.log")
#
# Full path to log file with all services enabled/disabled on system.
#
VALUE_CHKCONFIG = os.path.join(PREUPGRADE_CACHE, "chkconfig.log")
#
# Full path to log file with all groups gathered by getent
#
VALUE_GROUP = os.path.join(PREUPGRADE_CACHE, "group.log")
#
# Full path to log file with all installed files
#
VALUE_RPMTRACKEDFILES = os.path.join(PREUPGRADE_CACHE, "rpmtrackedfiles.log")
#
# Full path to log file with all installed files
#
VALUE_ALLMYFILES = os.path.join(PREUPGRADE_CACHE, "allmyfiles.log")
#
# Full path to log file with all executable files
#
VALUE_EXECUTABLES = os.path.join(PREUPGRADE_CACHE, "executable.log")
#
# Full path to log file with all Red Hat signed packages
#
VALUE_RPM_RHSIGNED = os.path.join(PREUPGRADE_CACHE, "rpm_rhsigned.log")
#
# Variable which referes to temporary directory directory provided by module
#
VALUE_TMP_PREUPGRADE = os.environ['XCCDF_VALUE_TMP_PREUPGRADE']
#
# Directory with configuration files that can be applied safely.
#
# Configuration files in this directory will be automatically applied on the
# upgraded system. Files has to be stored in this directory using whole path
# referring to the place where they should be copied. E.g.:
# $CLEANCONF_DIR/etc/group -> /etc/group
#
CLEANCONF_DIR = os.path.join(VALUE_TMP_PREUPGRADE, "cleanconf")
#
# Directory with configuration files that need to be overviewed manually.
#
# Configuration files in this directory cannot be applied on the upgraded
# system safely and need to be handled or overviewed manually. Usually are not
# copied automatically on the upgraded system unless there is a post-upgrade
# script that handle issue related with a configuration file at least
# partially.
#
DIRTYCONF_DIR = os.path.join(VALUE_TMP_PREUPGRADE, "dirtyconf")
#
# Variable which referes to current directory directory provided by module
#
VALUE_CURRENT_DIRECTORY = os.environ['XCCDF_VALUE_CURRENT_DIRECTORY']
#
# Variable which referes to solution file provided by module
#
SOLUTION_FILE = os.path.join(VALUE_CURRENT_DIRECTORY, settings.solution_txt)
#
# Variable which referes to current upgrade path directory
#
VALUE_REPORT_DIR = os.environ['XCCDF_VALUE_REPORT_DIR']
#
# Name of module being currently executed
#
try:
MODULE_PATH = os.environ['XCCDF_VALUE_MODULE_PATH']
except KeyError:
MODULE_PATH = VALUE_CURRENT_DIRECTORY.replace(VALUE_REPORT_DIR, '')
MODULE_PATH = MODULE_PATH.replace('/', '_')
#
# MIGRATE means if preupg binary was used with `--mode migrate` parameter
# UPGRADE means if preupg binary was used with `--mode upgrade` parameter
# These modes are used if `--mode` is not used
#
try:
MIGRATE = os.environ['XCCDF_VALUE_MIGRATE']
UPGRADE = os.environ['XCCDF_VALUE_UPGRADE']
except KeyError:
MIGRATE = 1
UPGRADE = 1
#
# Variable which indicates DEVEL mode.
#
try:
DEVEL_MODE = os.environ['XCCDF_VALUE_DEVEL_MODE']
except KeyError:
DEVEL_MODE = 0
#
# Override mode for is_dist_native() and similar
#
# Affects which packages are considered native:
#
# If set to 'sign' (default), GPG signature is consulted. If 'all',
# all packages are native. If set to path to a file, packages listed
# there are native.
#
try:
DIST_NATIVE = os.environ['XCCDF_VALUE_DIST_NATIVE']
except KeyError:
DIST_NATIVE = 'sign'
#
# preupgrade-scripts directory used by redhat-upgrade-tool
#
# Executable scripts inside the directrory (ans subdirectories) are processed
# by redhat-upgrade-tool during the pre-upgrade phase, after the upgrade RPM
# transaction is calculated and before the reboot is processed.
#
PREUPGRADE_SCRIPT_DIR = os.path.join(VALUE_TMP_PREUPGRADE, "preupgrade-scripts")
#
# postupgrade directory used by in-place upgrades.
#
# Scripts mentioned there are executed automatically by redhat-upgrade-tool
#
POSTUPGRADE_DIR = os.path.join(VALUE_TMP_PREUPGRADE, "postupgrade.d")
#
# postmigrate directory used after migration
#
# Executable scripts in the directory are processed during the %post phase
# when migration to the new system is done using the generated kickstart file.
#
POSTMIGRATE_DIR = os.path.join(VALUE_TMP_PREUPGRADE, "postmigrate.d")
#
# Directory which is used for kickstart generation
#
KICKSTART_DIR = os.path.join(VALUE_TMP_PREUPGRADE, "kickstart")
#
# README file which contains description about all files in kickstart directory
#
KICKSTART_README = os.path.join(KICKSTART_DIR, "README")
#
# Directory with scripts which can be executed after installation by administrator
#
KICKSTART_SCRIPTS = os.path.join(KICKSTART_DIR, "scripts")
#
# The same as $KICKSTART_SCRIPTS
#
KICKSTART_POSTUPGRADE = KICKSTART_SCRIPTS
#
# Variable which refers to static data used by preupgrade-assistant and modules
#
COMMON_DIR = os.path.join(os.environ['XCCDF_VALUE_REPORT_DIR'], "common")
#
# Variable which contains file with packages add to the kickstart anyway
#
SPECIAL_PKG_LIST = os.path.join(KICKSTART_DIR, 'special_pkg_list')
#
# Postupgrade directory which is not executed automatically after an upgrade or migration
#
NOAUTO_POSTUPGRADE_D = os.path.join(VALUE_TMP_PREUPGRADE, 'noauto_postupgrade.d')
#
# variables set by PA config file #
#
HOME_DIRECTORY_FILE = ""
USER_CONFIG_FILE = 0
#
# Version of this API
#
PREUPG_API_VERSION = 1
################
# RISK LOGGING #
################
def _log_risk(severity, message):
"""
log risk level to stderr
"""
print("preupg.risk.%s: %s\n" % (severity, message.encode(settings.defenc)), end="", file=sys.stderr)
def log_extreme_risk(message):
"""
log_extreme_risk(message)
Inplace upgrade is impossible.
"""
_log_risk("EXTREME", message)
def log_high_risk(message):
"""
log_high_risk(message)
Administrator has to inspect and correct upgraded system so
inplace upgrade can be used.
"""
_log_risk("HIGH", message)
def log_medium_risk(message):
"""
log_medium_risk(message)
inplace upgrade is possible; system after upgrade may be unstable
"""
_log_risk("MEDIUM", message)
def log_slight_risk(message):
"""
log_slight_risk(message)
no issues found; although there are some unexplored areas
"""
_log_risk("SLIGHT", message)
##################
# STDOUT LOGGING #
##################
def _log(severity, message):
"""
general logging function
:param severity: set it to one of INFO|ERROR|WARNING
:param message:message to be logged
:return:
"""
print("preupg.log.%s: %s\n" % (severity, message.encode(settings.defenc)), end="", file=sys.stderr)
def log_error(message):
"""
log_error(message) -> None
log message to stdout with severity error
use this severity if your script found something severe
which may cause malfunction on new system
"""
_log('ERROR', message)
def log_warning(message):
"""
log_warning(message) -> None
log message to stdout with severity warning
important finding, administrator of system should be aware of this
"""
_log('WARNING', message)
def log_info(message):
"""
log_info(message) -> None
log message to stdout with severity info
informational message
"""
_log('INFO', message)
def log_debug(message):
"""
log_debug(message) -> None
log message to stdout with severity debug
verbose information, may help with script debugging
"""
_log('DEBUG', message)
#########
# UTILS #
#########
def get_dest_dir():
"""
get_dest_dir()
return absolute path to directory, where you should store files
"""
return os.environ['XCCDF_VALUE_TMP_PREUPGRADE']
def shorten_envs():
"""make all the oscap's environemt variables shorter"""
envs = os.environ
prefixes = ('XCCDF_VALUE_', 'XCCDF_RESULT_')
for env_key, env_value in envs.items():
for prefix in prefixes:
if env_key.startswith(prefix):
os.environ[env_key.replace(prefix, '')] = env_value
# These are shortcut functions for:
# sys.exit(int(os.environ['FAIL']))
def exit_fail():
"""
The test failed.
Moving to new release with this configuration will result in malfunction.
"""
sys.exit(int(os.environ['XCCDF_RESULT_FAIL']))
def exit_error():
"""
An error occurred and test could not complete.
(script failed while doing its job)
"""
sys.exit(int(os.environ['XCCDF_RESULT_ERROR']))
def exit_pass():
"""Test passed."""
sys.exit(int(os.environ['XCCDF_RESULT_PASS']))
def exit_not_applicable():
"""Rule did not apply to test target. (e.g. package is not installed)"""
sys.exit(int(os.environ['XCCDF_RESULT_NOT_APPLICABLE']))
def exit_fixed():
"""Rule failed, but was later fixed."""
sys.exit(int(os.environ['XCCDF_RESULT_FIXED']))
def exit_informational():
"""Rule failed, but was later fixed."""
sys.exit(int(os.environ['XCCDF_RESULT_INFORMATIONAL']))
def switch_to_content():
"""Function for switch to the content directory"""
os.chdir(os.environ['CURRENT_DIRECTORY'])
def is_pkg_installed(pkg_name):
"""
Function checks if package is installed.
:param pkg_name: Parameter is a package name which will be checked.
:return: 0 - package is installed
1 - package is NOT installed
"""
lines = FileHelper.get_file_content(VALUE_RPM_QA, "rb", True)
found = [x for x in lines if x.split()[0] == pkg_name]
if found:
return True
else:
return False
def check_applies_to(check_applies=""):
"""
Function checks is package is installed and signed by Red Hat
:param check_applies: Parameter list of packages which will be checked. Module requires them.
:return: 0 - package is installed and signed by Red Hat
exit_not_applicable - module will not be executed
"""
not_applicable = 0
if check_applies != "":
rpms = check_applies.split(',')
for rpm in rpms:
if not (is_pkg_installed(rpm) and is_dist_native(rpm)):
log_info("Package %s is not installed or it is not signed by Red Hat." % rpm)
not_applicable = 1
if not_applicable:
exit_not_applicable()
return not_applicable
def check_rpm_to(check_rpm="", check_bin=""):
"""
Function checks if relevant package is installed and if relevant binary exists on the system.
Function is needed from module point of view.
:param check_rpm: list of RPMs separated by comma
:param check_bin: list of binaries separated by comma
:return:
"""
not_applicable = 0
if check_rpm != "":
rpms = check_rpm.split(',')
lines = FileHelper.get_file_content(VALUE_RPM_QA, "rb", True)
for rpm in rpms:
lst = [x for x in lines if rpm == x.split('\t')[0]]
if not lst:
log_high_risk("Package %s is not installed." % rpm)
not_applicable = 1
if check_bin != "":
binaries = check_bin.split(',')
for binary in binaries:
cmd = "which %s" % binary
if ProcessHelper.run_subprocess(cmd, print_output=False, shell=True) != 0:
log_high_risk("Binary %s is not installed." % binary)
not_applicable = 1
if not_applicable:
log_high_risk("Please, install all required packages (and binaries)"
" and run preupg again to process check properly.")
exit_fail()
return not_applicable
def solution_file(message):
"""
Function appends a message to solution file.
solution file will be created in module directory
:param message: Message - string of list of strings
:return:
"""
if os.path.exists(SOLUTION_FILE):
mod = "a+b"
else:
mod = "wb"
FileHelper.write_to_file(SOLUTION_FILE, mod, message)
def service_is_enabled(service_name):
"""Returns true if given service is enabled on any runlevel"""
return_value = False
lines = FileHelper.get_file_content(VALUE_CHKCONFIG, "rb", True)
for line in lines:
if re.match('^%s.*:on' % service_name, line):
return_value = True
break
return return_value
def config_file_changed(config_file_name):
"""
Searches cached data in VALUE_CONFIGCHANGED
returns:
True if given config file has been changed
False if given config file hasn't been changed
"""
config_changed = False
try:
lines = FileHelper.get_file_content(VALUE_CONFIGCHANGED, "rb", True)
for line in lines:
if line.find(config_file_name) != -1:
config_changed = True
break
except:
pass
return config_changed
def backup_config_file(config_file_name):
"""
backup the config file
:param config_file_name:
:return:
true if cp succeeds,
if config file doesn't exist
2 if config file was not changed and thus is not necessary to back-up
"""
try:
# report error if file doesn't exist
if not os.path.isfile(config_file_name):
return 1
# don't do anything if config file was not changed
if not config_file_changed(config_file_name):
return 2
# stripping / from beginning is necessary to concat paths properly
os.mkdir(os.path.join(VALUE_TMP_PREUPGRADE, os.path.dirname(config_file_name.strip("/"))))
except OSError:
# path probably exists, it's ok
pass
shutil.copyfile(config_file_name, os.path.join(VALUE_TMP_PREUPGRADE, config_file_name.strip("/")))
def is_dist_native(pkg):
"""
return 1 if package is not installed and print warning log.
is_dist_native function return only True or False
Case DEVEL_MODE is turn off then return True if package is signed or False if not.
Case DEVEL_MODE is turn on:
DIST_NATIVE = sign: return True if is RH_SIGNED else return False
DIST_NATIVE = all: always return True
DIST_NATIVE = path_to_file: return True if package is in file else return False
"""
rpm_qa = FileHelper.get_file_content(VALUE_RPM_QA, "rb", True)
found = [x for x in rpm_qa if x.split()[0] == pkg]
if not found:
log_warning("Package %s is not installed on Red Hat Enterprise Linux system.")
return False
rpm_signed = FileHelper.get_file_content(VALUE_RPM_RHSIGNED, "rb", True)
found = [x for x in rpm_signed if x.split()[0] == pkg]
if int(DEVEL_MODE) == 0:
if found:
return True
else:
return False
else:
if DIST_NATIVE == "all":
return True
if DIST_NATIVE == "sign":
if found:
return True
else:
return False
if os.path.exists(DIST_NATIVE):
list_native = map(
unicode.strip,
FileHelper.get_file_content(DIST_NATIVE, "r", method=True)
)
if pkg in list_native:
return True
return False
def get_dist_native_list():
"""
return list of all dist native packages according to is_dist_native()
"""
native_pkgs = []
tmp = FileHelper.get_file_content(VALUE_RPM_QA, "rb", True)
pkgs = [i.split("\t")[0] for i in tmp]
for pkg in pkgs:
if is_dist_native(pkg) is True:
native_pkgs.append(pkg)
return native_pkgs
def load_pa_configuration():
""" this is main function for parsing """
global HOME_DIRECTORY_FILE
global USER_CONFIG_FILE
global RH_SIGNED_PKGS
if not os.path.exists(PREUPGRADE_CONFIG):
log_error("Configuration file %s is missing or is not readable!"
% PREUPGRADE_CONFIG)
exit_error()
config = configparser.RawConfigParser()
config.read(PREUPGRADE_CONFIG)
section = 'preupgrade-assistant'
home_option = 'home_directory_file'
user_file = 'user_config_file'
if config.has_section(section):
if config.has_option(section, home_option):
HOME_DIRECTORY_FILE = config.get(section, home_option)
if config.has_option(section, user_file):
USER_CONFIG_FILE = config.get(section, user_file)
def print_home_dirs(user_name=""):
"""
print items from [home-dirs] which are relevant for given user
when username is not given or config file for user is not enabled,
items from main configuration file is printed
returns 0 on SUCCESS, otherwise 1 and logs warning
shouldn't be used before load_config_parser
"""
if not os.path.exists(PREUPGRADE_CONFIG):
log_error("Configuration file %s is missing or is not readable!"
% PREUPGRADE_CONFIG)
exit_error()
config = configparser.RawConfigParser()
home_option = 'home-dirs'
try:
if USER_CONFIG_FILE == 'enabled' and user_name == "":
config.read(PREUPGRADE_CONFIG)
return config.options(home_option)
user_home_dir = os.path.join('/home', user_name, HOME_DIRECTORY_FILE)
if not os.path.exists(user_home_dir):
return 0
config.read(user_home_dir)
return config.options(home_option)
except configparser.NoSectionError:
pass
except configparser.NoOptionError:
pass
def add_pkg_to_kickstart(pkg_name):
""" Function adds a package to special_pkg_list """
empty = False
if isinstance(pkg_name, list):
# list of packages
if len(pkg_name) == 0:
empty = True
else:
# string - pkg_name delimited by whitespace
if len(pkg_name.strip()) == 0:
empty = True
else:
# make list from string
pkg_name = pkg_name.strip().split()
if empty is True:
log_debug("Missing parameters! Any package will be added.")
return 1
for pkg in pkg_name:
FileHelper.write_to_file(SPECIAL_PKG_LIST, "a+b", pkg.strip() + '\n')
return 0
def deploy_hook(*args):
"""
Function which deploys script to specific location.
:param hook: hook, like postupgrade, preupgrade, etc.
:param script_name: script name
:return:
"""
if MODULE_PATH == "":
return 0
if len(args) < 1:
log_error("Hook name is not specified. (Possible values are postupgrade, preupgrade.)")
exit_error()
elif len(args) < 2:
log_error("Script name is not specified. It is mandatory.")
exit_error()
deploy_name = args[0]
script_name = args[1]
if deploy_name == "postupgrade" or deploy_name == "preupgrade":
if not os.path.exists(script_name):
log_error("Script_name %s does not exist." % script_name)
exit_error()
hook_dir = "%s/hooks/%s/%s" % (VALUE_TMP_PREUPGRADE, MODULE_PATH, deploy_name)
if not os.path.isdir(hook_dir):
os.makedirs(hook_dir)
else:
log_error("The %s directory already exists" % hook_dir)
exit_error()
try:
shutil.copyfile(script_name, os.path.join(hook_dir, "run_hook"))
for arg in args[2:]:
if arg.startswith('/'):
hook_arg = os.path.join(hook_dir, os.path.basename(arg))
else:
hook_arg = os.path.join(hook_dir, arg)
if os.path.isdir(hook_arg):
log_error("The %s directory already exists" % hook_arg)
exit_error()
if os.path.isfile(hook_arg):
log_error("The %s file already exists" % hook_arg)
exit_error()
try:
shutil.copytree(arg, hook_arg)
except OSError as exc:
if exc.errno == errno.ENOTDIR:
shutil.copyfile(arg, hook_arg)
else:
log_error("Copying failed: %s" % exc)
exit_error()
except IOError as e:
log_error("Copying of hook script failed: %s" % e)
exit_error()
else:
log_error("Unknown hook option '%s'" % deploy_name)
exit_error()
load_pa_configuration()
shorten_envs()
os.chdir(VALUE_CURRENT_DIRECTORY)
| gpl-3.0 |
tomlof/scikit-learn | sklearn/decomposition/tests/test_incremental_pca.py | 43 | 10272 | """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_iris()
def test_incremental_pca():
# Incremental PCA on dense arrays.
X = iris.data
batch_size = X.shape[0] // 3
ipca = IncrementalPCA(n_components=2, batch_size=batch_size)
pca = PCA(n_components=2)
pca.fit_transform(X)
X_transformed = ipca.fit_transform(X)
np.testing.assert_equal(X_transformed.shape, (X.shape[0], 2))
assert_almost_equal(ipca.explained_variance_ratio_.sum(),
pca.explained_variance_ratio_.sum(), 1)
for n_components in [1, 2, X.shape[1]]:
ipca = IncrementalPCA(n_components, batch_size=batch_size)
ipca.fit(X)
cov = ipca.get_covariance()
precision = ipca.get_precision()
assert_array_almost_equal(np.dot(cov, precision),
np.eye(X.shape[1]))
def test_incremental_pca_check_projection():
# Test that the projection of data is correct.
rng = np.random.RandomState(1999)
n, p = 100, 3
X = rng.randn(n, p) * .1
X[:10] += np.array([3, 4, 5])
Xt = 0.1 * rng.randn(1, p) + np.array([3, 4, 5])
# Get the reconstruction of the generated data X
# Note that Xt has the same "components" as X, just separated
# This is what we want to ensure is recreated correctly
Yt = IncrementalPCA(n_components=2).fit(X).transform(Xt)
# Normalize
Yt /= np.sqrt((Yt ** 2).sum())
# Make sure that the first element of Yt is ~1, this means
# the reconstruction worked as expected
assert_almost_equal(np.abs(Yt[0][0]), 1., 1)
def test_incremental_pca_inverse():
# Test that the projection of data can be inverted.
rng = np.random.RandomState(1999)
n, p = 50, 3
X = rng.randn(n, p) # spherical data
X[:, 1] *= .00001 # make middle component relatively small
X += [5, 4, 3] # make a large mean
# same check that we can find the original data from the transformed
# signal (since the data is almost of rank n_components)
ipca = IncrementalPCA(n_components=2, batch_size=10).fit(X)
Y = ipca.transform(X)
Y_inverse = ipca.inverse_transform(Y)
assert_almost_equal(X, Y_inverse, decimal=3)
def test_incremental_pca_validation():
# Test that n_components is >=1 and <= n_features.
X = [[0, 1], [1, 0]]
for n_components in [-1, 0, .99, 3]:
assert_raises(ValueError, IncrementalPCA(n_components,
batch_size=10).fit, X)
def test_incremental_pca_set_params():
# Test that components_ sign is stable over batch sizes.
rng = np.random.RandomState(1999)
n_samples = 100
n_features = 20
X = rng.randn(n_samples, n_features)
X2 = rng.randn(n_samples, n_features)
X3 = rng.randn(n_samples, n_features)
ipca = IncrementalPCA(n_components=20)
ipca.fit(X)
# Decreasing number of components
ipca.set_params(n_components=10)
assert_raises(ValueError, ipca.partial_fit, X2)
# Increasing number of components
ipca.set_params(n_components=15)
assert_raises(ValueError, ipca.partial_fit, X3)
# Returning to original setting
ipca.set_params(n_components=20)
ipca.partial_fit(X)
def test_incremental_pca_num_features_change():
# Test that changing n_components will raise an error.
rng = np.random.RandomState(1999)
n_samples = 100
X = rng.randn(n_samples, 20)
X2 = rng.randn(n_samples, 50)
ipca = IncrementalPCA(n_components=None)
ipca.fit(X)
assert_raises(ValueError, ipca.partial_fit, X2)
def test_incremental_pca_batch_signs():
# Test that components_ sign is stable over batch sizes.
rng = np.random.RandomState(1999)
n_samples = 100
n_features = 3
X = rng.randn(n_samples, n_features)
all_components = []
batch_sizes = np.arange(10, 20)
for batch_size in batch_sizes:
ipca = IncrementalPCA(n_components=None, batch_size=batch_size).fit(X)
all_components.append(ipca.components_)
for i, j in zip(all_components[:-1], all_components[1:]):
assert_almost_equal(np.sign(i), np.sign(j), decimal=6)
def test_incremental_pca_batch_values():
# Test that components_ values are stable over batch sizes.
rng = np.random.RandomState(1999)
n_samples = 100
n_features = 3
X = rng.randn(n_samples, n_features)
all_components = []
batch_sizes = np.arange(20, 40, 3)
for batch_size in batch_sizes:
ipca = IncrementalPCA(n_components=None, batch_size=batch_size).fit(X)
all_components.append(ipca.components_)
for i, j in zip(all_components[:-1], all_components[1:]):
assert_almost_equal(i, j, decimal=1)
def test_incremental_pca_partial_fit():
# Test that fit and partial_fit get equivalent results.
rng = np.random.RandomState(1999)
n, p = 50, 3
X = rng.randn(n, p) # spherical data
X[:, 1] *= .00001 # make middle component relatively small
X += [5, 4, 3] # make a large mean
# same check that we can find the original data from the transformed
# signal (since the data is almost of rank n_components)
batch_size = 10
ipca = IncrementalPCA(n_components=2, batch_size=batch_size).fit(X)
pipca = IncrementalPCA(n_components=2, batch_size=batch_size)
# Add one to make sure endpoint is included
batch_itr = np.arange(0, n + 1, batch_size)
for i, j in zip(batch_itr[:-1], batch_itr[1:]):
pipca.partial_fit(X[i:j, :])
assert_almost_equal(ipca.components_, pipca.components_, decimal=3)
def test_incremental_pca_against_pca_iris():
# Test that IncrementalPCA and PCA are approximate (to a sign flip).
X = iris.data
Y_pca = PCA(n_components=2).fit_transform(X)
Y_ipca = IncrementalPCA(n_components=2, batch_size=25).fit_transform(X)
assert_almost_equal(np.abs(Y_pca), np.abs(Y_ipca), 1)
def test_incremental_pca_against_pca_random_data():
# Test that IncrementalPCA and PCA are approximate (to a sign flip).
rng = np.random.RandomState(1999)
n_samples = 100
n_features = 3
X = rng.randn(n_samples, n_features) + 5 * rng.rand(1, n_features)
Y_pca = PCA(n_components=3).fit_transform(X)
Y_ipca = IncrementalPCA(n_components=3, batch_size=25).fit_transform(X)
assert_almost_equal(np.abs(Y_pca), np.abs(Y_ipca), 1)
def test_explained_variances():
# Test that PCA and IncrementalPCA calculations match
X = datasets.make_low_rank_matrix(1000, 100, tail_strength=0.,
effective_rank=10, random_state=1999)
prec = 3
n_samples, n_features = X.shape
for nc in [None, 99]:
pca = PCA(n_components=nc).fit(X)
ipca = IncrementalPCA(n_components=nc, batch_size=100).fit(X)
assert_almost_equal(pca.explained_variance_, ipca.explained_variance_,
decimal=prec)
assert_almost_equal(pca.explained_variance_ratio_,
ipca.explained_variance_ratio_, decimal=prec)
assert_almost_equal(pca.noise_variance_, ipca.noise_variance_,
decimal=prec)
def test_singular_values():
# Check that the IncrementalPCA output has the correct singular values
rng = np.random.RandomState(0)
n_samples = 1000
n_features = 100
X = datasets.make_low_rank_matrix(n_samples, n_features, tail_strength=0.0,
effective_rank=10, random_state=rng)
pca = PCA(n_components=10, svd_solver='full', random_state=rng).fit(X)
ipca = IncrementalPCA(n_components=10, batch_size=100).fit(X)
assert_array_almost_equal(pca.singular_values_, ipca.singular_values_, 2)
# Compare to the Frobenius norm
X_pca = pca.transform(X)
X_ipca = ipca.transform(X)
assert_array_almost_equal(np.sum(pca.singular_values_**2.0),
np.linalg.norm(X_pca, "fro")**2.0, 12)
assert_array_almost_equal(np.sum(ipca.singular_values_**2.0),
np.linalg.norm(X_ipca, "fro")**2.0, 2)
# Compare to the 2-norms of the score vectors
assert_array_almost_equal(pca.singular_values_,
np.sqrt(np.sum(X_pca**2.0, axis=0)), 12)
assert_array_almost_equal(ipca.singular_values_,
np.sqrt(np.sum(X_ipca**2.0, axis=0)), 2)
# Set the singular values and see what we get back
rng = np.random.RandomState(0)
n_samples = 100
n_features = 110
X = datasets.make_low_rank_matrix(n_samples, n_features, tail_strength=0.0,
effective_rank=3, random_state=rng)
pca = PCA(n_components=3, svd_solver='full', random_state=rng)
ipca = IncrementalPCA(n_components=3, batch_size=100)
X_pca = pca.fit_transform(X)
X_pca /= np.sqrt(np.sum(X_pca**2.0, axis=0))
X_pca[:, 0] *= 3.142
X_pca[:, 1] *= 2.718
X_hat = np.dot(X_pca, pca.components_)
pca.fit(X_hat)
ipca.fit(X_hat)
assert_array_almost_equal(pca.singular_values_, [3.142, 2.718, 1.0], 14)
assert_array_almost_equal(ipca.singular_values_, [3.142, 2.718, 1.0], 14)
def test_whitening():
# Test that PCA and IncrementalPCA transforms match to sign flip.
X = datasets.make_low_rank_matrix(1000, 10, tail_strength=0.,
effective_rank=2, random_state=1999)
prec = 3
n_samples, n_features = X.shape
for nc in [None, 9]:
pca = PCA(whiten=True, n_components=nc).fit(X)
ipca = IncrementalPCA(whiten=True, n_components=nc,
batch_size=250).fit(X)
Xt_pca = pca.transform(X)
Xt_ipca = ipca.transform(X)
assert_almost_equal(np.abs(Xt_pca), np.abs(Xt_ipca), decimal=prec)
Xinv_ipca = ipca.inverse_transform(Xt_ipca)
Xinv_pca = pca.inverse_transform(Xt_pca)
assert_almost_equal(X, Xinv_ipca, decimal=prec)
assert_almost_equal(X, Xinv_pca, decimal=prec)
assert_almost_equal(Xinv_pca, Xinv_ipca, decimal=prec)
| bsd-3-clause |
mvanderkolff/xhtml2pdf | test/linkloading.py | 154 | 12563 | # -*- coding: utf-8 -*-
# Copyright 2010 Dirk Holtwick, holtwick.it
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__version__ = "$Revision: 194 $"
__author__ = "$Author: holtwick $"
__date__ = "$Date: 2008-04-18 18:59:53 +0200 (Fr, 18 Apr 2008) $"
import ho.pisa as pisa
import logging
log = logging.getLogger(__file__)
def dummyLoader(name):
return '\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00F\x00\x00\x00\x89\x04\x03\x00\x00\x00c\xbeS\xd6\x00\x00\x000PLTE\x00\x00\x00\n\x06\x04\x18\x14\x0f-&\x1eLB6w`E\x8f\x80q\xb2\x9c\x82\xbe\xa1{\xc7\xb0\x96\xd1\xbd\xa9\xd9\xd0\xc6\xef\xeb\xe6\xf8\xf3\xef\xff\xfb\xf7\xff\xff\xffZ\x83\x0b|\x00\x00\x0c\xedIDATx^u\x97]l\x1bWv\xc7g\xe2`\x81\xbe\xcd%Gr\xd3\xa7P\x12e\xb7\x01\x8a\xd0")E\x01\x02\x8f\xf8!\x8bI\x17\x10\xc5!))5`\xf1C\xb4\xb25`S\xb2l\xb95\x90H\xa4.\xb9/u$K3\xe3\xa2\x80W\x12\xc59L\xf6a\xb3\x8dcN\xd6@\xb7\x1f\x01\x8a\x85\x16\x9b-\xfa\x81M\xb8@\x83l\xd1\xd8\xbc|)\xd0\x97\x82\xea\xb93\x92\xec"\xce\x11 \t3?\xfe\xcf\xff\x9e{\xce\x01(\x1c>7\x18\xfb\xc2\xfaE\xffk_\xb6\x18\xeb\x1e>\x8f\xe92d\xfe%T\xa8\x98\xfa\x07\x1f $<\x0f\xe1\x91\xabT\xc1\xacT\xf2\xbfd\xec\xbb\x98\xdfM\xeb\x86aYP\xfa\xd3\xd6\xf3\x98C[\xa6\xaaU\xa1a5\xe9\x1b\xad\xef\xd0i}\x91\xccy+\xc8X\xf5E\xf6]:\xff0\xd8\x97\xce7\xb9P\xf1\xd1\xb7\x98\xaec\xe7/\xd3\xa1\xeb\x81{\x96e5\xd7.\xb6\x85\xe7\x99aO\x94\xf1R(\xfeC\xce\xd4F\xbf\xc50\x1b\xfa\xefS\xa9\xb2\x12p\x98({\x8eN\x9b\xb1\xbf\xf5O\xa5\xd7\x0b\xb4\xc9\x0f\x96\xec<G\xa7\xc5\x1e\xbf\xfa\xe2b\x90\x16\xb2\x00\x96E\x93O\x9e\xe7\xe77\x8b\xd2@ \xa3\xa7\x96\xe6\r\xab\xb9\x97\xfc\xf6\xb90WV\x0e\x8d(\xa1\xa5dd*\x06PL\xa2\xe7g\xdfw\xba\xe8\xe6o\x06\xc6\xd5\x80\xc7\xe5s\xbb|\xbd\x91\xd2\xb9 \x13\x9e1\xc2\x13\xb5\xfeN\rn\xa5\xd5a\xc5+\xe7\xb7\xf5\xa2\xcbC\xde>a\x9c\xd2\xb5\xad\x07\xdbS\x0b\xb0\xa5z\xeb\x94\xd2y\x80kD\xee<e\x10h\x7fs]\xf4g\xa7\x01\xb6\x12\x91z\xa9P\x8a\\\xcfg\xfdQ\xf6\x0c\x83\xb1CD?\x05\x80\xf2\xa4;z)\xb8\x11\xf1\x11\xf7\xe5\x8b\x9d\xff\xcf\\\x92H\x846\x80f\x91Ys/\x11\xe2r\x85\xfe\x98u\x9e\xf5\xf3_\x1eB\xd2U\x00\x9a\xf3\xc9\xc92\xb9\xbc\xbc\xec\x93N?:\xce\xd59\xect\xdb\xec_\xbdC\xa4\x1f\x99\xb9\x81\x97\xddj\xb9g\x8c\xf4\xaf\xe8\x8f\xba\xc8\x1cwy\xbb\xd3\xb8\xab.\xfb\x0bU\xd03S\xa2\xac\x96\x03k\xe1\x02\xe4\x19\xbe\x12N\xcc|3<U\xd8O\x02\xd4iQ\x12\\j\x81R\x80\xbd\x14\x16\xed\x88\xc1\xfavw&\x02isj\xa2\xa9\xd1\x12\x91\xc4\xfe$\xa5\xe1\xbc\xf2f\xbbs\xcc \xc2\xb2\xc6\xcd\xec\xe8\xfe\xa2\x05\xb4F$A\x0c\x94\n\xee\x9b\xc5\xec_\xb3\xa7\x0c\xfb\xf7q\xad\xb2\xb6b5?h\xea\xe6$\x11\t\xe9\xebs\r\xbdv\xf5\xf6\t\xd3a\xec#5\xb8\x9c\x08\xdf\xb4\xc0J\xc1\x9a$\x11\x7f8\x1c\x01\xb8\xf4\x17\xec\xb0s\xe29\x93\x18\x08\xa5\xcc\xa4eA\xaep\xd7#\xca\xa0\xeb\xd7o\xd5\x8a\xb7\x19;a:.\x1f\x11\xdd7\x1b8R\xcb\x83\xf5\xac<\xbf\x1e.,\xce~<\xff\xe3N\x9b\x1d3m\x0f\xea\x8b\x85{\xd6\xa7\xd6\xc3\xf8e}\xd9\xdc C\xd1\xd9f\xfe\x9d\x16;f\xba\x7f/\x12A\x10\xce\xe2\x88[\xffT\x9a\x99\xc8\x0co\xf5\xf5\x05g\xad\xda\x0fX\xeb\xa4\xceqQ\x10$\xb1\xb7\xd2@\xa86x\x7f8>h._\x9dh4\x8d\xa7:\x8f#X\x13At\xdb3nF\xee\xc8\x19wV^\xf4\x1b\xd6\xdc\xed\x13\xe6w\x01I\x90\x90\xa1F\x05\x99\xdc}B\x88(\x87}\xb7\xac\xda\x99\x13\xe6\xa7\xa1\xf3\x02fs\xa5)\xbd\xd70\r\xceH"\x91\xc2\x15\xc8\x1e\x9f\xbd\xbd\x17\xf7\x8b\x04m\x07\xd2\xb4\x02\xc8 !\xcf\xe1\x83\x0b\xc6\x9d+\\\x87u;\xedl\xdc{^\x12\x05\x89$\x0b\xd40\xef\x12\tu\xd2\x99!\xec\xc4\xab\x17\x8f\x98\xc7/\xc6\x07\xc6$;\xc1YZ\xd1+\n\x11E\x12\xa0\xe0\x1b\x18G\xd3\x0e\xf3\xb57\xeeN\xbc,\x89\xa2@z\xd0\x12]\xc34C\x11d\xbct\x809\x0c\xfbU N"\x1eA\x92\xf0l\x03\xd8]\xeb\nq/\xc9\xb4\xe6\x91\x13\xf2\x97\xc8t\x1dF\xea#\xa2\xc0\xebH\x06)\x98\x8b\xc4\xbd\xd73\x12\x17e\xe5\x956g\xb0C~\x15P\x89(\t<\x08\xe9\xbda\xc0]\xcf\x1f\xed\x91\xbcBd\xe5\rv\xc4\xfc:\xac\xe2Qlf\xc8G\x82\x95\xc6\'\xf1\x18(><\xa6\xfb\xc0\xf6\x83\xcc\xe7\t\xd5G\x1c&\x8d\xc3E\x1b\x0fK\x00\x8a"\xc8\xd9\xde\x93\xfb\xfa\\U\xa7\x08\xcf\x85\x96\xd3\xf9\xb1\xf4\x0f\x9b\x9c\x11\xa4q_\xf8\xe0)3\xa5\x9e\x97\x1c;^\xbaU\xa8Z[1x\x9f\xbcX$3_v9\xd3\xedt?W\xe3^\x14r\xa04T\xc0\xfad\x14\xc6r\x83\xf7\xa5\xc4\x91\x1f\xc6\x90!r\x9fs0\xb1\xa76\xdd\xb0\x1e\xc66\xcf\\\x9ay\xf5\x85\xc4\xc1aW\xb0\x97\xd355A\x88,8AjA\x1d\x1b-S\x98Ly\xe4\xe4m\xe7\xec-\xe6WU\x82%\x94\x1cF\xed\xa1Uk/\xa2\xb9\xb3\xe4T\xee\r\xf6[dZ-\x16@F\xc2{w\x92\x05C#\xd4\x1a\x1f\xae\xcbe\x8f\xff\\\xaf\xe3\xa7\xfd\xf5\xd9\xb2:\x89wu\x14\xb2\xe2\xbeqO_\xa9\x0f\xaf\xfb\xfa\x06\xe7\xae\xb4m?\xff\xdc[\x8a\xa8\xca1$\x8a!\xf2Zc\x13\xea\x17\xd6\\I(\xcd\xb4\x84\xeea\x9b}\xe4\xce\x8f\x85\x13\xce\x8d\x89\xc8HR\x10\xb2P\xa7\x19w\x0c\xf6\x93\xbf\xe4L\xeb\x12\x89\x95\\\x11\xc5\xbe1" *\xca\xc6\x80Ik\xbe\xf0\x02\xd4s\x8f\xb8\x9fo|\xbd\x83\xda\x80+\xc7\xdbPD\x10\x8f\xf8\xc2B?\xadlD\x8b\x00\x943]\xf6?\xa9\xfe\x1e\xdc\xd6\x83\x08\t\xbc\x00\xc3\x8aH\xd2\xfd\x85\x8a_\x1b?a~\xb4\xb0\x99\xf1-g\xfc\x86\x11\x1a\x1a:\xd7G\x00\xce\x8b\xbd\xef\x176a\xed\xb5f\xb3\x9e{\x9b\xe7\xda\xbde\xc1^h\x1cj\x97s*\xc69\x80]B2\x05]\xcb.\x00\xd4\xcb\xafs\x9d\xfb\xef\xe0\x90\xefG\r\x8d\xaa\xe10\x9aA\x8eH\xee\x02-\xab^\x00\xd3f\xba\xbb\xc6\xa7V\xb3\xa9Uu]\xcf\x86\xb1\xda\xf6\x8c\xbe\x90,\xe4\x16]Q\xd08s\xd8\xde\xc5=\xd0\x040\xa0\x01e\x1f\x8e\xab\xcd\x90Hr\xdd\xf4yS\xb0\xc5\x99\xc71\x04@\xdf\x1c6\x00\xeeb\x89$\xde\xb5\xc4C\xfa\x01v\x86\xd2\xb0\x8f\x9e\xbb\xffV\x05\x93\x96\t\x99\x9b\x013DPG$R\xdf\xa9bx\x85\x7f\x12\xac\x07\x9c\xf9\xa4\n:\x8d\xe3h\xcfC.\xcb\xcbH\xdc\x03j\x90\xa2]\xdd\xc0\x9de\xfe\x00\x99T\x15\xa0\xe6!\x0159\x9f\xcf\xc7\t"I\x7f\xb9@\xab\x1a\xa5Z\xf5SK{\x13\x99\xf1*\xd4\xe7\xc8 \x8e\xf0\xe5\x89p\xde#{\xe3\xe9<\xb5\xa3R\xbfgY\x9a\x1f=GQg{\xfe\x06\xc5X\xd0\xebD.\xac\xf3\xff\xcb\xaa\x9a\xac\\\xc0\x9a\x94\\\x8e\x0e\x0f\xcd\xf9\xa4G.P\x8cuU\x8dxw\x0b\r0Koq\x86\x1aO!\x9a\x90\xd3\x1c\xc9*\x84\x8c\x16/7\xabu\xfa\xe7\xc8Di\xc5fL\x8a&\xe9v8\x89\x7fscD\x92\x17&W\x1e\xde\xd3J\xaf\xd8\x0c\xad\xd8\x14\xbe\x03C_T\xf3\xf9\\\xe2eB\xdc\xb1\x84F\xf5\xf0\x1a?{\x84[D\xa4\x01u\x8a\xbf\xf6T\x1e\xb83\xce\x04\xbd\xa6\xaa\xcd\xaf}\x88\xe7:?L\xb5\xfcM\'\x1b`(X*\xf5UQL-\xf5>\x18\xce\x8c$\x99\xc0\x98\x12\xa4tJ\xbd\xac\xeb<\x1bX\xcd\x1d{w\xf2\xae\x1d\xfeI\x94,q\xa6\xa3\x04\n\xebJ\x00\x97.\xcc\xeb\xb4\n\xf0>2|d%\x12\xfbI\xbe\'\x94\xecp\x9d@j]q\x0f\x8d\xd3\x9a?\xa6\x1b\x00\xef\x11I\xe0\xbb\x91\xb8\xa6wj\xd3\xc1 \xcf\xf5sY\xcdM\x11\x12(\x94\x88\\\xb1>K\xbf\xe7\x91\x88\xc8\xb5\xdc\xc9\xd0\xb5\xec\x99\xb78\xf3\xebS\xaa\x8a\x03\x88\x8c\x87\\\xf8\xf4\xfe\xcc5\xb4\x83\x86\x029\xf7\xd4\xe9\x9b\xa1\xa5/\xb9\x9f\xff\x15#jbh(\x92\xc6\x06\t6\xe6.\xfb\xb1\xc4\xfdb\x8fV\xf2\x89\xa2\x1c\xb9\xd2\xe6\xcc\x93\xc9\x80\x8a\x81\xf5\xc5d\xd5D\xed\x0f\xefr\xdd\x0b\xb4<\x89\xae\xc8\x15\xc6\x84\x0e\xeb~\x16Bh\x8a\xa8\xe5\xb0+Y\xd9\xdc\x9b\xb5,S!7hi\nG\x92\x1cp\xe6\xf0\xb7\x1fo\xf7\xf5\xf5\xbdL\x06K\x02\xb9P\x9d\xd8\xbbeY;\xa4\x07\xef,!\x89\xd2\xe9N\xf7\x10\x99v\x13\xee\xa0K\xd2["nZ\x81M\xec\xab;\x9e42\x93\x82$\xbe\xd29\xe4\xcc\x93\x18lp\xd5`\x89\x04\x0bU\x98Z\xb1\x9a\xfex\x9a\x96\xf9\xfa#\xb79\xc3\xba\xc8\x94\xf9|\xde(\x91\xe84@\xb2a}\x9c\x0c\xdb\xa9\x04\xe1\xd4#\x9ba\xc8`k\x89\xb2^"\x91\n\xec\xa7,kiKFF\xc1\x91\xc5m\x88\xcc!{2\x08\xb4\xe4\x11\'\x00sU\xeb\xc5\xd9fx\xa6&\xd3r\x02\'Q|\xb3c3\x87\xed\xbbP_#d\xc6\x98\x93\xd3\xd5\xd5\xc0\xec\xc3\x01(\xcbeu\n\x19r\x91ul\xa6\xb3\x07u\xac\xde\xeeK\x97\x08\xf6Vpv\'\x06\xef\x8e\xe4T\x85\x88\x92\xcc\x1c\xa6\xcb\x90YC\xe6\xb4B\xc2!wa=\x07\xf5w\xc7U,\x0e\x91\xfe\xa4\xd5:a\xcc\xb2O\xde\xed%\x18=t{\x06\xb4w\x83\t\x9f\x84%\xfbY\xf7(\x17\xdbY\x00\xaa\xc8\xbbI>\xea\x11\xdee\x9a\x12T\xb0b\xe2\xf7\x0eP\xc7\xf1|\x9f3$Q\xe4\xdb9J\rd\xce\xe5}\x9c\xf9\xb36;\xd6\xb9?\x83\x8c\x18\xbe\x86\x0c\x19__\x01s\xcd\xbd\xf8\x02\xf6*\x16\x87\xb5\x8f\xfc\xd8:b\xe2\x9a$H\xaedy\x01\xccLOv@\xb2\xdb\x82u\x1d\xa6\xbd\xb3b3s(\xe3N\xa1\x9fm_$\x11\x97D^c\xac\xa0\xe3g\x0f\x00\xeb<4\x87\x1f\x95SK\xbcX\xc3XA\xe9-4s\xc4t\x9f\xf8\x01\xd6\xf0H\xd8\xc7DNfM:\xd7sF\x9d\x12\xe5\x1f?\xcb\x8c\xa2K\x91\xb8\xe6DI\x94\xd3\xa3Z\x9ex\x83\x81\xb1\x84\xf7g\xfcP\xc7L\x8c\xdf\xa9\xf0\xa2\xffUQ\x08\xa4\xce\xe6|$\x91\x95U5\xf8\x08\x99\xae\xc3`\x8f\x99\x94*\x828\x91\x11p\x80\x06}\xe2)\xf5\xd2@^M\x7f\x88\x9e\x9f\xea\xd4)\x9d#\xe2BV\x10\x02\xd9~\\\x18\xd7\xc7\x92TM\xbf\xdd:a\x0e\xbf\x18EfU +\x8b\xc8d\xb0\xbe\xc1\xa4/J\xf37^G\xe4X\xe7q\xcc\x04Z&\xc2K\x0eC\\Y\x1a\xb8`,\x9a\xb7Z\xad\xa7\xb9Fu\x13u\xa4\x97\xb26#}\xcfK#\xd4\xd85W\xdb\xec\x19\xc6\x00\r\xeb\xfaR\xc9a\xc6F\xea\xab\x9aQ\x87U\xf6\x8cN\x0c\x1a\xday"\xfe\x9e\xc3\x90k#\xf52gJWX\x17\xef\xeb\x98\x01\x9a\xc7\xfa\x95\x88\xcd\xcc\x05\xa3U\xce\xd4\xdf\xc0+\xed:3\xf8x\x14\x99u\t\xbd\x12\x11\x19W1\xd0c\xd8\x8c\xcaX\x8b9\xf3\xf5\x1f1\xa8\xd3UIt\xe1p\xb8\xb3~Z\xf1\x91\r\xcd\xa85\xcc\xdc\x01k\x1f33\x00\xda\xaa\xe4\x0e/\x12\x89\xa4\xb1V\x8b\xbe\xa2\x06\xc5\x15(\xf1\x9b?\xb4\x99\xaf\x00\x80\xc6\xdd)\xc8\x12B\xfc\xcd\n\xad\x14s\xbay\x15\'|\x98\xb1\x13\x1d\x03h$U\x1b?\'\x86C\xa4\x01\x94\xee\x8e\xe8p\x15\x1b8\x8c\xd7\xeax\xfe\xeaF\xb5^\xd1k\xe7z\xb13\xae\xfb\x1aVS\xd39\x13\x03\x9ayttv\x16\xa2\x06\x98EQ\xec\x15"xo\xb8\xa1\x00Ftc\xaf\x17\x05\xdf\xec:\xf3\xce\xa2\x94\xc2&\x1f?\x92\xa6\xd5\xcd3M\x1d`\xa62\xbf\x13Df\x03\r\xd9~\xc2i\n\x97H8\xac\x88i\xdd0\x07,]\xdfZ\xd9^\xd9\xcf\x1b\x94\x96n\x1f1\xf7\xbdUXR)}\xcf\xfe\xa27`\x81V6\xf6rZn\x85\xd2\xf2\xf7\x8f\xcf%\xc3\x05\n\xf8@\xec\x1f1`\xee\x9df}j\xc5\xdc\x18Voit\xf5\xfb-\xc7\xf3\xcf\'\x8a\x7f\x00\x1a\xa5\xeb\xc4C&\xe0\xfdY\x0b&\x0bK\x99A\xafQ\xa7k\x07-\x9e\xab\xc3\xc6\xb6\x94\xd3\x00uZ\x96T%X\xd9\x8b!\x93t\'\x06\xaf\x83I\xd7o\xb7\x9c\\\x91\xc5p\xbfa\xeat]I\xff\xc8O\xf7\x83M\xc8\x10w\xc0\xbb\xb4b\xd2\xf2\xa8\xc3\xfc\xe7|\x94\xc6\xa7ML\x86_m\xb3\x14\x96\x8cz9G\xc8\xd9\xaca\x96\xe6C\x1fr\xa6\xf5@+\x18\xa5A\xd3\x04\x9a\xed\xd9\xc8j\xb0\x1f\xa6\xd4X"\xeei0\xd6\n\xea\x01g\xday\x8dB=~\x06\x1d\x95zV\xb7\xab`\xea\x1aB\xba\xc9\x1d\x06\xdf\xb6\xeb\xf3\x9b\n4\xf9N\xd8\xc6c(Y\xb3\x02{\xf3\x0f\n\x15@\xc3\x18\xfeN\xd7f(>\xc0\x9e\xbf3\x0e\x1a\xda\xd2\xa1\xe6\xc9O\xa0\xa8\x81H\xeeb\xdb\xd6\xf9G.\x0c\xb0zU\x9e\x81\xcd\xdf7\x00\x96<\xde( \xab\xd1l\xe0\xc0\xe9\xc3\x8f\x90G\xa9\xf8\xc6\xbc\x1fv\xe5J\xb5\xba\xd9#\'\x81K\xaf\xc5>hu\xed>\xfc)\xe5a\x8cm\xc2F\xcc\x1cZ\xde\xdc\x9f\x0ef\xd1\xf8:-\xfd\xd5\x01;\xea\xc3S\xd4\x8e\xdd\xe5\x19\x80\x86\x8fd\xca\x13\xd1\x1e\xa3\x9e\x0fEX\x1b\x7f\x1c\x1dU-\xd8\xd9F5t\x95 \xa1\xa5\x89\xa8:\xddTg\xf9N\xc5\xc9\xb1\x99\xc7J\xc4\x16\x9a\xd6\xd0\x95\x99 J4\xb5\x7f\xab\x85D\x8b\xffr\xf6<{\xb8\x1d\x0e\xf9\xa9\x13\xb0GnZ\xd6/Z\xfc%\xb3\x99\xae\xcd0f\xe1c\x1e\x9f\r\r\x05\xad\x16{&\x10\xc0\xf8?Z\n\xf1+\xfb\x81\xd5F\x00\x00\x00\x00IEND\xaeB`\x82'
class myLinkLoader:
"""
This object is just a wrapper to track additional informations
and handle temporary files after they are not needed any more.
"""
def __init__(self, **kw):
"""
The self.kw could be used in getFileName if you like
"""
self.kw = kw
self.tmpFileList = []
def __del__(self):
for path in self.tmpFileList:
os.remove(path)
self.tmpFileList = []
def getFileName(self, path, relative=None):
import os
import tempfile
log.info("myLinkLoader.getFileName: %r %r %r", path, relative, self.kw)
try:
if "." in path:
new_suffix = "." + path.split(".")[-1].lower()
if new_suffix in (".css", ".gif", ".jpg", ".png"):
suffix = new_suffix
tmpPath = tempfile.mktemp(prefix="pisa-", suffix = suffix)
tmpFile = file(tmpPath, "wb")
try:
# Here you may add your own stuff
tmpFile.write(dummyLoader(path))
finally:
tmpFile.close()
self.tmpFileList.append(tmpPath)
return tmpPath
except Exception, e:
log.exception("myLinkLoader.getFileName")
return None
def helloWorld():
filename = __file__ + ".pdf"
lc = myLinkLoader(database="some_name", port=666).getFileName
pdf = pisa.CreatePDF(
u"""
<p>
Hello <strong>World</strong>
<p>
<img src="apath/some.png">
""",
file(filename, "wb"),
link_callback = lc,
)
if not pdf.err:
pisa.startViewer(filename)
if __name__=="__main__":
pisa.showLogging()
helloWorld()
# print repr(open("img/denker.png", "rb").read())
| apache-2.0 |
apple/llvm-project | lldb/test/API/functionalities/dynamic_value_child_count/TestDynamicValueChildCount.py | 4 | 3113 | """
Test that dynamic values update their child count correctly
"""
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class DynamicValueChildCountTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
def setUp(self):
# Call super's setUp().
TestBase.setUp(self)
# Find the line number to break for main.c.
self.main_third_call_line = line_number(
'pass-to-base.cpp', '// Break here and check b has 0 children')
self.main_fourth_call_line = line_number(
'pass-to-base.cpp', '// Break here and check b still has 0 children')
self.main_fifth_call_line = line_number(
'pass-to-base.cpp', '// Break here and check b has one child now')
self.main_sixth_call_line = line_number(
'pass-to-base.cpp', '// Break here and check b has 0 children again')
@add_test_categories(['pyapi'])
@expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24663")
def test_get_dynamic_vals(self):
"""Test fetching C++ dynamic values from pointers & references."""
"""Get argument vals for the call stack when stopped on a breakpoint."""
self.build(dictionary=self.getBuildFlags())
exe = self.getBuildArtifact("a.out")
# Create a target from the debugger.
target = self.dbg.CreateTarget(exe)
self.assertTrue(target, VALID_TARGET)
# Set up our breakpoints:
third_call_bpt = target.BreakpointCreateByLocation(
'pass-to-base.cpp', self.main_third_call_line)
self.assertTrue(third_call_bpt,
VALID_BREAKPOINT)
fourth_call_bpt = target.BreakpointCreateByLocation(
'pass-to-base.cpp', self.main_fourth_call_line)
self.assertTrue(fourth_call_bpt,
VALID_BREAKPOINT)
fifth_call_bpt = target.BreakpointCreateByLocation(
'pass-to-base.cpp', self.main_fifth_call_line)
self.assertTrue(fifth_call_bpt,
VALID_BREAKPOINT)
sixth_call_bpt = target.BreakpointCreateByLocation(
'pass-to-base.cpp', self.main_sixth_call_line)
self.assertTrue(sixth_call_bpt,
VALID_BREAKPOINT)
# Now launch the process, and do not stop at the entry point.
process = target.LaunchSimple(
None, None, self.get_process_working_directory())
self.assertEquals(process.GetState(), lldb.eStateStopped,
PROCESS_STOPPED)
b = self.frame().FindVariable("b").GetDynamicValue(lldb.eDynamicCanRunTarget)
self.assertEquals(b.GetNumChildren(), 0, "b has 0 children")
self.runCmd("continue")
self.assertEquals(b.GetNumChildren(), 0, "b still has 0 children")
self.runCmd("continue")
self.assertNotEqual(b.GetNumChildren(), 0, "b now has 1 child")
self.runCmd("continue")
self.assertEqual(
b.GetNumChildren(), 0,
"b didn't go back to 0 children")
| apache-2.0 |
gchp/django | tests/expressions/models.py | 261 | 1925 | """
Tests for F() query expression syntax.
"""
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Employee(models.Model):
firstname = models.CharField(max_length=50)
lastname = models.CharField(max_length=50)
salary = models.IntegerField(blank=True, null=True)
def __str__(self):
return '%s %s' % (self.firstname, self.lastname)
@python_2_unicode_compatible
class Company(models.Model):
name = models.CharField(max_length=100)
num_employees = models.PositiveIntegerField()
num_chairs = models.PositiveIntegerField()
ceo = models.ForeignKey(
Employee,
models.CASCADE,
related_name='company_ceo_set')
point_of_contact = models.ForeignKey(
Employee,
models.SET_NULL,
related_name='company_point_of_contact_set',
null=True)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Number(models.Model):
integer = models.BigIntegerField(db_column='the_integer')
float = models.FloatField(null=True, db_column='the_float')
def __str__(self):
return '%i, %.3f' % (self.integer, self.float)
class Experiment(models.Model):
name = models.CharField(max_length=24)
assigned = models.DateField()
completed = models.DateField()
estimated_time = models.DurationField()
start = models.DateTimeField()
end = models.DateTimeField()
class Meta:
ordering = ('name',)
def duration(self):
return self.end - self.start
@python_2_unicode_compatible
class Time(models.Model):
time = models.TimeField(null=True)
def __str__(self):
return "%s" % self.time
@python_2_unicode_compatible
class UUID(models.Model):
uuid = models.UUIDField(null=True)
def __str__(self):
return "%s" % self.uuid
| bsd-3-clause |
8l/beri | cheritest/trunk/tests/fpu/test_fpu_x_disabled.py | 2 | 2018 | #-
# Copyright (c) 2013 Michael Roe
# All rights reserved.
#
# This software was developed by SRI International and the University of
# Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237
# ("CTSRD"), as part of the DARPA CRASH research programme.
#
# @BERI_LICENSE_HEADER_START@
#
# Licensed to BERI Open Systems C.I.C. (BERI) under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. BERI licenses this
# file to you under the BERI Hardware-Software License, Version 1.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.beri-open-systems.org/legal/license-1-0.txt
#
# Unless required by applicable law or agreed to in writing, Work distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
#
# @BERI_LICENSE_HEADER_END@
#
#
# Test floating point division of a small number by itself
#
from beritest_tools import BaseBERITestCase
from nose.plugins.attrib import attr
class test_fpu_x_disabled(BaseBERITestCase):
def test_fpu_x_disabled_1(self):
'''Test that a floating point operation raises an exception if the FPU is disabled'''
self.assertRegisterEqual(self.MIPS.a2, 1, "A floating point operation with the FPU disabled did not raise an exception")
def test_fpu_x_disabled_2(self):
'''Test that CP0.cause.ExcCode is set when FPU is disabled'''
self.assertRegisterEqual(self.MIPS.a3, 11, "CP0.cause.exccode was not set to coprocessor unusable when the FPU was disabled")
def test_fpu_x_disabled_3(self):
'''Test that CP0.cause.ce is set when FPU is disabled'''
self.assertRegisterEqual(self.MIPS.a4, 1, "CP0.cause.ce was not set to 1 when the FPU was disabled")
| apache-2.0 |
joshrule/LOTlib | LOTlib/Inference/Samplers/MemoizedMHSampler.py | 2 | 1277 | from cachetools import LRUCache
from LOTlib.Miscellaneous import Infinity
from MetropolisHastings import MHSampler
class MemoizedMHSampler(MHSampler):
"""
Same as MHSampler, but the values of compute_posterior are cached via LRUCache
"""
def __init__(self, h0, data, memoize=Infinity, **kwargs):
MHSampler.__init__(self, h0, data, **kwargs)
# self.mem stores return of compute_posterior
self.mem = LRUCache(maxsize=memoize)
def compute_posterior(self, h, data, shortcut=-Infinity):
if h in self.mem:
ret = self.mem[h]
h.posterior_score = ret # set this because it may not be set
return ret
else:
ret = MHSampler.compute_posterior(self, h, data, shortcut=-Infinity) # calls update to posterior counter
self.mem[h] = ret
return ret
if __name__ == "__main__":
from LOTlib.Examples.Number.Global import generate_data, NumberExpression, grammar
data = generate_data(100)
h0 = NumberExpression(grammar)
sampler = MemoizedMHSampler(h0, data, steps=1000)
for h in sampler:
pass #print q(get_knower_pattern(h)), h.posterior_score, h.prior, h.likelihood, q(h), sampler.acceptance_count, sampler.acceptance_ratio()
| gpl-3.0 |
rdowinton/scrapy | tests/test_middleware.py | 30 | 2326 | from twisted.trial import unittest
from scrapy.settings import Settings
from scrapy.exceptions import NotConfigured
from scrapy.middleware import MiddlewareManager
class M1(object):
def open_spider(self, spider):
pass
def close_spider(self, spider):
pass
def process(self, response, request, spider):
pass
class M2(object):
def open_spider(self, spider):
pass
def close_spider(self, spider):
pass
pass
class M3(object):
def process(self, response, request, spider):
pass
class MOff(object):
def open_spider(self, spider):
pass
def close_spider(self, spider):
pass
def __init__(self):
raise NotConfigured
class TestMiddlewareManager(MiddlewareManager):
@classmethod
def _get_mwlist_from_settings(cls, settings):
return ['tests.test_middleware.%s' % x for x in ['M1', 'MOff', 'M3']]
def _add_middleware(self, mw):
super(TestMiddlewareManager, self)._add_middleware(mw)
if hasattr(mw, 'process'):
self.methods['process'].append(mw.process)
class MiddlewareManagerTest(unittest.TestCase):
def test_init(self):
m1, m2, m3 = M1(), M2(), M3()
mwman = TestMiddlewareManager(m1, m2, m3)
self.assertEqual(mwman.methods['open_spider'], [m1.open_spider, m2.open_spider])
self.assertEqual(mwman.methods['close_spider'], [m2.close_spider, m1.close_spider])
self.assertEqual(mwman.methods['process'], [m1.process, m3.process])
def test_methods(self):
mwman = TestMiddlewareManager(M1(), M2(), M3())
self.assertEqual([x.im_class for x in mwman.methods['open_spider']],
[M1, M2])
self.assertEqual([x.im_class for x in mwman.methods['close_spider']],
[M2, M1])
self.assertEqual([x.im_class for x in mwman.methods['process']],
[M1, M3])
def test_enabled(self):
m1, m2, m3 = M1(), M2(), M3()
mwman = MiddlewareManager(m1, m2, m3)
self.assertEqual(mwman.middlewares, (m1, m2, m3))
def test_enabled_from_settings(self):
settings = Settings()
mwman = TestMiddlewareManager.from_settings(settings)
classes = [x.__class__ for x in mwman.middlewares]
self.assertEqual(classes, [M1, M3])
| bsd-3-clause |
kmad1729/website | django/contrib/localflavor/se/forms.py | 311 | 5623 | # -*- coding: utf-8 -*-
"""
Swedish specific Form helpers
"""
import re
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.core.validators import EMPTY_VALUES
from django.contrib.localflavor.se.utils import (id_number_checksum,
validate_id_birthday, format_personal_id_number, valid_organisation,
format_organisation_number)
__all__ = ('SECountySelect', 'SEOrganisationNumberField',
'SEPersonalIdentityNumberField', 'SEPostalCodeField')
SWEDISH_ID_NUMBER = re.compile(r'^(?P<century>\d{2})?(?P<year>\d{2})(?P<month>\d{2})(?P<day>\d{2})(?P<sign>[\-+])?(?P<serial>\d{3})(?P<checksum>\d)$')
SE_POSTAL_CODE = re.compile(r'^[1-9]\d{2} ?\d{2}$')
class SECountySelect(forms.Select):
"""
A Select form widget that uses a list of the Swedish counties (län) as its
choices.
The cleaned value is the official county code -- see
http://en.wikipedia.org/wiki/Counties_of_Sweden for a list.
"""
def __init__(self, attrs=None):
from se_counties import COUNTY_CHOICES
super(SECountySelect, self).__init__(attrs=attrs,
choices=COUNTY_CHOICES)
class SEOrganisationNumberField(forms.CharField):
"""
A form field that validates input as a Swedish organisation number
(organisationsnummer).
It accepts the same input as SEPersonalIdentityField (for sole
proprietorships (enskild firma). However, co-ordination numbers are not
accepted.
It also accepts ordinary Swedish organisation numbers with the format
NNNNNNNNNN.
The return value will be YYYYMMDDXXXX for sole proprietors, and NNNNNNNNNN
for other organisations.
"""
default_error_messages = {
'invalid': _('Enter a valid Swedish organisation number.'),
}
def clean(self, value):
value = super(SEOrganisationNumberField, self).clean(value)
if value in EMPTY_VALUES:
return u''
match = SWEDISH_ID_NUMBER.match(value)
if not match:
raise forms.ValidationError(self.error_messages['invalid'])
gd = match.groupdict()
# Compare the calculated value with the checksum
if id_number_checksum(gd) != int(gd['checksum']):
raise forms.ValidationError(self.error_messages['invalid'])
# First: check if this is a real organisation_number
if valid_organisation(gd):
return format_organisation_number(gd)
# Is this a single properitor (enskild firma)?
try:
birth_day = validate_id_birthday(gd, False)
return format_personal_id_number(birth_day, gd)
except ValueError:
raise forms.ValidationError(self.error_messages['invalid'])
class SEPersonalIdentityNumberField(forms.CharField):
"""
A form field that validates input as a Swedish personal identity number
(personnummer).
The correct formats are YYYYMMDD-XXXX, YYYYMMDDXXXX, YYMMDD-XXXX,
YYMMDDXXXX and YYMMDD+XXXX.
A + indicates that the person is older than 100 years, which will be taken
into consideration when the date is validated.
The checksum will be calculated and checked. The birth date is checked to
be a valid date.
By default, co-ordination numbers (samordningsnummer) will be accepted. To
only allow real personal identity numbers, pass the keyword argument
coordination_number=False to the constructor.
The cleaned value will always have the format YYYYMMDDXXXX.
"""
def __init__(self, coordination_number=True, *args, **kwargs):
self.coordination_number = coordination_number
super(SEPersonalIdentityNumberField, self).__init__(*args, **kwargs)
default_error_messages = {
'invalid': _('Enter a valid Swedish personal identity number.'),
'coordination_number': _('Co-ordination numbers are not allowed.'),
}
def clean(self, value):
value = super(SEPersonalIdentityNumberField, self).clean(value)
if value in EMPTY_VALUES:
return u''
match = SWEDISH_ID_NUMBER.match(value)
if match is None:
raise forms.ValidationError(self.error_messages['invalid'])
gd = match.groupdict()
# compare the calculated value with the checksum
if id_number_checksum(gd) != int(gd['checksum']):
raise forms.ValidationError(self.error_messages['invalid'])
# check for valid birthday
try:
birth_day = validate_id_birthday(gd)
except ValueError:
raise forms.ValidationError(self.error_messages['invalid'])
# make sure that co-ordination numbers do not pass if not allowed
if not self.coordination_number and int(gd['day']) > 60:
raise forms.ValidationError(self.error_messages['coordination_number'])
return format_personal_id_number(birth_day, gd)
class SEPostalCodeField(forms.RegexField):
"""
A form field that validates input as a Swedish postal code (postnummer).
Valid codes consist of five digits (XXXXX). The number can optionally be
formatted with a space after the third digit (XXX XX).
The cleaned value will never contain the space.
"""
default_error_messages = {
'invalid': _('Enter a Swedish postal code in the format XXXXX.'),
}
def __init__(self, *args, **kwargs):
super(SEPostalCodeField, self).__init__(SE_POSTAL_CODE, *args, **kwargs)
def clean(self, value):
return super(SEPostalCodeField, self).clean(value).replace(' ', '')
| bsd-3-clause |
rubencabrera/odoo | addons/base_import_module/tests/test_module/__openerp__.py | 377 | 1290 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013-Today OpenERP SA (<http://www.openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Test Module',
'category': 'Website',
'summary': 'Custom',
'version': '1.0',
'description': """
Test
""",
'author': 'OpenERP SA',
'depends': ['website'],
'data': [
'test.xml',
],
'installable': True,
'application': True,
}
| agpl-3.0 |
vjpai/grpc | src/python/grpcio_tests/tests_aio/interop/methods.py | 8 | 17741 | # Copyright 2019 The gRPC Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implementations of interoperability test methods."""
import argparse
import asyncio
import collections
import datetime
import enum
import inspect
import json
import os
import threading
import time
from typing import Any, Optional, Union
import grpc
from google import auth as google_auth
from google.auth import environment_vars as google_auth_environment_vars
from google.auth.transport import grpc as google_auth_transport_grpc
from google.auth.transport import requests as google_auth_transport_requests
from grpc.experimental import aio
from src.proto.grpc.testing import empty_pb2, messages_pb2, test_pb2_grpc
_INITIAL_METADATA_KEY = "x-grpc-test-echo-initial"
_TRAILING_METADATA_KEY = "x-grpc-test-echo-trailing-bin"
async def _expect_status_code(call: aio.Call,
expected_code: grpc.StatusCode) -> None:
code = await call.code()
if code != expected_code:
raise ValueError('expected code %s, got %s' %
(expected_code, await call.code()))
async def _expect_status_details(call: aio.Call, expected_details: str) -> None:
details = await call.details()
if details != expected_details:
raise ValueError('expected message %s, got %s' %
(expected_details, await call.details()))
async def _validate_status_code_and_details(call: aio.Call,
expected_code: grpc.StatusCode,
expected_details: str) -> None:
await _expect_status_code(call, expected_code)
await _expect_status_details(call, expected_details)
def _validate_payload_type_and_length(response: Union[
messages_pb2.SimpleResponse, messages_pb2.StreamingOutputCallResponse],
expected_type: Any,
expected_length: int) -> None:
if response.payload.type is not expected_type:
raise ValueError('expected payload type %s, got %s' %
(expected_type, type(response.payload.type)))
elif len(response.payload.body) != expected_length:
raise ValueError('expected payload body size %d, got %d' %
(expected_length, len(response.payload.body)))
async def _large_unary_common_behavior(
stub: test_pb2_grpc.TestServiceStub, fill_username: bool,
fill_oauth_scope: bool, call_credentials: Optional[grpc.CallCredentials]
) -> messages_pb2.SimpleResponse:
size = 314159
request = messages_pb2.SimpleRequest(
response_type=messages_pb2.COMPRESSABLE,
response_size=size,
payload=messages_pb2.Payload(body=b'\x00' * 271828),
fill_username=fill_username,
fill_oauth_scope=fill_oauth_scope)
response = await stub.UnaryCall(request, credentials=call_credentials)
_validate_payload_type_and_length(response, messages_pb2.COMPRESSABLE, size)
return response
async def _empty_unary(stub: test_pb2_grpc.TestServiceStub) -> None:
response = await stub.EmptyCall(empty_pb2.Empty())
if not isinstance(response, empty_pb2.Empty):
raise TypeError('response is of type "%s", not empty_pb2.Empty!' %
type(response))
async def _large_unary(stub: test_pb2_grpc.TestServiceStub) -> None:
await _large_unary_common_behavior(stub, False, False, None)
async def _client_streaming(stub: test_pb2_grpc.TestServiceStub) -> None:
payload_body_sizes = (
27182,
8,
1828,
45904,
)
async def request_gen():
for size in payload_body_sizes:
yield messages_pb2.StreamingInputCallRequest(
payload=messages_pb2.Payload(body=b'\x00' * size))
response = await stub.StreamingInputCall(request_gen())
if response.aggregated_payload_size != sum(payload_body_sizes):
raise ValueError('incorrect size %d!' %
response.aggregated_payload_size)
async def _server_streaming(stub: test_pb2_grpc.TestServiceStub) -> None:
sizes = (
31415,
9,
2653,
58979,
)
request = messages_pb2.StreamingOutputCallRequest(
response_type=messages_pb2.COMPRESSABLE,
response_parameters=(
messages_pb2.ResponseParameters(size=sizes[0]),
messages_pb2.ResponseParameters(size=sizes[1]),
messages_pb2.ResponseParameters(size=sizes[2]),
messages_pb2.ResponseParameters(size=sizes[3]),
))
call = stub.StreamingOutputCall(request)
for size in sizes:
response = await call.read()
_validate_payload_type_and_length(response, messages_pb2.COMPRESSABLE,
size)
async def _ping_pong(stub: test_pb2_grpc.TestServiceStub) -> None:
request_response_sizes = (
31415,
9,
2653,
58979,
)
request_payload_sizes = (
27182,
8,
1828,
45904,
)
call = stub.FullDuplexCall()
for response_size, payload_size in zip(request_response_sizes,
request_payload_sizes):
request = messages_pb2.StreamingOutputCallRequest(
response_type=messages_pb2.COMPRESSABLE,
response_parameters=(messages_pb2.ResponseParameters(
size=response_size),),
payload=messages_pb2.Payload(body=b'\x00' * payload_size))
await call.write(request)
response = await call.read()
_validate_payload_type_and_length(response, messages_pb2.COMPRESSABLE,
response_size)
await call.done_writing()
await _validate_status_code_and_details(call, grpc.StatusCode.OK, '')
async def _cancel_after_begin(stub: test_pb2_grpc.TestServiceStub):
call = stub.StreamingInputCall()
call.cancel()
if not call.cancelled():
raise ValueError('expected cancelled method to return True')
code = await call.code()
if code is not grpc.StatusCode.CANCELLED:
raise ValueError('expected status code CANCELLED')
async def _cancel_after_first_response(stub: test_pb2_grpc.TestServiceStub):
request_response_sizes = (
31415,
9,
2653,
58979,
)
request_payload_sizes = (
27182,
8,
1828,
45904,
)
call = stub.FullDuplexCall()
response_size = request_response_sizes[0]
payload_size = request_payload_sizes[0]
request = messages_pb2.StreamingOutputCallRequest(
response_type=messages_pb2.COMPRESSABLE,
response_parameters=(messages_pb2.ResponseParameters(
size=response_size),),
payload=messages_pb2.Payload(body=b'\x00' * payload_size))
await call.write(request)
await call.read()
call.cancel()
try:
await call.read()
except asyncio.CancelledError:
assert await call.code() is grpc.StatusCode.CANCELLED
else:
raise ValueError('expected call to be cancelled')
async def _timeout_on_sleeping_server(stub: test_pb2_grpc.TestServiceStub):
request_payload_size = 27182
time_limit = datetime.timedelta(seconds=1)
call = stub.FullDuplexCall(timeout=time_limit.total_seconds())
request = messages_pb2.StreamingOutputCallRequest(
response_type=messages_pb2.COMPRESSABLE,
payload=messages_pb2.Payload(body=b'\x00' * request_payload_size),
response_parameters=(messages_pb2.ResponseParameters(
interval_us=int(time_limit.total_seconds() * 2 * 10**6)),))
await call.write(request)
await call.done_writing()
try:
await call.read()
except aio.AioRpcError as rpc_error:
if rpc_error.code() is not grpc.StatusCode.DEADLINE_EXCEEDED:
raise
else:
raise ValueError('expected call to exceed deadline')
async def _empty_stream(stub: test_pb2_grpc.TestServiceStub):
call = stub.FullDuplexCall()
await call.done_writing()
assert await call.read() == aio.EOF
async def _status_code_and_message(stub: test_pb2_grpc.TestServiceStub):
details = 'test status message'
status = grpc.StatusCode.UNKNOWN # code = 2
# Test with a UnaryCall
request = messages_pb2.SimpleRequest(
response_type=messages_pb2.COMPRESSABLE,
response_size=1,
payload=messages_pb2.Payload(body=b'\x00'),
response_status=messages_pb2.EchoStatus(code=status.value[0],
message=details))
call = stub.UnaryCall(request)
await _validate_status_code_and_details(call, status, details)
# Test with a FullDuplexCall
call = stub.FullDuplexCall()
request = messages_pb2.StreamingOutputCallRequest(
response_type=messages_pb2.COMPRESSABLE,
response_parameters=(messages_pb2.ResponseParameters(size=1),),
payload=messages_pb2.Payload(body=b'\x00'),
response_status=messages_pb2.EchoStatus(code=status.value[0],
message=details))
await call.write(request) # sends the initial request.
await call.done_writing()
try:
await call.read()
except aio.AioRpcError as rpc_error:
assert rpc_error.code() == status
await _validate_status_code_and_details(call, status, details)
async def _unimplemented_method(stub: test_pb2_grpc.TestServiceStub):
call = stub.UnimplementedCall(empty_pb2.Empty())
await _expect_status_code(call, grpc.StatusCode.UNIMPLEMENTED)
async def _unimplemented_service(stub: test_pb2_grpc.UnimplementedServiceStub):
call = stub.UnimplementedCall(empty_pb2.Empty())
await _expect_status_code(call, grpc.StatusCode.UNIMPLEMENTED)
async def _custom_metadata(stub: test_pb2_grpc.TestServiceStub):
initial_metadata_value = "test_initial_metadata_value"
trailing_metadata_value = b"\x0a\x0b\x0a\x0b\x0a\x0b"
metadata = aio.Metadata(
(_INITIAL_METADATA_KEY, initial_metadata_value),
(_TRAILING_METADATA_KEY, trailing_metadata_value),
)
async def _validate_metadata(call):
initial_metadata = await call.initial_metadata()
if initial_metadata[_INITIAL_METADATA_KEY] != initial_metadata_value:
raise ValueError('expected initial metadata %s, got %s' %
(initial_metadata_value,
initial_metadata[_INITIAL_METADATA_KEY]))
trailing_metadata = await call.trailing_metadata()
if trailing_metadata[_TRAILING_METADATA_KEY] != trailing_metadata_value:
raise ValueError('expected trailing metadata %s, got %s' %
(trailing_metadata_value,
trailing_metadata[_TRAILING_METADATA_KEY]))
# Testing with UnaryCall
request = messages_pb2.SimpleRequest(
response_type=messages_pb2.COMPRESSABLE,
response_size=1,
payload=messages_pb2.Payload(body=b'\x00'))
call = stub.UnaryCall(request, metadata=metadata)
await _validate_metadata(call)
# Testing with FullDuplexCall
call = stub.FullDuplexCall(metadata=metadata)
request = messages_pb2.StreamingOutputCallRequest(
response_type=messages_pb2.COMPRESSABLE,
response_parameters=(messages_pb2.ResponseParameters(size=1),))
await call.write(request)
await call.read()
await call.done_writing()
await _validate_metadata(call)
async def _compute_engine_creds(stub: test_pb2_grpc.TestServiceStub,
args: argparse.Namespace):
response = await _large_unary_common_behavior(stub, True, True, None)
if args.default_service_account != response.username:
raise ValueError('expected username %s, got %s' %
(args.default_service_account, response.username))
async def _oauth2_auth_token(stub: test_pb2_grpc.TestServiceStub,
args: argparse.Namespace):
json_key_filename = os.environ[google_auth_environment_vars.CREDENTIALS]
wanted_email = json.load(open(json_key_filename, 'r'))['client_email']
response = await _large_unary_common_behavior(stub, True, True, None)
if wanted_email != response.username:
raise ValueError('expected username %s, got %s' %
(wanted_email, response.username))
if args.oauth_scope.find(response.oauth_scope) == -1:
raise ValueError(
'expected to find oauth scope "{}" in received "{}"'.format(
response.oauth_scope, args.oauth_scope))
async def _jwt_token_creds(stub: test_pb2_grpc.TestServiceStub):
json_key_filename = os.environ[google_auth_environment_vars.CREDENTIALS]
wanted_email = json.load(open(json_key_filename, 'r'))['client_email']
response = await _large_unary_common_behavior(stub, True, False, None)
if wanted_email != response.username:
raise ValueError('expected username %s, got %s' %
(wanted_email, response.username))
async def _per_rpc_creds(stub: test_pb2_grpc.TestServiceStub,
args: argparse.Namespace):
json_key_filename = os.environ[google_auth_environment_vars.CREDENTIALS]
wanted_email = json.load(open(json_key_filename, 'r'))['client_email']
google_credentials, unused_project_id = google_auth.default(
scopes=[args.oauth_scope])
call_credentials = grpc.metadata_call_credentials(
google_auth_transport_grpc.AuthMetadataPlugin(
credentials=google_credentials,
request=google_auth_transport_requests.Request()))
response = await _large_unary_common_behavior(stub, True, False,
call_credentials)
if wanted_email != response.username:
raise ValueError('expected username %s, got %s' %
(wanted_email, response.username))
async def _special_status_message(stub: test_pb2_grpc.TestServiceStub):
details = b'\t\ntest with whitespace\r\nand Unicode BMP \xe2\x98\xba and non-BMP \xf0\x9f\x98\x88\t\n'.decode(
'utf-8')
status = grpc.StatusCode.UNKNOWN # code = 2
# Test with a UnaryCall
request = messages_pb2.SimpleRequest(
response_type=messages_pb2.COMPRESSABLE,
response_size=1,
payload=messages_pb2.Payload(body=b'\x00'),
response_status=messages_pb2.EchoStatus(code=status.value[0],
message=details))
call = stub.UnaryCall(request)
await _validate_status_code_and_details(call, status, details)
@enum.unique
class TestCase(enum.Enum):
EMPTY_UNARY = 'empty_unary'
LARGE_UNARY = 'large_unary'
SERVER_STREAMING = 'server_streaming'
CLIENT_STREAMING = 'client_streaming'
PING_PONG = 'ping_pong'
CANCEL_AFTER_BEGIN = 'cancel_after_begin'
CANCEL_AFTER_FIRST_RESPONSE = 'cancel_after_first_response'
TIMEOUT_ON_SLEEPING_SERVER = 'timeout_on_sleeping_server'
EMPTY_STREAM = 'empty_stream'
STATUS_CODE_AND_MESSAGE = 'status_code_and_message'
UNIMPLEMENTED_METHOD = 'unimplemented_method'
UNIMPLEMENTED_SERVICE = 'unimplemented_service'
CUSTOM_METADATA = "custom_metadata"
COMPUTE_ENGINE_CREDS = 'compute_engine_creds'
OAUTH2_AUTH_TOKEN = 'oauth2_auth_token'
JWT_TOKEN_CREDS = 'jwt_token_creds'
PER_RPC_CREDS = 'per_rpc_creds'
SPECIAL_STATUS_MESSAGE = 'special_status_message'
_TEST_CASE_IMPLEMENTATION_MAPPING = {
TestCase.EMPTY_UNARY: _empty_unary,
TestCase.LARGE_UNARY: _large_unary,
TestCase.SERVER_STREAMING: _server_streaming,
TestCase.CLIENT_STREAMING: _client_streaming,
TestCase.PING_PONG: _ping_pong,
TestCase.CANCEL_AFTER_BEGIN: _cancel_after_begin,
TestCase.CANCEL_AFTER_FIRST_RESPONSE: _cancel_after_first_response,
TestCase.TIMEOUT_ON_SLEEPING_SERVER: _timeout_on_sleeping_server,
TestCase.EMPTY_STREAM: _empty_stream,
TestCase.STATUS_CODE_AND_MESSAGE: _status_code_and_message,
TestCase.UNIMPLEMENTED_METHOD: _unimplemented_method,
TestCase.UNIMPLEMENTED_SERVICE: _unimplemented_service,
TestCase.CUSTOM_METADATA: _custom_metadata,
TestCase.COMPUTE_ENGINE_CREDS: _compute_engine_creds,
TestCase.OAUTH2_AUTH_TOKEN: _oauth2_auth_token,
TestCase.JWT_TOKEN_CREDS: _jwt_token_creds,
TestCase.PER_RPC_CREDS: _per_rpc_creds,
TestCase.SPECIAL_STATUS_MESSAGE: _special_status_message,
}
async def test_interoperability(
case: TestCase,
stub: test_pb2_grpc.TestServiceStub,
args: Optional[argparse.Namespace] = None) -> None:
method = _TEST_CASE_IMPLEMENTATION_MAPPING.get(case)
if method is None:
raise NotImplementedError(f'Test case "{case}" not implemented!')
else:
num_params = len(inspect.signature(method).parameters)
if num_params == 1:
await method(stub)
elif num_params == 2:
if args is not None:
await method(stub, args)
else:
raise ValueError(f'Failed to run case [{case}]: args is None')
else:
raise ValueError(f'Invalid number of parameters [{num_params}]')
| apache-2.0 |
JonathanLevi/fabric | bddtests/steps/sdk_impl.py | 35 | 1364 | import os
import re
import time
import copy
import base64
from datetime import datetime, timedelta
import sys, requests, json
import bdd_test_util
from grpc.beta import implementations
import fabric_pb2
import chaincode_pb2
import devops_pb2
SDK_NODE_APP_REST_PORT = 8080
def buildUrl(context, ipAddress, path):
schema = "http"
if 'TLS' in context.tags:
schema = "https"
return "{0}://{1}:{2}{3}".format(schema, ipAddress, SDK_NODE_APP_REST_PORT, path)
@given(u'I register thru the sample SDK app supplying username "{enrollId}" and secret "{enrollSecret}" on "{composeService}"')
def step_impl(context, enrollId, enrollSecret, composeService):
assert 'compose_containers' in context, "compose_containers not found in context"
# Get the sampleApp IP Address
containerDataList = bdd_test_util.getContainerDataValuesFromContext(context, [composeService], lambda containerData: containerData)
sampleAppIpAddress = containerDataList[0].ipAddress
secretMsg = {
"enrollId": enrollId,
"enrollSecret" : enrollSecret
}
request_url = buildUrl(context, sampleAppIpAddress, "/")
resp = requests.get(request_url, headers={'Accept': 'application/json'}, verify=False)
assert resp.status_code == 200, "Failed to GET url %s: %s" % (request_url,resp.text)
context.response = resp
print("")
| apache-2.0 |
briancurtin/python-openstacksdk | openstack/tests/unit/workflow/test_proxy.py | 1 | 2321 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from openstack.tests.unit import test_proxy_base2
from openstack.workflow.v2 import _proxy
from openstack.workflow.v2 import execution
from openstack.workflow.v2 import workflow
class TestWorkflowProxy(test_proxy_base2.TestProxyBase):
def setUp(self):
super(TestWorkflowProxy, self).setUp()
self.proxy = _proxy.Proxy(self.session)
def test_workflows(self):
self.verify_list(self.proxy.workflows,
workflow.Workflow,
paginated=True)
def test_executions(self):
self.verify_list(self.proxy.executions,
execution.Execution,
paginated=True)
def test_workflow_get(self):
self.verify_get(self.proxy.get_workflow,
workflow.Workflow)
def test_execution_get(self):
self.verify_get(self.proxy.get_execution,
execution.Execution)
def test_workflow_create(self):
self.verify_create(self.proxy.create_workflow,
workflow.Workflow)
def test_execution_create(self):
self.verify_create(self.proxy.create_execution,
execution.Execution)
def test_workflow_delete(self):
self.verify_delete(self.proxy.delete_workflow,
workflow.Workflow, True)
def test_execution_delete(self):
self.verify_delete(self.proxy.delete_execution,
execution.Execution, True)
def test_workflow_find(self):
self.verify_find(self.proxy.find_workflow,
workflow.Workflow)
def test_execution_find(self):
self.verify_find(self.proxy.find_execution,
execution.Execution)
| apache-2.0 |
pczerkas/tempest | tempest/api/identity/admin/v3/test_list_users.py | 7 | 4408 | # Copyright 2014 Hewlett-Packard Development Company, L.P
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.api.identity import base
from tempest.common.utils import data_utils
from tempest import test
class UsersV3TestJSON(base.BaseIdentityV3AdminTest):
def _list_users_with_params(self, params, key, expected, not_expected):
# Helper method to list users filtered with params and
# assert the response based on expected and not_expected
# expected: user expected in the list response
# not_expected: user, which should not be present in list response
body = self.client.get_users(params)['users']
self.assertIn(expected[key], map(lambda x: x[key], body))
self.assertNotIn(not_expected[key],
map(lambda x: x[key], body))
@classmethod
def resource_setup(cls):
super(UsersV3TestJSON, cls).resource_setup()
alt_user = data_utils.rand_name('test_user')
alt_password = data_utils.rand_name('pass')
cls.alt_email = alt_user + '@testmail.tm'
cls.data.setup_test_domain()
# Create user with Domain
u1_name = data_utils.rand_name('test_user')
cls.domain_enabled_user = cls.client.create_user(
u1_name, password=alt_password,
email=cls.alt_email, domain_id=cls.data.domain['id'])['user']
cls.data.v3_users.append(cls.domain_enabled_user)
# Create default not enabled user
u2_name = data_utils.rand_name('test_user')
cls.non_domain_enabled_user = cls.client.create_user(
u2_name, password=alt_password,
email=cls.alt_email, enabled=False)['user']
cls.data.v3_users.append(cls.non_domain_enabled_user)
@test.idempotent_id('08f9aabb-dcfe-41d0-8172-82b5fa0bd73d')
def test_list_user_domains(self):
# List users with domain
params = {'domain_id': self.data.domain['id']}
self._list_users_with_params(params, 'domain_id',
self.domain_enabled_user,
self.non_domain_enabled_user)
@test.idempotent_id('bff8bf2f-9408-4ef5-b63a-753c8c2124eb')
def test_list_users_with_not_enabled(self):
# List the users with not enabled
params = {'enabled': False}
self._list_users_with_params(params, 'enabled',
self.non_domain_enabled_user,
self.domain_enabled_user)
@test.idempotent_id('c285bb37-7325-4c02-bff3-3da5d946d683')
def test_list_users_with_name(self):
# List users with name
params = {'name': self.domain_enabled_user['name']}
self._list_users_with_params(params, 'name',
self.domain_enabled_user,
self.non_domain_enabled_user)
@test.idempotent_id('b30d4651-a2ea-4666-8551-0c0e49692635')
def test_list_users(self):
# List users
body = self.client.get_users()['users']
fetched_ids = [u['id'] for u in body]
missing_users = [u['id'] for u in self.data.v3_users
if u['id'] not in fetched_ids]
self.assertEqual(0, len(missing_users),
"Failed to find user %s in fetched list" %
', '.join(m_user for m_user in missing_users))
@test.idempotent_id('b4baa3ae-ac00-4b4e-9e27-80deaad7771f')
def test_get_user(self):
# Get a user detail
user = self.client.get_user(self.data.v3_users[0]['id'])['user']
self.assertEqual(self.data.v3_users[0]['id'], user['id'])
self.assertEqual(self.data.v3_users[0]['name'], user['name'])
self.assertEqual(self.alt_email, user['email'])
self.assertEqual(self.data.domain['id'], user['domain_id'])
| apache-2.0 |
codemac/servo | tests/wpt/harness/wptrunner/browsers/servodriver.py | 48 | 4743 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
import os
import subprocess
import tempfile
from mozprocess import ProcessHandler
from .base import Browser, require_arg, get_free_port, browser_command, ExecutorBrowser
from ..executors import executor_kwargs as base_executor_kwargs
from ..executors.executorservodriver import (ServoWebDriverTestharnessExecutor,
ServoWebDriverRefTestExecutor)
here = os.path.join(os.path.split(__file__)[0])
__wptrunner__ = {"product": "servodriver",
"check_args": "check_args",
"browser": "ServoWebDriverBrowser",
"executor": {"testharness": "ServoWebDriverTestharnessExecutor",
"reftest": "ServoWebDriverRefTestExecutor"},
"browser_kwargs": "browser_kwargs",
"executor_kwargs": "executor_kwargs",
"env_options": "env_options"}
hosts_text = """127.0.0.1 web-platform.test
127.0.0.1 www.web-platform.test
127.0.0.1 www1.web-platform.test
127.0.0.1 www2.web-platform.test
127.0.0.1 xn--n8j6ds53lwwkrqhv28a.web-platform.test
127.0.0.1 xn--lve-6lad.web-platform.test
"""
def check_args(**kwargs):
require_arg(kwargs, "binary")
def browser_kwargs(**kwargs):
return {"binary": kwargs["binary"],
"debug_info": kwargs["debug_info"]}
def executor_kwargs(test_type, server_config, cache_manager, run_info_data, **kwargs):
rv = base_executor_kwargs(test_type, server_config,
cache_manager, **kwargs)
return rv
def env_options():
return {"host": "web-platform.test",
"bind_hostname": "true",
"testharnessreport": "testharnessreport-servodriver.js",
"supports_debugger": True}
def make_hosts_file():
hosts_fd, hosts_path = tempfile.mkstemp()
with os.fdopen(hosts_fd, "w") as f:
f.write(hosts_text)
return hosts_path
class ServoWebDriverBrowser(Browser):
used_ports = set()
def __init__(self, logger, binary, debug_info=None, webdriver_host="127.0.0.1"):
Browser.__init__(self, logger)
self.binary = binary
self.webdriver_host = webdriver_host
self.webdriver_port = None
self.proc = None
self.debug_info = debug_info
self.hosts_path = make_hosts_file()
self.command = None
def start(self):
self.webdriver_port = get_free_port(4444, exclude=self.used_ports)
self.used_ports.add(self.webdriver_port)
env = os.environ.copy()
env["HOST_FILE"] = self.hosts_path
debug_args, command = browser_command(self.binary,
["--cpu", "--hard-fail",
"--webdriver", str(self.webdriver_port),
"about:blank"],
self.debug_info)
self.command = command
self.command = debug_args + self.command
if not self.debug_info or not self.debug_info.interactive:
self.proc = ProcessHandler(self.command,
processOutputLine=[self.on_output],
env=env,
storeOutput=False)
self.proc.run()
else:
self.proc = subprocess.Popen(self.command, env=env)
self.logger.debug("Servo Started")
def stop(self):
self.logger.debug("Stopping browser")
if self.proc is not None:
try:
self.proc.kill()
except OSError:
# This can happen on Windows if the process is already dead
pass
def pid(self):
if self.proc is None:
return None
try:
return self.proc.pid
except AttributeError:
return None
def on_output(self, line):
"""Write a line of output from the process to the log"""
self.logger.process_output(self.pid(),
line.decode("utf8", "replace"),
command=" ".join(self.command))
def is_alive(self):
if self.runner:
return self.runner.is_running()
return False
def cleanup(self):
self.stop()
def executor_browser(self):
assert self.webdriver_port is not None
return ExecutorBrowser, {"webdriver_host": self.webdriver_host,
"webdriver_port": self.webdriver_port}
| mpl-2.0 |
AfonsoFGarcia/swift | swift/common/internal_client.py | 16 | 33091 | # Copyright (c) 2010-2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from eventlet import sleep, Timeout
from eventlet.green import httplib, socket, urllib2
import json
import struct
from sys import exc_info
import zlib
from swift import gettext_ as _
from time import gmtime, strftime, time
import urlparse
from zlib import compressobj
from swift.common.utils import quote
from swift.common.http import HTTP_NOT_FOUND
from swift.common.swob import Request
from swift.common.wsgi import loadapp, pipeline_property
class UnexpectedResponse(Exception):
"""
Exception raised on invalid responses to InternalClient.make_request().
:param message: Exception message.
:param resp: The unexpected response.
"""
def __init__(self, message, resp):
super(UnexpectedResponse, self).__init__(message)
self.resp = resp
class CompressingFileReader(object):
"""
Wrapper for file object to compress object while reading.
Can be used to wrap file objects passed to InternalClient.upload_object().
Used in testing of InternalClient.
:param file_obj: File object to wrap.
:param compresslevel: Compression level, defaults to 9.
:param chunk_size: Size of chunks read when iterating using object,
defaults to 4096.
"""
def __init__(self, file_obj, compresslevel=9, chunk_size=4096):
self._f = file_obj
self.compresslevel = compresslevel
self.chunk_size = chunk_size
self.set_initial_state()
def set_initial_state(self):
"""
Sets the object to the state needed for the first read.
"""
self._f.seek(0)
self._compressor = compressobj(
self.compresslevel, zlib.DEFLATED, -zlib.MAX_WBITS,
zlib.DEF_MEM_LEVEL, 0)
self.done = False
self.first = True
self.crc32 = 0
self.total_size = 0
def read(self, *a, **kw):
"""
Reads a chunk from the file object.
Params are passed directly to the underlying file object's read().
:returns: Compressed chunk from file object.
"""
if self.done:
return ''
x = self._f.read(*a, **kw)
if x:
self.crc32 = zlib.crc32(x, self.crc32) & 0xffffffff
self.total_size += len(x)
compressed = self._compressor.compress(x)
if not compressed:
compressed = self._compressor.flush(zlib.Z_SYNC_FLUSH)
else:
compressed = self._compressor.flush(zlib.Z_FINISH)
crc32 = struct.pack("<L", self.crc32 & 0xffffffff)
size = struct.pack("<L", self.total_size & 0xffffffff)
footer = crc32 + size
compressed += footer
self.done = True
if self.first:
self.first = False
header = '\037\213\010\000\000\000\000\000\002\377'
compressed = header + compressed
return compressed
def __iter__(self):
return self
def next(self):
chunk = self.read(self.chunk_size)
if chunk:
return chunk
raise StopIteration
def seek(self, offset, whence=0):
if not (offset == 0 and whence == 0):
raise NotImplementedError('Seek implemented on offset 0 only')
self.set_initial_state()
class InternalClient(object):
"""
An internal client that uses a swift proxy app to make requests to Swift.
This client will exponentially slow down for retries.
:param conf_path: Full path to proxy config.
:param user_agent: User agent to be sent to requests to Swift.
:param request_tries: Number of tries before InternalClient.make_request()
gives up.
"""
def __init__(self, conf_path, user_agent, request_tries,
allow_modify_pipeline=False):
self.app = loadapp(conf_path,
allow_modify_pipeline=allow_modify_pipeline)
self.user_agent = user_agent
self.request_tries = request_tries
get_object_ring = pipeline_property('get_object_ring')
container_ring = pipeline_property('container_ring')
account_ring = pipeline_property('account_ring')
auto_create_account_prefix = pipeline_property(
'auto_create_account_prefix', default='.')
def make_request(
self, method, path, headers, acceptable_statuses, body_file=None):
"""
Makes a request to Swift with retries.
:param method: HTTP method of request.
:param path: Path of request.
:param headers: Headers to be sent with request.
:param acceptable_statuses: List of acceptable statuses for request.
:param body_file: Body file to be passed along with request,
defaults to None.
:returns : Response object on success.
:raises UnexpectedResponse: Exception raised when make_request() fails
to get a response with an acceptable status
:raises Exception: Exception is raised when code fails in an
unexpected way.
"""
headers = dict(headers)
headers['user-agent'] = self.user_agent
resp = exc_type = exc_value = exc_traceback = None
for attempt in xrange(self.request_tries):
req = Request.blank(
path, environ={'REQUEST_METHOD': method}, headers=headers)
if body_file is not None:
if hasattr(body_file, 'seek'):
body_file.seek(0)
req.body_file = body_file
try:
resp = req.get_response(self.app)
if resp.status_int in acceptable_statuses or \
resp.status_int // 100 in acceptable_statuses:
return resp
except (Exception, Timeout):
exc_type, exc_value, exc_traceback = exc_info()
# sleep only between tries, not after each one
if attempt < self.request_tries - 1:
sleep(2 ** (attempt + 1))
if resp:
raise UnexpectedResponse(
_('Unexpected response: %s') % resp.status, resp)
if exc_type:
# To make pep8 tool happy, in place of raise t, v, tb:
raise exc_type(*exc_value.args), None, exc_traceback
def _get_metadata(
self, path, metadata_prefix='', acceptable_statuses=(2,),
headers=None):
"""
Gets metadata by doing a HEAD on a path and using the metadata_prefix
to get values from the headers returned.
:param path: Path to do HEAD on.
:param metadata_prefix: Used to filter values from the headers
returned. Will strip that prefix from the
keys in the dict returned. Defaults to ''.
:param acceptable_statuses: List of status for valid responses,
defaults to (2,).
:param headers: extra headers to send
:returns : A dict of metadata with metadata_prefix stripped from keys.
Keys will be lowercase.
:raises UnexpectedResponse: Exception raised when requests fail
to get a response with an acceptable status
:raises Exception: Exception is raised when code fails in an
unexpected way.
"""
headers = headers or {}
resp = self.make_request('HEAD', path, headers, acceptable_statuses)
metadata_prefix = metadata_prefix.lower()
metadata = {}
for k, v in resp.headers.iteritems():
if k.lower().startswith(metadata_prefix):
metadata[k[len(metadata_prefix):].lower()] = v
return metadata
def _iter_items(
self, path, marker='', end_marker='',
acceptable_statuses=(2, HTTP_NOT_FOUND)):
"""
Returns an iterator of items from a json listing. Assumes listing has
'name' key defined and uses markers.
:param path: Path to do GET on.
:param marker: Prefix of first desired item, defaults to ''.
:param end_marker: Last item returned will be 'less' than this,
defaults to ''.
:param acceptable_statuses: List of status for valid responses,
defaults to (2, HTTP_NOT_FOUND).
:raises UnexpectedResponse: Exception raised when requests fail
to get a response with an acceptable status
:raises Exception: Exception is raised when code fails in an
unexpected way.
"""
while True:
resp = self.make_request(
'GET', '%s?format=json&marker=%s&end_marker=%s' %
(path, quote(marker), quote(end_marker)),
{}, acceptable_statuses)
if not resp.status_int == 200:
break
data = json.loads(resp.body)
if not data:
break
for item in data:
yield item
marker = data[-1]['name'].encode('utf8')
def make_path(self, account, container=None, obj=None):
"""
Returns a swift path for a request quoting and utf-8 encoding the path
parts as need be.
:param account: swift account
:param container: container, defaults to None
:param obj: object, defaults to None
:raises ValueError: Is raised if obj is specified and container is
not.
"""
path = '/v1/%s' % quote(account)
if container:
path += '/%s' % quote(container)
if obj:
path += '/%s' % quote(obj)
elif obj:
raise ValueError('Object specified without container')
return path
def _set_metadata(
self, path, metadata, metadata_prefix='',
acceptable_statuses=(2,)):
"""
Sets metadata on path using metadata_prefix to set values in headers of
POST request.
:param path: Path to do POST on.
:param metadata: Dict of metadata to set.
:param metadata_prefix: Prefix used to set metadata values in headers
of requests, used to prefix keys in metadata
when setting metadata, defaults to ''.
:param acceptable_statuses: List of status for valid responses,
defaults to (2,).
:raises UnexpectedResponse: Exception raised when requests fail
to get a response with an acceptable status
:raises Exception: Exception is raised when code fails in an
unexpected way.
"""
headers = {}
for k, v in metadata.iteritems():
if k.lower().startswith(metadata_prefix):
headers[k] = v
else:
headers['%s%s' % (metadata_prefix, k)] = v
self.make_request('POST', path, headers, acceptable_statuses)
# account methods
def iter_containers(
self, account, marker='', end_marker='',
acceptable_statuses=(2, HTTP_NOT_FOUND)):
"""
Returns an iterator of containers dicts from an account.
:param account: Account on which to do the container listing.
:param marker: Prefix of first desired item, defaults to ''.
:param end_marker: Last item returned will be 'less' than this,
defaults to ''.
:param acceptable_statuses: List of status for valid responses,
defaults to (2, HTTP_NOT_FOUND).
:raises UnexpectedResponse: Exception raised when requests fail
to get a response with an acceptable status
:raises Exception: Exception is raised when code fails in an
unexpected way.
"""
path = self.make_path(account)
return self._iter_items(path, marker, end_marker, acceptable_statuses)
def get_account_info(
self, account, acceptable_statuses=(2, HTTP_NOT_FOUND)):
"""
Returns (container_count, object_count) for an account.
:param account: Account on which to get the information.
:param acceptable_statuses: List of status for valid responses,
defaults to (2, HTTP_NOT_FOUND).
:raises UnexpectedResponse: Exception raised when requests fail
to get a response with an acceptable status
:raises Exception: Exception is raised when code fails in an
unexpected way.
"""
path = self.make_path(account)
resp = self.make_request('HEAD', path, {}, acceptable_statuses)
if not resp.status_int // 100 == 2:
return (0, 0)
return (int(resp.headers.get('x-account-container-count', 0)),
int(resp.headers.get('x-account-object-count', 0)))
def get_account_metadata(
self, account, metadata_prefix='', acceptable_statuses=(2,)):
"""
Gets account metadata.
:param account: Account on which to get the metadata.
:param metadata_prefix: Used to filter values from the headers
returned. Will strip that prefix from the
keys in the dict returned. Defaults to ''.
:param acceptable_statuses: List of status for valid responses,
defaults to (2,).
:returns : Returns dict of account metadata. Keys will be lowercase.
:raises UnexpectedResponse: Exception raised when requests fail
to get a response with an acceptable status
:raises Exception: Exception is raised when code fails in an
unexpected way.
"""
path = self.make_path(account)
return self._get_metadata(path, metadata_prefix, acceptable_statuses)
def set_account_metadata(
self, account, metadata, metadata_prefix='',
acceptable_statuses=(2,)):
"""
Sets account metadata. A call to this will add to the account
metadata and not overwrite all of it with values in the metadata dict.
To clear an account metadata value, pass an empty string as
the value for the key in the metadata dict.
:param account: Account on which to get the metadata.
:param metadata: Dict of metadata to set.
:param metadata_prefix: Prefix used to set metadata values in headers
of requests, used to prefix keys in metadata
when setting metadata, defaults to ''.
:param acceptable_statuses: List of status for valid responses,
defaults to (2,).
:raises UnexpectedResponse: Exception raised when requests fail
to get a response with an acceptable status
:raises Exception: Exception is raised when code fails in an
unexpected way.
"""
path = self.make_path(account)
self._set_metadata(
path, metadata, metadata_prefix, acceptable_statuses)
# container methods
def container_exists(self, account, container):
"""
Checks to see if a container exists.
:param account: The container's account.
:param container: Container to check.
:raises UnexpectedResponse: Exception raised when requests fail
to get a response with an acceptable status
:raises Exception: Exception is raised when code fails in an
unexpected way.
:returns : True if container exists, false otherwise.
"""
path = self.make_path(account, container)
resp = self.make_request('HEAD', path, {}, (2, HTTP_NOT_FOUND))
return not resp.status_int == HTTP_NOT_FOUND
def create_container(
self, account, container, headers=None, acceptable_statuses=(2,)):
"""
Creates container.
:param account: The container's account.
:param container: Container to create.
:param headers: Defaults to empty dict.
:param acceptable_statuses: List of status for valid responses,
defaults to (2,).
:raises UnexpectedResponse: Exception raised when requests fail
to get a response with an acceptable status
:raises Exception: Exception is raised when code fails in an
unexpected way.
"""
headers = headers or {}
path = self.make_path(account, container)
self.make_request('PUT', path, headers, acceptable_statuses)
def delete_container(
self, account, container, acceptable_statuses=(2, HTTP_NOT_FOUND)):
"""
Deletes a container.
:param account: The container's account.
:param container: Container to delete.
:param acceptable_statuses: List of status for valid responses,
defaults to (2, HTTP_NOT_FOUND).
:raises UnexpectedResponse: Exception raised when requests fail
to get a response with an acceptable status
:raises Exception: Exception is raised when code fails in an
unexpected way.
"""
path = self.make_path(account, container)
self.make_request('DELETE', path, {}, acceptable_statuses)
def get_container_metadata(
self, account, container, metadata_prefix='',
acceptable_statuses=(2,)):
"""
Gets container metadata.
:param account: The container's account.
:param container: Container to get metadata on.
:param metadata_prefix: Used to filter values from the headers
returned. Will strip that prefix from the
keys in the dict returned. Defaults to ''.
:param acceptable_statuses: List of status for valid responses,
defaults to (2,).
:returns : Returns dict of container metadata. Keys will be lowercase.
:raises UnexpectedResponse: Exception raised when requests fail
to get a response with an acceptable status
:raises Exception: Exception is raised when code fails in an
unexpected way.
"""
path = self.make_path(account, container)
return self._get_metadata(path, metadata_prefix, acceptable_statuses)
def iter_objects(
self, account, container, marker='', end_marker='',
acceptable_statuses=(2, HTTP_NOT_FOUND)):
"""
Returns an iterator of object dicts from a container.
:param account: The container's account.
:param container: Container to iterate objects on.
:param marker: Prefix of first desired item, defaults to ''.
:param end_marker: Last item returned will be 'less' than this,
defaults to ''.
:param acceptable_statuses: List of status for valid responses,
defaults to (2, HTTP_NOT_FOUND).
:raises UnexpectedResponse: Exception raised when requests fail
to get a response with an acceptable status
:raises Exception: Exception is raised when code fails in an
unexpected way.
"""
path = self.make_path(account, container)
return self._iter_items(path, marker, end_marker, acceptable_statuses)
def set_container_metadata(
self, account, container, metadata, metadata_prefix='',
acceptable_statuses=(2,)):
"""
Sets container metadata. A call to this will add to the container
metadata and not overwrite all of it with values in the metadata dict.
To clear a container metadata value, pass an empty string as the value
for the key in the metadata dict.
:param account: The container's account.
:param container: Container to set metadata on.
:param metadata: Dict of metadata to set.
:param metadata_prefix: Prefix used to set metadata values in headers
of requests, used to prefix keys in metadata
when setting metadata, defaults to ''.
:param acceptable_statuses: List of status for valid responses,
defaults to (2,).
:raises UnexpectedResponse: Exception raised when requests fail
to get a response with an acceptable status
:raises Exception: Exception is raised when code fails in an
unexpected way.
"""
path = self.make_path(account, container)
self._set_metadata(
path, metadata, metadata_prefix, acceptable_statuses)
# object methods
def delete_object(
self, account, container, obj,
acceptable_statuses=(2, HTTP_NOT_FOUND),
headers=None):
"""
Deletes an object.
:param account: The object's account.
:param container: The object's container.
:param obj: The object.
:param acceptable_statuses: List of status for valid responses,
defaults to (2, HTTP_NOT_FOUND).
:param headers: extra headers to send with request
:raises UnexpectedResponse: Exception raised when requests fail
to get a response with an acceptable status
:raises Exception: Exception is raised when code fails in an
unexpected way.
"""
path = self.make_path(account, container, obj)
self.make_request('DELETE', path, (headers or {}), acceptable_statuses)
def get_object_metadata(
self, account, container, obj, metadata_prefix='',
acceptable_statuses=(2,), headers=None):
"""
Gets object metadata.
:param account: The object's account.
:param container: The object's container.
:param obj: The object.
:param metadata_prefix: Used to filter values from the headers
returned. Will strip that prefix from the
keys in the dict returned. Defaults to ''.
:param acceptable_statuses: List of status for valid responses,
defaults to (2,).
:param headers: extra headers to send with request
:returns : Dict of object metadata.
:raises UnexpectedResponse: Exception raised when requests fail
to get a response with an acceptable status
:raises Exception: Exception is raised when code fails in an
unexpected way.
"""
path = self.make_path(account, container, obj)
return self._get_metadata(path, metadata_prefix, acceptable_statuses,
headers=headers)
def get_object(self, account, container, obj, headers,
acceptable_statuses=(2,)):
"""
Returns a 3-tuple (status, headers, iterator of object body)
"""
headers = headers or {}
path = self.make_path(account, container, obj)
resp = self.make_request('GET', path, headers, acceptable_statuses)
return (resp.status_int, resp.headers, resp.app_iter)
def iter_object_lines(
self, account, container, obj, headers=None,
acceptable_statuses=(2,)):
"""
Returns an iterator of object lines from an uncompressed or compressed
text object.
Uncompress object as it is read if the object's name ends with '.gz'.
:param account: The object's account.
:param container: The object's container.
:param obj: The object.
:param acceptable_statuses: List of status for valid responses,
defaults to (2,).
:raises UnexpectedResponse: Exception raised when requests fail
to get a response with an acceptable status
:raises Exception: Exception is raised when code fails in an
unexpected way.
"""
headers = headers or {}
path = self.make_path(account, container, obj)
resp = self.make_request('GET', path, headers, acceptable_statuses)
if not resp.status_int // 100 == 2:
return
last_part = ''
compressed = obj.endswith('.gz')
# magic in the following zlib.decompressobj argument is courtesy of
# Python decompressing gzip chunk-by-chunk
# http://stackoverflow.com/questions/2423866
d = zlib.decompressobj(16 + zlib.MAX_WBITS)
for chunk in resp.app_iter:
if compressed:
chunk = d.decompress(chunk)
parts = chunk.split('\n')
if len(parts) == 1:
last_part = last_part + parts[0]
else:
parts[0] = last_part + parts[0]
for part in parts[:-1]:
yield part
last_part = parts[-1]
if last_part:
yield last_part
def set_object_metadata(
self, account, container, obj, metadata,
metadata_prefix='', acceptable_statuses=(2,)):
"""
Sets an object's metadata. The object's metadata will be overwritten
by the values in the metadata dict.
:param account: The object's account.
:param container: The object's container.
:param obj: The object.
:param metadata: Dict of metadata to set.
:param metadata_prefix: Prefix used to set metadata values in headers
of requests, used to prefix keys in metadata
when setting metadata, defaults to ''.
:param acceptable_statuses: List of status for valid responses,
defaults to (2,).
:raises UnexpectedResponse: Exception raised when requests fail
to get a response with an acceptable status
:raises Exception: Exception is raised when code fails in an
unexpected way.
"""
path = self.make_path(account, container, obj)
self._set_metadata(
path, metadata, metadata_prefix, acceptable_statuses)
def upload_object(
self, fobj, account, container, obj, headers=None):
"""
:param fobj: File object to read object's content from.
:param account: The object's account.
:param container: The object's container.
:param obj: The object.
:param headers: Headers to send with request, defaults ot empty dict.
:raises UnexpectedResponse: Exception raised when requests fail
to get a response with an acceptable status
:raises Exception: Exception is raised when code fails in an
unexpected way.
"""
headers = dict(headers or {})
if 'Content-Length' not in headers:
headers['Transfer-Encoding'] = 'chunked'
path = self.make_path(account, container, obj)
self.make_request('PUT', path, headers, (2,), fobj)
def get_auth(url, user, key, auth_version='1.0', **kwargs):
if auth_version != '1.0':
exit('ERROR: swiftclient missing, only auth v1.0 supported')
req = urllib2.Request(url)
req.add_header('X-Auth-User', user)
req.add_header('X-Auth-Key', key)
conn = urllib2.urlopen(req)
headers = conn.info()
return (
headers.getheader('X-Storage-Url'),
headers.getheader('X-Auth-Token'))
class SimpleClient(object):
"""
Simple client that is used in bin/swift-dispersion-* and container sync
"""
def __init__(self, url=None, token=None, starting_backoff=1,
max_backoff=5, retries=5):
self.url = url
self.token = token
self.attempts = 0 # needed in swif-dispersion-populate
self.starting_backoff = starting_backoff
self.max_backoff = max_backoff
self.retries = retries
def base_request(self, method, container=None, name=None, prefix=None,
headers=None, proxy=None, contents=None,
full_listing=None, logger=None, additional_info=None,
timeout=None):
# Common request method
trans_start = time()
url = self.url
if headers is None:
headers = {}
if self.token:
headers['X-Auth-Token'] = self.token
if container:
url = '%s/%s' % (url.rstrip('/'), quote(container))
if name:
url = '%s/%s' % (url.rstrip('/'), quote(name))
else:
url += '?format=json'
if prefix:
url += '&prefix=%s' % prefix
req = urllib2.Request(url, headers=headers, data=contents)
if proxy:
proxy = urlparse.urlparse(proxy)
req.set_proxy(proxy.netloc, proxy.scheme)
req.get_method = lambda: method
conn = urllib2.urlopen(req, timeout=timeout)
body = conn.read()
try:
body_data = json.loads(body)
except ValueError:
body_data = None
trans_stop = time()
if logger:
sent_content_length = 0
for n, v in headers.items():
nl = n.lower()
if nl == 'content-length':
try:
sent_content_length = int(v)
break
except ValueError:
pass
logger.debug("-> " + " ".join(
quote(str(x) if x else "-", ":/")
for x in (
strftime('%Y-%m-%dT%H:%M:%S', gmtime(trans_stop)),
method,
url,
conn.getcode(),
sent_content_length,
conn.info()['content-length'],
trans_start,
trans_stop,
trans_stop - trans_start,
additional_info
)))
return [None, body_data]
def retry_request(self, method, **kwargs):
retries = kwargs.pop('retries', self.retries)
self.attempts = 0
backoff = self.starting_backoff
while self.attempts <= retries:
self.attempts += 1
try:
return self.base_request(method, **kwargs)
except (socket.error, httplib.HTTPException, urllib2.URLError):
if self.attempts > retries:
raise
sleep(backoff)
backoff = min(backoff * 2, self.max_backoff)
def get_account(self, *args, **kwargs):
# Used in swift-dispersion-populate
return self.retry_request('GET', **kwargs)
def put_container(self, container, **kwargs):
# Used in swift-dispersion-populate
return self.retry_request('PUT', container=container, **kwargs)
def get_container(self, container, **kwargs):
# Used in swift-dispersion-populate
return self.retry_request('GET', container=container, **kwargs)
def put_object(self, container, name, contents, **kwargs):
# Used in swift-dispersion-populate
return self.retry_request('PUT', container=container, name=name,
contents=contents.read(), **kwargs)
def put_object(url, **kwargs):
"""For usage with container sync """
client = SimpleClient(url=url)
client.retry_request('PUT', **kwargs)
def delete_object(url, **kwargs):
"""For usage with container sync """
client = SimpleClient(url=url)
client.retry_request('DELETE', **kwargs)
| apache-2.0 |
thezawad/kivy | examples/widgets/focus_behavior.py | 67 | 3559 | from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.behaviors import FocusBehavior
from kivy.graphics import Color, Rectangle
class FocusWithColor(FocusBehavior):
''' Class that when focused, changes its background color to red.
'''
_color = None
_rect = None
def __init__(self, **kwargs):
super(FocusWithColor, self).__init__(**kwargs)
with self.canvas:
self._color = Color(1, 1, 1, .2)
self._rect = Rectangle(size=self.size, pos=self.pos)
self.bind(size=self._update_rect, pos=self._update_rect)
def _update_rect(self, instance, value):
self._rect.pos = instance.pos
self._rect.size = instance.size
def on_focused(self, instance, value, *largs):
self._color.rgba = [1, 0, 0, .2] if value else [1, 1, 1, .2]
class FocusLabel(FocusWithColor, Label):
'''A label, which in addition to turn red when focused, it also sets the
keyboard input to the text of the label.
'''
def keyboard_on_key_down(self, window, keycode, text, modifiers):
'''We call super before doing anything else to enable tab cycling
by FocusBehavior. If we wanted to use tab for ourselves, we could just
not call it, or call it if we didn't need tab.
'''
if super(FocusLabel, self).keyboard_on_key_down(window, keycode,
text, modifiers):
return True
self.text = keycode[1]
return True
class FocusGridLayout(FocusWithColor, GridLayout):
pass
class FocusBoxLayout(FocusWithColor, BoxLayout):
pass
class FocusApp(App):
def build(self):
root = FocusBoxLayout(padding=[10, 10], spacing=10)
self.grid1 = grid1 = FocusGridLayout(cols=4, padding=[10, 10],
spacing=10)
self.grid2 = grid2 = FocusGridLayout(cols=4, padding=[10, 10],
spacing=10)
root.add_widget(FocusLabel(text='Left', size_hint_x=0.4))
root.add_widget(grid1)
root.add_widget(grid2)
root.add_widget(FocusLabel(text='Right', size_hint_x=0.4))
for i in range(40):
grid1.add_widget(FocusLabel(text='l' + str(i)))
for i in range(40):
grid2.add_widget(FocusLabel(text='r' + str(i)))
# make elements 29, 9 un-focusable. The widgets are displayed in
# reverse order, so 9 = 39 - 10
grid2.children[30].text = grid1.children[14].text =\
grid2.children[15].text = grid1.children[34].text = 'Skip me'
grid2.children[15].is_focusable = False
grid2.children[30].is_focusable = False
# similarly, make 39 - 14 = 25, and 5 un-focusable
grid1.children[14].is_focusable = False
grid1.children[34].is_focusable = False
# don't move focus passed this element
grid2.children[35].focus_next = StopIteration
grid2.children[35].text = 'Stop forward'
# exchange the links between the sides so that it'll skip to the other
# side in the middle. Remember that children are displayed reversed
# in layouts.
grid1.children[10].focus_next = grid2.children[9]
grid2.children[10].focus_next = grid1.children[9]
grid1.children[10].text = '-->'
grid2.children[10].text = '<--'
return root
if __name__ == '__main__':
FocusApp().run()
| mit |
telukir/PubMed2Go | full_text_index/PubMedXapian.py | 4 | 4316 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Copyright (c) 2014, Kersten Doering <kersten.doering@gmail.com>, Christian Senger <der.senger@googlemail.com>
"""
import xappy
import sys
import os
from SynonymParser import SynonymParser
from Article import Article
class PubMedXapian():
__indexCount = 0
__indexMsg = ""
def __init__( self,
directory_name,
#no absolut path
xapianPath = "xapian",
):
self.__xapianPath = os.path.join( xapianPath, directory_name )
self.__pmids = []
self.__searchConn = None
def __buildDoc(self, article):
if article.getTitle() == None: return None
doc = xappy.UnprocessedDocument()
doc.fields.append(xappy.Field("title", article.getTitle()))
if article.getAbstract() == None:
pass
else:
doc.fields.append(xappy.Field("text", article.getAbstract()))
#'INDEX_EXACT' - maximum length 220, but prefix "XA" is added to each term in the document
#maximum length 218
for chemical in [chemical for chemical in article.getChemicals() if len(chemical) < 219]:
doc.fields.append(xappy.Field("chemical_exact", chemical))
for keyword in article.getKeywords():
doc.fields.append(xappy.Field("keyword", keyword))
for mesh in article.getMeSH():
doc.fields.append(xappy.Field("mesh", mesh))
doc.id = str(article.getPMID())
return doc
def buildIndexWithArticles(self, articles):
conn = xappy.IndexerConnection(self.__xapianPath)
#add priority to title field in case of ranked matching (weight=5)- index all fields and store data
conn.add_field_action('title', xappy.FieldActions.INDEX_FREETEXT, weight=5, language='en')
conn.add_field_action('text', xappy.FieldActions.INDEX_FREETEXT, language='en')
conn.add_field_action('chemical_exact', xappy.FieldActions.INDEX_EXACT)
conn.add_field_action('keyword', xappy.FieldActions.INDEX_FREETEXT, language='en')
conn.add_field_action('mesh', xappy.FieldActions.INDEX_FREETEXT, language='en')
conn.add_field_action('text', xappy.FieldActions.STORE_CONTENT)
conn.add_field_action('title', xappy.FieldActions.STORE_CONTENT)
conn.add_field_action('chemical_exact', xappy.FieldActions.STORE_CONTENT)
conn.add_field_action('keyword', xappy.FieldActions.STORE_CONTENT)
conn.add_field_action('mesh', xappy.FieldActions.STORE_CONTENT)
for article in articles:
doc = self.__buildDoc(article)
if doc == None: continue
try:
#process doc to pdoc explicitly - not needed here
#pdoc = conn.process(doc)
conn.add(doc)
except:
continue
PubMedXapian.__indexCount += 1
nbs = len(PubMedXapian.__indexMsg)
PubMedXapian.__indexMsg = "article %s indexed" % (str(PubMedXapian.__indexCount))
sys.stdout.write('\b' * nbs + PubMedXapian.__indexMsg)
conn.flush()
conn.close()
def findPMIDsWithSynonyms(self, synonyms):
if self.__searchConn == None:
self.__searchConn = xappy.SearchConnection(self.__xapianPath)
self.__searchConn.reopen()
xapian_querys = []
for querystring in synonyms:
title, text, keyword, chemical_exact, mesh = '"' + querystring + '"', '"' + querystring + '"', '"' + querystring + '"', '"' + querystring + '"', '"' + querystring + '"'
xapian_querys.append( self.__searchConn.query_field('title', title) )
xapian_querys.append( self.__searchConn.query_field('text', text) )
xapian_querys.append( self.__searchConn.query_field('keyword', keyword) )
xapian_querys.append( self.__searchConn.query_field('chemical_exact', chemical_exact) )
xapian_querys.append( self.__searchConn.query_field('mesh', mesh) )
merged_q = self.__searchConn.query_composite(self.__searchConn.OP_OR, xapian_querys)
results=self.__searchConn.search(merged_q, 0, self.__searchConn.get_doccount())
return [r.id for r in results]
| isc |
cevaris/pants | tests/python/pants_test/backend/jvm/tasks/reports/test_junit_html_report.py | 9 | 5119 | # coding=utf-8
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from pants.backend.jvm.tasks.reports.junit_html_report import JUnitHtmlReport
from pants.util.contextutil import temporary_dir
from pants.util.strutil import ensure_text
from pants_test.base_test import BaseTest
class TestJUnitHtmlReport(BaseTest):
def xml_file_path(self, file):
return os.path.join(self.real_build_root,
'tests/python/pants_test/backend/jvm/tasks/reports/junit_html_report_resources',
file)
def test_passing(self):
testsuites = JUnitHtmlReport().parse_xml_file(self.xml_file_path('TEST-org.pantsbuild.PassingTest.xml'))
self.assertEqual(1, len(testsuites))
self.assertEqual(4, testsuites[0].tests)
self.assertEqual(0, testsuites[0].errors)
self.assertEqual(0, testsuites[0].failures)
self.assertEqual(0, testsuites[0].skipped)
self.assertEqual(4.76, testsuites[0].time)
self.assertEqual(4, len(testsuites[0].testcases))
self.assertIsNone(testsuites[0].testcases[0].failure)
self.assertIsNone(testsuites[0].testcases[0].error)
def test_failed(self):
testsuites = JUnitHtmlReport().parse_xml_file(self.xml_file_path('TEST-org.pantsbuild.FailureTest.xml'))
self.assertEqual(1, len(testsuites))
self.assertEqual(1, testsuites[0].tests)
self.assertEqual(0, testsuites[0].errors)
self.assertEqual(1, testsuites[0].failures)
self.assertEqual(0, testsuites[0].skipped)
self.assertEqual(0.01, testsuites[0].time)
self.assertEqual(1, len(testsuites[0].testcases))
self.assertIsNone(testsuites[0].testcases[0].error)
self.assertEquals('java.lang.AssertionError', testsuites[0].testcases[0].failure['type'])
self.assertIn('java.lang.AssertionError', testsuites[0].testcases[0].failure['message'])
def test_errored(self):
testsuites = JUnitHtmlReport().parse_xml_file(self.xml_file_path('TEST-org.pantsbuild.ErrorTest.xml'))
self.assertEqual(1, len(testsuites))
self.assertEqual(1, testsuites[0].tests)
self.assertEqual(1, testsuites[0].errors)
self.assertEqual(0, testsuites[0].failures)
self.assertEqual(0, testsuites[0].skipped)
self.assertEqual(0.32, testsuites[0].time)
self.assertEqual(1, len(testsuites[0].testcases))
self.assertIsNone(testsuites[0].testcases[0].failure)
self.assertEquals('java.lang.RuntimeException', testsuites[0].testcases[0].error['type'])
self.assertIn('java.lang.RuntimeException', testsuites[0].testcases[0].error['message'])
def test_skipped(self):
testsuites = JUnitHtmlReport().parse_xml_file(self.xml_file_path('TEST-org.pantsbuild.SkippedTest.xml'))
self.assertEqual(1, len(testsuites))
self.assertEqual(1, testsuites[0].tests)
self.assertEqual(0, testsuites[0].errors)
self.assertEqual(0, testsuites[0].failures)
self.assertEqual(1, testsuites[0].skipped)
self.assertEqual(0, testsuites[0].time)
self.assertEqual(1, len(testsuites[0].testcases))
def test_time(self):
testsuites = JUnitHtmlReport().parse_xml_file(self.xml_file_path('TEST-org.pantsbuild.TimeTest.xml'))
self.assertEqual(1, len(testsuites))
self.assertEqual(4, testsuites[0].tests)
self.assertEqual(0.5, testsuites[0].time)
self.assertEqual(4, len(testsuites[0].testcases))
def test_empty(self):
testsuites = JUnitHtmlReport().parse_xml_file(self.xml_file_path('TEST-org.pantsbuild.EmptyTestSuite.xml'))
self.assertEqual(1, len(testsuites))
self.assertEqual(0, len(testsuites[0].testcases))
def test_unicode(self):
testsuites = JUnitHtmlReport().parse_xml_file(self.xml_file_path('TEST-org.pantsbuild.UnicodeCharsTest.xml'))
self.assertEqual(1, len(testsuites))
self.assertEqual(2, testsuites[0].tests)
self.assertEqual(2, len(testsuites[0].testcases))
self.assertEquals(u'org.pantsbuild.PåssingTest', testsuites[0].name)
self.assertEquals(u'testTwö', testsuites[0].testcases[1].name)
self.assertIn(u'org.pantsbuild.PåssingTest.testTwö', testsuites[0].testcases[1].error['message'])
def test_all(self):
test_dir = os.path.join(self.real_build_root,
'tests/python/pants_test/backend/jvm/tasks/reports/junit_html_report_resources')
testsuites = JUnitHtmlReport().parse_xml_files(test_dir)
self.assertEqual(7, len(testsuites))
with temporary_dir() as output_dir:
output_file = os.path.join(output_dir, 'junit-report.html')
JUnitHtmlReport().report(test_dir, output_dir)
self.assertTrue(os.path.exists(output_file))
with open(output_file) as html_file:
html_data = ensure_text(html_file.read())
self.assertIn(u'</span> org.pantsbuild.PåssingTest', html_data)
self.assertIn(u'</span> testTwö</td>', html_data)
self.assertIn(u'at org.pantsbuild.PåssingTest.testTwö(ErrorTest.java:29)', html_data)
| apache-2.0 |
CarterFendley/2015-robot | robot/common/sensor.py | 1 | 4226 | import wpilib
from common.distance_sensors import SharpIR2Y0A02, SharpIRGP2Y0A41SK0F, CombinedSensor
from networktables import NetworkTable
class Sensor:
def __init__(self, tote_motor, can_motor):
self.sd = NetworkTable.getTable('SmartDashboard')
self.toteLimitLSensor = wpilib.DigitalInput(0) ##Left limit switch
self.toteLimitRSensor = wpilib.DigitalInput(1) ##Right limit switch
self.longDistanceLSensor = SharpIR2Y0A02(1) # # Robot's left
self.longDistanceRSensor = SharpIR2Y0A02(3) # # Robot's right
self.shortDistanceLSensor = SharpIRGP2Y0A41SK0F(2) # # Robot's left
self.shortDistanceRSensor = SharpIRGP2Y0A41SK0F(7) # # Robot's right
self.leftSensor = CombinedSensor(self.longDistanceLSensor, 22, self.shortDistanceLSensor, 6)
self.rightSensor = CombinedSensor(self.longDistanceRSensor, 22, self.shortDistanceRSensor, 6)
self.tote_motor = tote_motor
self.can_motor = can_motor
self.in_range = False
self.in_range_start = None
# Premature optimization, but it looks nicer
self._tote_exclude_range = set()
# measured using the calibration routine
interference = [(1031, 1387), (1888, 2153), (4544, 4895), (5395, 5664), (8008, 8450)]
#for i in [1033, 2031, 4554, 5393, 7902]:
for r1, r2 in interference:
for j in range(r1, r2):
self._tote_exclude_range.add(j)
self.update()
def update(self):
self.now = wpilib.Timer.getFPGATimestamp()
self.toteLimitL = self.toteLimitLSensor.get()
self.toteLimitR = self.toteLimitRSensor.get()
self.longDistanceL = self.longDistanceLSensor.getDistance()
self.longDistanceR = self.longDistanceRSensor.getDistance()
self.shortDistanceL = self.shortDistanceLSensor.getDistance()
self.shortDistanceR = self.shortDistanceRSensor.getDistance()
self.leftDistance = self.leftSensor.getDistance()
self.rightDistance = self.rightSensor.getDistance()
self.tote_enc = self.tote_motor.getEncPosition()
self.can_enc = self.can_motor.getEncPosition()
# Calculate if its in range
in_range = (self.leftDistance < 30 and self.rightDistance < 30)
# if it's in the way, then set it to the last thing
self.interfered = self.tote_enc in self._tote_exclude_range
if self.interfered:
in_range = self.in_range
self.in_range = in_range
#if self.in_range_start is None:
# if in_range:
# self.in_range_start = self.now
#else:
# self.in_range = in_range and self.now > self.in_range_start + 0.05
#
# if not in_range:
# self.in_range_start = None
def is_against_tote(self):
if not self.toteLimitL and not self.toteLimitR:
return True
return False
def is_in_range(self):
return self.in_range
def update_sd(self):
self.sd.putNumber('shortSensorValueL', self.shortDistanceL)
self.sd.putNumber('shortSensorValueR', self.shortDistanceR)
self.sd.putNumber('longSensorValueL', self.longDistanceL)
self.sd.putNumber('longSensorValueR', self.longDistanceR)
#self.sd.putNumber('shortSensorVoltageL', self.sensor.shortDistanceL)
#self.sd.putNumber('shortSensorVoltageR', self.sensor.shortDistanceR)
#self.sd.putNumber('longSensorVoltageL', self.sensor.longDistanceL)
#self.sd.putNumber('longSensorVoltageR', self.sensor.longDistanceR)
self.sd.putBoolean('toteInRange', self.in_range)
self.sd.putBoolean('toteInterfere', self.interfered)
self.sd.putNumber('combinedL', self.leftDistance)
self.sd.putNumber('combinedR', self.rightDistance)
self.sd.putBoolean('toteLimitL', self.toteLimitL)
self.sd.putBoolean('toteLimitR', self.toteLimitR)
def doit(self):
pass
| apache-2.0 |
mcuringa/py-tutor | pytutor/tutor/editor_views.py | 1 | 9647 | import random
import json
import difflib
from django.template import loader, Context
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.core import serializers
from django.contrib import messages
from django.db.models import Q
import django.contrib.humanize.templatetags.humanize as humanize
from tutor.templatetags import tutor_extras
from tutor.models import *
def list(request, editor_name=""):
"""List the questions in the database"""
print ("editor:", editor_name)
context = {}
if len(editor_name) > 0:
# filter the questions on this editor
questions = Question.objects.all().filter(Q(creator__username=editor_name) | Q(modifier__username=editor_name)).order_by('-modified')
else:
editor_name = "All"
questions = Question.objects.all().order_by('-modified')
context["editor_name"] = editor_name
context["questions"] = questions
return render(request, 'tutor/list.html', context)
def tags(request):
"""List the tags in the database"""
questions = Question.objects.all()
tags = []
for question in questions:
qtags = question.tags.split(",")
qtags = [q.strip() for q in qtags if len(q.strip() > 0)]
tags.extend(qtags)
tags = sorted(list(set(tags)))
context = {"tags": tags}
return render(request, 'tutor/tags.html', context)
def tests_to_json(test_results, admin_mode=False):
tests = []
for test, fail, result in test_results:
data = {"id": test.id, "code": test.to_code(), "admin_mode": admin_mode}
if fail is None:
data["passed"] = True
data["css_status"] = "success"
data["status"] = "Pass"
data["error_msg"] = ''
else:
data["passed"] = False
data["status"] = "Fail"
data["css_status"] = "danger"
data["error_msg"] = tutor_extras.error_msg(fail)
tests.append(data)
return json.dumps(tests)
@login_required
def question_form(request, pk=0):
if pk == 0:
form = QuestionForm()
form.instance.creator = request.user
form.instance.modifier = request.user
history = []
test_results = []
qstate = "default"
else:
question = Question.objects.get(pk=pk)
form = QuestionForm(instance=question)
history = ArchiveQuestion.objects.all().filter(parent_id=pk).order_by('-version')
passed, test_results = question.run_tests()
if question.status == Question.FAILED:
qstate = "danger"
elif question.status == Question.ACTIVE:
qstate = "success"
else:
qstate = "warning"
if len(test_results) == 0:
msg = """This question has no unit tests.
Without tests, this question can't be studied!"""
messages.warning(request, msg)
test_form = TestForm()
os_ctrl = "ctrl"
# if "Macintosh" in request.META["HTTP_USER_AGENT"]:
# os_ctrl = "cmd"
context = { "question": form,
"pk": pk,
"history": history,
"test_form": test_form,
# "tests": test_results,
"qstate": qstate,
"os_ctrl": os_ctrl,
"question_json": form.instance.as_json(),
"tests_json": tests_to_json(test_results,admin_mode=True)
}
return render(request, 'tutor/question_form.html', context)
@login_required
def add_test(request):
questionId = int(request.POST["question_id"])
q = Question.objects.get(pk=questionId)
if q.status == Question.DELETED:
raise ValueError("Cannot add tests to DELETED Questions")
form = TestForm(request.POST)
form.instance.question = q
data = {}
try:
test = form.save()
success = True
user_function = q.solution
test, ex, result = test.evaluate(user_function)
passed = (ex == None)
#update the question if the new test changed its status
if q.status == Question.ACTIVE and not passed:
q.status = Question.FAILED
q.save()
elif q.status == Question.ACTIVE and passed:
q.status = Question.FAILED
q.save()
data['tests_json'] = tests_to_json([(test, ex, result)], admin_mode=True)
data['question_json'] = q.as_json()
if passed:
data["message"] = {"msg": "Test added, code passed.", "msg_level": "success"}
else:
data["message"] = {"msg": "Test added, code failed.", "msg_level": "warning"}
data["success"] = True
except Exception as ex:
data["message"] = {"msg": "Test code could not be added.", "msg_level": "danger"}
data["success"] = False
return HttpResponse(json.dumps(data), content_type="application/json")
@login_required
def del_test(request, pk):
test = Test.objects.get(pk=pk)
question = test.question
if question.status == Question.DELETED:
raise ValueError("Cannot delete tests to DELETED Questions")
test.delete()
msg = {"msg": "test deleted", "msg_level": "success"}
updated = question.test_and_update()
data = {"message": msg, "question_json": question.as_json()}
return HttpResponse(json.dumps(data), content_type="application/json")
@login_required
def save_question(request):
pk = int(request.POST["pk"])
if pk > 0:
q = Question.objects.get(pk=pk)
form = QuestionForm(request.POST, instance=q)
form.instance.version += 1
else:
form = QuestionForm(request.POST)
form.instance.version = 1
form.instance.creator = request.user
form.instance.modifier = request.user
data = {}
try:
question = form.save()
results = []
if pk > 0:
passed, results = question.run_tests()
if passed:
question.status = Question.ACTIVE
else:
question.status = Question.FAILED
pk = question.id
question.save()
archive(question)
question_json = form.instance.as_json();
data["question"] = question_json
data["msg"] = {"msg": "question saved", "msg_level": "success"}
data["tests_json"] = tests_to_json(results,admin_mode=True)
# data["tests"] = json.dumps(results)
except ValueError as vex:
question_json = form.instance.as_json()
data["msg"] = {"msg": "question saved", "msg_level": "success"}
data["question"] = question_json
data["form_erros"] = form.errors
return HttpResponse(json.dumps(data), content_type="application/json")
@login_required
def delete_question(request, pk):
"""Deletes the selected question and all related ArchiveQuestions."""
question = Question.objects.get(pk=pk)
responses = Response.objects.all().filter(question=question)
archives = ArchiveQuestion.objects.all().filter(parent_id=pk).order_by('-version')
if len(responses) == 0: # hard delete
for q in archives:
q.delete()
question.delete()
messages.success(request, "Question deleted.")
else:
question.status = Question.DELETED
question.save()
messages.success(request, "Question de-activated.")
return HttpResponseRedirect("/question/list")
def archive(question):
aq = ArchiveQuestion()
aq.archive(question)
aq.modifier = question.modifier
aq.save()
@login_required
def dup(request, pk=0):
new_q = Question.objects.get(pk=pk)
tests = Test.objects.all().filter(question=new_q)
new_q.pk = None
new_q.creator = request.user
new_q.modifier = request.user
new_q.save()
for t in tests:
t.pk = None
t.question = new_q
t.save()
messages.success(request, "Test successfully duplicated.")
url = "/question/{}/edit".format(new_q.pk)
return HttpResponseRedirect("/question/list")
def html_diff(s1, s2):
ugly = difflib.HtmlDiff().make_table(s1.split("\n"), s2.split("\n"))
return ugly
@login_required
def diff(request, pk, v1, v2):
q1 = ArchiveQuestion.objects.get(parent__id=pk, version=v1)
q2 = ArchiveQuestion.objects.get(parent__id=pk, version=v2)
titles = html_diff(q1.function_name, q2.function_name)
prompts = html_diff(q1.prompt, q2.prompt)
solutions = html_diff(q1.solution, q2.solution)
context = {
"question": q1.parent,
"versions": [q1,q2],
"titles": titles,
"prompts": prompts,
"solutions": solutions,
}
return render(request, 'tutor/diff.html', context)
@login_required
def revert(request, pk, versionNum):
version = ArchiveQuestion.objects.get(parent__id=pk, version=versionNum)
# question = Question.objects.get(pk=pk)
question = version.parent
question.function_name = version.function_name
question.prompt = version.prompt
question.solution = version.solution
question.tags = version.tags
question.level = version.level
question.version = question.version + 1
question.modifier = request.user
question.comment = "Reverted to revision {} by {}".format(versionNum, request.user.username)
question.test_and_update()
archive(question)
messages.success(request, "Question successfully reverted to revision {}.".format(versionNum))
url = "/question/{}/edit".format(pk)
return HttpResponseRedirect(url)
| agpl-3.0 |
itoed/fabric | sites/shared_conf.py | 19 | 1039 | from os.path import join
from datetime import datetime
import alabaster
# Alabaster theme + mini-extension
html_theme_path = [alabaster.get_path()]
extensions = ['alabaster']
# Paths relative to invoking conf.py - not this shared file
html_static_path = [join('..', '_shared_static')]
html_theme = 'alabaster'
html_theme_options = {
'logo': 'logo.png',
'logo_name': True,
'logo_text_align': 'center',
'description': "Pythonic remote execution",
'github_user': 'fabric',
'github_repo': 'fabric',
'travis_button': True,
'gratipay_user': 'bitprophet',
'analytics_id': 'UA-18486793-1',
'link': '#3782BE',
'link_hover': '#3782BE',
}
html_sidebars = {
'**': [
'about.html',
'navigation.html',
'searchbox.html',
'donate.html',
]
}
# Regular settings
project = 'Fabric'
year = datetime.now().year
copyright = '%d Jeff Forcier' % year
master_doc = 'index'
templates_path = ['_templates']
exclude_trees = ['_build']
source_suffix = '.rst'
default_role = 'obj'
| bsd-2-clause |
AlexanderLang/OpenAutomatedFarm | FarmGUI/farmgui/models/ParameterSetpointLog.py | 1 | 3845 | """
Created on Feb 15, 2014
@author: alex
"""
from sqlalchemy import Column
from sqlalchemy.types import BigInteger
from sqlalchemy.types import SmallInteger
from sqlalchemy.types import DateTime
from sqlalchemy.types import Float
from sqlalchemy import ForeignKey
from .meta import Base
class ParameterSetpointLog(Base):
"""
classdocs
"""
__tablename__ = 'ParameterSetpointLogs'
_id = Column(BigInteger, primary_key=True, autoincrement=True, nullable=False, unique=True)
parameter_id = Column(SmallInteger, ForeignKey('Parameters._id'), nullable=False)
time = Column(DateTime, nullable=False)
setpoint = Column(Float, nullable=True)
def __init__(self, parameter, time, setpoint):
self.parameter = parameter
self.time = time
self.setpoint = setpoint
@property
def id(self):
return self._id
@staticmethod
def log(db_session, parameter, time, setpoint, old_logs):
if old_logs is None:
query = db_session.query(ParameterSetpointLog).filter_by(parameter_id=parameter.id)
old_logs = query.order_by(ParameterSetpointLog.time.desc()).limit(2).all()
insert_new_setpoint = False
if len(old_logs) < 2:
# there aren't enought logs jet for interpolation
insert_new_setpoint = True
else:
# verify that last log values are numbers
y1 = old_logs[1].setpoint
y2 = old_logs[0].setpoint
if y1 is None and y2 is None and setpoint is None:
# still no value, update last log
old_logs[0].time = time
return old_logs
elif y1 is not None and y2 is None:
# (only)last value is None, add new entry (no matter if None or Number)
insert_new_setpoint = True
elif y1 is not None and y2 is not None and setpoint is None:
# first None value, log it
insert_new_setpoint = True
else:
# try to interpolate
t1 = old_logs[1].time
t2 = old_logs[0].time
if y1 is None or y2 is None:
insert_new_setpoint = True
else:
dt = (t2 - t1).total_seconds()
k_old = None
if dt != 0:
k_old = (y2 - y1) / dt
k_new = None
dt = (time - t2).total_seconds()
if dt != 0:
k_new = (setpoint - y2) / dt
if k_old is not None and k_new is not None:
if k_new != 0:
diff = abs((k_new - k_old) / k_new)
if diff < 0.02:
# new point is on straight line with old values, update last entry
old_logs[0].time = time
old_logs[0].setpoint = setpoint
else:
insert_new_setpoint = True
else:
if k_old == 0:
# value is constant, update last log entry
old_logs[0].time = time
old_logs[0].setpoint = setpoint
else:
# value started being constant, add new entry
insert_new_setpoint = True
else:
insert_new_setpoint = True
if insert_new_setpoint:
new_log = ParameterSetpointLog(parameter, time, setpoint)
db_session.add(new_log)
old_logs[:0] = [new_log]
old_logs.pop()
return old_logs
| gpl-3.0 |
scascketta/LostNumber | LostNumber/handle_msg.py | 1 | 4767 | from redis import StrictRedis
from LostNumber import app
import process_msg
import details
r = StrictRedis(host=details.redis_addr, port=details.redis_port)
logger = app.logger
def is_num_registered(num):
return r.sismember('registered_nums', num)
def register_num(data):
"""Adds a number to our list of registered nums, records location data."""
num = data['from']
city = data['from_city']
zipcode = data['from_zip']
state = data['from_state']
logger.info('Registering ' + num)
pipe = r.pipeline()
pipe.sadd('registered_nums', num)
pipe.sadd('available_nums', num)
pipe.sadd('cities:' + city, num)
pipe.sadd('zipcodes:' + zipcode, num)
pipe.sadd(num + ':state', state)
pipe.sadd(num + ':zipcode', zipcode)
pipe.sadd(num + ':city', city)
pipe.sadd('cities', city)
pipe.sadd('zipcodes', zipcode)
pipe.sadd('states', state)
pipe.execute()
def check_if_register_num(data):
"""Check if the number wants to register and send them respective msg."""
sender = data['from']
body = data['body']
register = check_for_register(body)
if not register:
return "Welcome to LostNum, an invite-only national random chat service by SMS. Send 'YES' to continue and login. Send 'NO' to stop and do nothing."
elif register == 'True':
register_num(data)
return "Sweet! You've enabled LostNum! Enter 'START' followed by your message to start a chat. Enter 'DONE' any time to exit a chat. Enter 'OFFLINE' to not receive any chats."
elif register == 'False':
return "Okay, you won't get any more messages from LostNum."
def check_for_register(body):
body = body.lower()
if 'yes' in body:
return 'True'
elif 'no' in body:
return 'False'
else:
return None
def check_for(data, command):
if data['body']:
body = data['body']
return command in body
def start_convo(data):
"""
Starts a convo. Removes START command and forwards msg to a randomly
selected number.
"""
body = data['body']
num = data['from']
body = body.replace('START', '')
logger.info('Starting convo from {0}'.format(num))
process_msg.start_convo(num, body)
def check_in_convo(num):
return r.sismember('in_conversation', num)
def forward_convo(data):
"""Adds the current number of messages sent and state data."""
sender = data['from']
convo_count = get_convo_count(sender)
if convo_count >= 10:
end_convo(sender)
else:
incr_convo_count(sender)
dest = get_partner(sender)
logger.info('Forwarding message from {0} to {1}'.format(sender, dest))
state = r.smembers(sender + ":state").pop()
body = '(' + str(convo_count) + "/10 - " + state + ") " + data['body']
process_msg.add_msg(dest, body)
r.incr('total_count')
def able_to_start():
"""Checks that there are at least two people in available nums."""
size = r.scard('available_nums')
return size >= 2
def get_convo_count(num):
partner = get_partner(num)
return int(r.hget(partner + ":" + num, 'count'))
def get_partner(num):
return r.smembers(num).pop()
def incr_convo_count(num):
original = get_convo_count(num)
incr = str(original + 1)
partner = get_partner(num)
r.hset(partner + ":" + num, 'count', incr)
r.hset(num + ":" + partner, 'count', incr)
def end_convo(num):
"""
Removes participants from in_convo set, deletes the index data,
adds them back to available nums set.
"""
partner = get_partner(num)
logger.info('Ending convo between {0} and {1}'.format(num, partner))
pipe = r.pipeline()
pipe.srem('in_conversation', num)
pipe.srem('in_conversation', partner)
pipe.srem(num, partner)
pipe.srem(partner, num)
pipe.hdel(num + ":" + partner, 'count')
pipe.hdel(partner + ":" + num, 'count')
pipe.sadd('available_nums', num)
pipe.sadd('available_nums', partner)
pipe.execute()
process_msg.add_msg(num, 'LostNum: End of conversation.')
process_msg.add_msg(partner, 'LostNum: End of conversation.')
def handle_offline(data):
"""Sets a user offline."""
num = data['from']
logger.info('Setting {0} to offline mode.'.format(num))
pipe = r.pipeline()
pipe.srem('available_nums', num)
pipe.sadd('offline_nums', num)
pipe.execute()
def check_offline(data):
num = data['from']
return r.sismember('offline_nums', num)
def handle_online(data):
"""Sets a user online."""
num = data['from']
logger.info('Setting {0} to online mode.'.format(num))
pipe = r.pipeline()
pipe.sadd('available_nums', num)
pipe.srem('offline_nums', num)
pipe.execute()
| mit |
Curious72/sympy | examples/advanced/curvilinear_coordinates.py | 96 | 3691 | #!/usr/bin/env python
"""
This example shows how to work with coordinate transformations, curvilinear
coordinates and a little bit with differential geometry.
It takes polar, cylindrical, spherical, rotating disk coordinates and others
and calculates all kinds of interesting properties, like Jacobian, metric
tensor, Laplace operator, ...
"""
from sympy import var, sin, cos, pprint, Matrix, eye, trigsimp, Eq, \
Function, simplify, sinh, cosh, expand, symbols
def laplace(f, g_inv, g_det, X):
"""
Calculates Laplace(f), using the inverse metric g_inv, the determinant of
the metric g_det, all in variables X.
"""
r = 0
for i in range(len(X)):
for j in range(len(X)):
r += g_inv[i, j]*f.diff(X[i]).diff(X[j])
for sigma in range(len(X)):
for alpha in range(len(X)):
r += g_det.diff(X[sigma]) * g_inv[sigma, alpha] * \
f.diff(X[alpha]) / (2*g_det)
return r
def transform(name, X, Y, g_correct=None, recursive=False):
"""
Transforms from cartesian coordinates X to any curvilinear coordinates Y.
It printing useful information, like Jacobian, metric tensor, determinant
of metric, Laplace operator in the new coordinates, ...
g_correct ... if not None, it will be taken as the metric --- this is
useful if sympy's trigsimp() is not powerful enough to
simplify the metric so that it is usable for later
calculation. Leave it as None, only if the metric that
transform() prints is not simplified, you can help it by
specifying the correct one.
recursive ... apply recursive trigonometric simplification (use only when
needed, as it is an expensive operation)
"""
print("_"*80)
print("Transformation:", name)
for x, y in zip(X, Y):
pprint(Eq(y, x))
J = X.jacobian(Y)
print("Jacobian:")
pprint(J)
g = J.T*eye(J.shape[0])*J
g = g.applyfunc(expand)
print("metric tensor g_{ij}:")
pprint(g)
if g_correct is not None:
g = g_correct
print("metric tensor g_{ij} specified by hand:")
pprint(g)
print("inverse metric tensor g^{ij}:")
g_inv = g.inv(method="ADJ")
g_inv = g_inv.applyfunc(simplify)
pprint(g_inv)
print("det g_{ij}:")
g_det = g.det()
pprint(g_det)
f = Function("f")(*list(Y))
print("Laplace:")
pprint(laplace(f, g_inv, g_det, Y))
def main():
mu, nu, rho, theta, phi, sigma, tau, a, t, x, y, z, w = symbols(
"mu, nu, rho, theta, phi, sigma, tau, a, t, x, y, z, w")
transform("polar", Matrix([rho*cos(phi), rho*sin(phi)]), [rho, phi])
transform("cylindrical", Matrix([rho*cos(phi), rho*sin(phi), z]),
[rho, phi, z])
transform("spherical",
Matrix([rho*sin(theta)*cos(phi), rho*sin(theta)*sin(phi),
rho*cos(theta)]),
[rho, theta, phi],
recursive=True
)
transform("rotating disk",
Matrix([t,
x*cos(w*t) - y*sin(w*t),
x*sin(w*t) + y*cos(w*t),
z]),
[t, x, y, z])
transform("parabolic",
Matrix([sigma*tau, (tau**2 - sigma**2) / 2]),
[sigma, tau])
transform("bipolar",
Matrix([a*sinh(tau)/(cosh(tau)-cos(sigma)),
a*sin(sigma)/(cosh(tau)-cos(sigma))]),
[sigma, tau]
)
transform("elliptic",
Matrix([a*cosh(mu)*cos(nu), a*sinh(mu)*sin(nu)]),
[mu, nu]
)
if __name__ == "__main__":
main()
| bsd-3-clause |
mega-force/xbmc | lib/gtest/scripts/upload.py | 2511 | 51024 | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tool for uploading diffs from a version control system to the codereview app.
Usage summary: upload.py [options] [-- diff_options]
Diff options are passed to the diff command of the underlying system.
Supported version control systems:
Git
Mercurial
Subversion
It is important for Git/Mercurial users to specify a tree/node/branch to diff
against by using the '--rev' option.
"""
# This code is derived from appcfg.py in the App Engine SDK (open source),
# and from ASPN recipe #146306.
import cookielib
import getpass
import logging
import md5
import mimetypes
import optparse
import os
import re
import socket
import subprocess
import sys
import urllib
import urllib2
import urlparse
try:
import readline
except ImportError:
pass
# The logging verbosity:
# 0: Errors only.
# 1: Status messages.
# 2: Info logs.
# 3: Debug logs.
verbosity = 1
# Max size of patch or base file.
MAX_UPLOAD_SIZE = 900 * 1024
def GetEmail(prompt):
"""Prompts the user for their email address and returns it.
The last used email address is saved to a file and offered up as a suggestion
to the user. If the user presses enter without typing in anything the last
used email address is used. If the user enters a new address, it is saved
for next time we prompt.
"""
last_email_file_name = os.path.expanduser("~/.last_codereview_email_address")
last_email = ""
if os.path.exists(last_email_file_name):
try:
last_email_file = open(last_email_file_name, "r")
last_email = last_email_file.readline().strip("\n")
last_email_file.close()
prompt += " [%s]" % last_email
except IOError, e:
pass
email = raw_input(prompt + ": ").strip()
if email:
try:
last_email_file = open(last_email_file_name, "w")
last_email_file.write(email)
last_email_file.close()
except IOError, e:
pass
else:
email = last_email
return email
def StatusUpdate(msg):
"""Print a status message to stdout.
If 'verbosity' is greater than 0, print the message.
Args:
msg: The string to print.
"""
if verbosity > 0:
print msg
def ErrorExit(msg):
"""Print an error message to stderr and exit."""
print >>sys.stderr, msg
sys.exit(1)
class ClientLoginError(urllib2.HTTPError):
"""Raised to indicate there was an error authenticating with ClientLogin."""
def __init__(self, url, code, msg, headers, args):
urllib2.HTTPError.__init__(self, url, code, msg, headers, None)
self.args = args
self.reason = args["Error"]
class AbstractRpcServer(object):
"""Provides a common interface for a simple RPC server."""
def __init__(self, host, auth_function, host_override=None, extra_headers={},
save_cookies=False):
"""Creates a new HttpRpcServer.
Args:
host: The host to send requests to.
auth_function: A function that takes no arguments and returns an
(email, password) tuple when called. Will be called if authentication
is required.
host_override: The host header to send to the server (defaults to host).
extra_headers: A dict of extra headers to append to every request.
save_cookies: If True, save the authentication cookies to local disk.
If False, use an in-memory cookiejar instead. Subclasses must
implement this functionality. Defaults to False.
"""
self.host = host
self.host_override = host_override
self.auth_function = auth_function
self.authenticated = False
self.extra_headers = extra_headers
self.save_cookies = save_cookies
self.opener = self._GetOpener()
if self.host_override:
logging.info("Server: %s; Host: %s", self.host, self.host_override)
else:
logging.info("Server: %s", self.host)
def _GetOpener(self):
"""Returns an OpenerDirector for making HTTP requests.
Returns:
A urllib2.OpenerDirector object.
"""
raise NotImplementedError()
def _CreateRequest(self, url, data=None):
"""Creates a new urllib request."""
logging.debug("Creating request for: '%s' with payload:\n%s", url, data)
req = urllib2.Request(url, data=data)
if self.host_override:
req.add_header("Host", self.host_override)
for key, value in self.extra_headers.iteritems():
req.add_header(key, value)
return req
def _GetAuthToken(self, email, password):
"""Uses ClientLogin to authenticate the user, returning an auth token.
Args:
email: The user's email address
password: The user's password
Raises:
ClientLoginError: If there was an error authenticating with ClientLogin.
HTTPError: If there was some other form of HTTP error.
Returns:
The authentication token returned by ClientLogin.
"""
account_type = "GOOGLE"
if self.host.endswith(".google.com"):
# Needed for use inside Google.
account_type = "HOSTED"
req = self._CreateRequest(
url="https://www.google.com/accounts/ClientLogin",
data=urllib.urlencode({
"Email": email,
"Passwd": password,
"service": "ah",
"source": "rietveld-codereview-upload",
"accountType": account_type,
}),
)
try:
response = self.opener.open(req)
response_body = response.read()
response_dict = dict(x.split("=")
for x in response_body.split("\n") if x)
return response_dict["Auth"]
except urllib2.HTTPError, e:
if e.code == 403:
body = e.read()
response_dict = dict(x.split("=", 1) for x in body.split("\n") if x)
raise ClientLoginError(req.get_full_url(), e.code, e.msg,
e.headers, response_dict)
else:
raise
def _GetAuthCookie(self, auth_token):
"""Fetches authentication cookies for an authentication token.
Args:
auth_token: The authentication token returned by ClientLogin.
Raises:
HTTPError: If there was an error fetching the authentication cookies.
"""
# This is a dummy value to allow us to identify when we're successful.
continue_location = "http://localhost/"
args = {"continue": continue_location, "auth": auth_token}
req = self._CreateRequest("http://%s/_ah/login?%s" %
(self.host, urllib.urlencode(args)))
try:
response = self.opener.open(req)
except urllib2.HTTPError, e:
response = e
if (response.code != 302 or
response.info()["location"] != continue_location):
raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg,
response.headers, response.fp)
self.authenticated = True
def _Authenticate(self):
"""Authenticates the user.
The authentication process works as follows:
1) We get a username and password from the user
2) We use ClientLogin to obtain an AUTH token for the user
(see http://code.google.com/apis/accounts/AuthForInstalledApps.html).
3) We pass the auth token to /_ah/login on the server to obtain an
authentication cookie. If login was successful, it tries to redirect
us to the URL we provided.
If we attempt to access the upload API without first obtaining an
authentication cookie, it returns a 401 response and directs us to
authenticate ourselves with ClientLogin.
"""
for i in range(3):
credentials = self.auth_function()
try:
auth_token = self._GetAuthToken(credentials[0], credentials[1])
except ClientLoginError, e:
if e.reason == "BadAuthentication":
print >>sys.stderr, "Invalid username or password."
continue
if e.reason == "CaptchaRequired":
print >>sys.stderr, (
"Please go to\n"
"https://www.google.com/accounts/DisplayUnlockCaptcha\n"
"and verify you are a human. Then try again.")
break
if e.reason == "NotVerified":
print >>sys.stderr, "Account not verified."
break
if e.reason == "TermsNotAgreed":
print >>sys.stderr, "User has not agreed to TOS."
break
if e.reason == "AccountDeleted":
print >>sys.stderr, "The user account has been deleted."
break
if e.reason == "AccountDisabled":
print >>sys.stderr, "The user account has been disabled."
break
if e.reason == "ServiceDisabled":
print >>sys.stderr, ("The user's access to the service has been "
"disabled.")
break
if e.reason == "ServiceUnavailable":
print >>sys.stderr, "The service is not available; try again later."
break
raise
self._GetAuthCookie(auth_token)
return
def Send(self, request_path, payload=None,
content_type="application/octet-stream",
timeout=None,
**kwargs):
"""Sends an RPC and returns the response.
Args:
request_path: The path to send the request to, eg /api/appversion/create.
payload: The body of the request, or None to send an empty request.
content_type: The Content-Type header to use.
timeout: timeout in seconds; default None i.e. no timeout.
(Note: for large requests on OS X, the timeout doesn't work right.)
kwargs: Any keyword arguments are converted into query string parameters.
Returns:
The response body, as a string.
"""
# TODO: Don't require authentication. Let the server say
# whether it is necessary.
if not self.authenticated:
self._Authenticate()
old_timeout = socket.getdefaulttimeout()
socket.setdefaulttimeout(timeout)
try:
tries = 0
while True:
tries += 1
args = dict(kwargs)
url = "http://%s%s" % (self.host, request_path)
if args:
url += "?" + urllib.urlencode(args)
req = self._CreateRequest(url=url, data=payload)
req.add_header("Content-Type", content_type)
try:
f = self.opener.open(req)
response = f.read()
f.close()
return response
except urllib2.HTTPError, e:
if tries > 3:
raise
elif e.code == 401:
self._Authenticate()
## elif e.code >= 500 and e.code < 600:
## # Server Error - try again.
## continue
else:
raise
finally:
socket.setdefaulttimeout(old_timeout)
class HttpRpcServer(AbstractRpcServer):
"""Provides a simplified RPC-style interface for HTTP requests."""
def _Authenticate(self):
"""Save the cookie jar after authentication."""
super(HttpRpcServer, self)._Authenticate()
if self.save_cookies:
StatusUpdate("Saving authentication cookies to %s" % self.cookie_file)
self.cookie_jar.save()
def _GetOpener(self):
"""Returns an OpenerDirector that supports cookies and ignores redirects.
Returns:
A urllib2.OpenerDirector object.
"""
opener = urllib2.OpenerDirector()
opener.add_handler(urllib2.ProxyHandler())
opener.add_handler(urllib2.UnknownHandler())
opener.add_handler(urllib2.HTTPHandler())
opener.add_handler(urllib2.HTTPDefaultErrorHandler())
opener.add_handler(urllib2.HTTPSHandler())
opener.add_handler(urllib2.HTTPErrorProcessor())
if self.save_cookies:
self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies")
self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file)
if os.path.exists(self.cookie_file):
try:
self.cookie_jar.load()
self.authenticated = True
StatusUpdate("Loaded authentication cookies from %s" %
self.cookie_file)
except (cookielib.LoadError, IOError):
# Failed to load cookies - just ignore them.
pass
else:
# Create an empty cookie file with mode 600
fd = os.open(self.cookie_file, os.O_CREAT, 0600)
os.close(fd)
# Always chmod the cookie file
os.chmod(self.cookie_file, 0600)
else:
# Don't save cookies across runs of update.py.
self.cookie_jar = cookielib.CookieJar()
opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar))
return opener
parser = optparse.OptionParser(usage="%prog [options] [-- diff_options]")
parser.add_option("-y", "--assume_yes", action="store_true",
dest="assume_yes", default=False,
help="Assume that the answer to yes/no questions is 'yes'.")
# Logging
group = parser.add_option_group("Logging options")
group.add_option("-q", "--quiet", action="store_const", const=0,
dest="verbose", help="Print errors only.")
group.add_option("-v", "--verbose", action="store_const", const=2,
dest="verbose", default=1,
help="Print info level logs (default).")
group.add_option("--noisy", action="store_const", const=3,
dest="verbose", help="Print all logs.")
# Review server
group = parser.add_option_group("Review server options")
group.add_option("-s", "--server", action="store", dest="server",
default="codereview.appspot.com",
metavar="SERVER",
help=("The server to upload to. The format is host[:port]. "
"Defaults to 'codereview.appspot.com'."))
group.add_option("-e", "--email", action="store", dest="email",
metavar="EMAIL", default=None,
help="The username to use. Will prompt if omitted.")
group.add_option("-H", "--host", action="store", dest="host",
metavar="HOST", default=None,
help="Overrides the Host header sent with all RPCs.")
group.add_option("--no_cookies", action="store_false",
dest="save_cookies", default=True,
help="Do not save authentication cookies to local disk.")
# Issue
group = parser.add_option_group("Issue options")
group.add_option("-d", "--description", action="store", dest="description",
metavar="DESCRIPTION", default=None,
help="Optional description when creating an issue.")
group.add_option("-f", "--description_file", action="store",
dest="description_file", metavar="DESCRIPTION_FILE",
default=None,
help="Optional path of a file that contains "
"the description when creating an issue.")
group.add_option("-r", "--reviewers", action="store", dest="reviewers",
metavar="REVIEWERS", default=None,
help="Add reviewers (comma separated email addresses).")
group.add_option("--cc", action="store", dest="cc",
metavar="CC", default=None,
help="Add CC (comma separated email addresses).")
# Upload options
group = parser.add_option_group("Patch options")
group.add_option("-m", "--message", action="store", dest="message",
metavar="MESSAGE", default=None,
help="A message to identify the patch. "
"Will prompt if omitted.")
group.add_option("-i", "--issue", type="int", action="store",
metavar="ISSUE", default=None,
help="Issue number to which to add. Defaults to new issue.")
group.add_option("--download_base", action="store_true",
dest="download_base", default=False,
help="Base files will be downloaded by the server "
"(side-by-side diffs may not work on files with CRs).")
group.add_option("--rev", action="store", dest="revision",
metavar="REV", default=None,
help="Branch/tree/revision to diff against (used by DVCS).")
group.add_option("--send_mail", action="store_true",
dest="send_mail", default=False,
help="Send notification email to reviewers.")
def GetRpcServer(options):
"""Returns an instance of an AbstractRpcServer.
Returns:
A new AbstractRpcServer, on which RPC calls can be made.
"""
rpc_server_class = HttpRpcServer
def GetUserCredentials():
"""Prompts the user for a username and password."""
email = options.email
if email is None:
email = GetEmail("Email (login for uploading to %s)" % options.server)
password = getpass.getpass("Password for %s: " % email)
return (email, password)
# If this is the dev_appserver, use fake authentication.
host = (options.host or options.server).lower()
if host == "localhost" or host.startswith("localhost:"):
email = options.email
if email is None:
email = "test@example.com"
logging.info("Using debug user %s. Override with --email" % email)
server = rpc_server_class(
options.server,
lambda: (email, "password"),
host_override=options.host,
extra_headers={"Cookie":
'dev_appserver_login="%s:False"' % email},
save_cookies=options.save_cookies)
# Don't try to talk to ClientLogin.
server.authenticated = True
return server
return rpc_server_class(options.server, GetUserCredentials,
host_override=options.host,
save_cookies=options.save_cookies)
def EncodeMultipartFormData(fields, files):
"""Encode form fields for multipart/form-data.
Args:
fields: A sequence of (name, value) elements for regular form fields.
files: A sequence of (name, filename, value) elements for data to be
uploaded as files.
Returns:
(content_type, body) ready for httplib.HTTP instance.
Source:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
"""
BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-'
CRLF = '\r\n'
lines = []
for (key, value) in fields:
lines.append('--' + BOUNDARY)
lines.append('Content-Disposition: form-data; name="%s"' % key)
lines.append('')
lines.append(value)
for (key, filename, value) in files:
lines.append('--' + BOUNDARY)
lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' %
(key, filename))
lines.append('Content-Type: %s' % GetContentType(filename))
lines.append('')
lines.append(value)
lines.append('--' + BOUNDARY + '--')
lines.append('')
body = CRLF.join(lines)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
return content_type, body
def GetContentType(filename):
"""Helper to guess the content-type from the filename."""
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
# Use a shell for subcommands on Windows to get a PATH search.
use_shell = sys.platform.startswith("win")
def RunShellWithReturnCode(command, print_output=False,
universal_newlines=True):
"""Executes a command and returns the output from stdout and the return code.
Args:
command: Command to execute.
print_output: If True, the output is printed to stdout.
If False, both stdout and stderr are ignored.
universal_newlines: Use universal_newlines flag (default: True).
Returns:
Tuple (output, return code)
"""
logging.info("Running %s", command)
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=use_shell, universal_newlines=universal_newlines)
if print_output:
output_array = []
while True:
line = p.stdout.readline()
if not line:
break
print line.strip("\n")
output_array.append(line)
output = "".join(output_array)
else:
output = p.stdout.read()
p.wait()
errout = p.stderr.read()
if print_output and errout:
print >>sys.stderr, errout
p.stdout.close()
p.stderr.close()
return output, p.returncode
def RunShell(command, silent_ok=False, universal_newlines=True,
print_output=False):
data, retcode = RunShellWithReturnCode(command, print_output,
universal_newlines)
if retcode:
ErrorExit("Got error status from %s:\n%s" % (command, data))
if not silent_ok and not data:
ErrorExit("No output from %s" % command)
return data
class VersionControlSystem(object):
"""Abstract base class providing an interface to the VCS."""
def __init__(self, options):
"""Constructor.
Args:
options: Command line options.
"""
self.options = options
def GenerateDiff(self, args):
"""Return the current diff as a string.
Args:
args: Extra arguments to pass to the diff command.
"""
raise NotImplementedError(
"abstract method -- subclass %s must override" % self.__class__)
def GetUnknownFiles(self):
"""Return a list of files unknown to the VCS."""
raise NotImplementedError(
"abstract method -- subclass %s must override" % self.__class__)
def CheckForUnknownFiles(self):
"""Show an "are you sure?" prompt if there are unknown files."""
unknown_files = self.GetUnknownFiles()
if unknown_files:
print "The following files are not added to version control:"
for line in unknown_files:
print line
prompt = "Are you sure to continue?(y/N) "
answer = raw_input(prompt).strip()
if answer != "y":
ErrorExit("User aborted")
def GetBaseFile(self, filename):
"""Get the content of the upstream version of a file.
Returns:
A tuple (base_content, new_content, is_binary, status)
base_content: The contents of the base file.
new_content: For text files, this is empty. For binary files, this is
the contents of the new file, since the diff output won't contain
information to reconstruct the current file.
is_binary: True iff the file is binary.
status: The status of the file.
"""
raise NotImplementedError(
"abstract method -- subclass %s must override" % self.__class__)
def GetBaseFiles(self, diff):
"""Helper that calls GetBase file for each file in the patch.
Returns:
A dictionary that maps from filename to GetBaseFile's tuple. Filenames
are retrieved based on lines that start with "Index:" or
"Property changes on:".
"""
files = {}
for line in diff.splitlines(True):
if line.startswith('Index:') or line.startswith('Property changes on:'):
unused, filename = line.split(':', 1)
# On Windows if a file has property changes its filename uses '\'
# instead of '/'.
filename = filename.strip().replace('\\', '/')
files[filename] = self.GetBaseFile(filename)
return files
def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options,
files):
"""Uploads the base files (and if necessary, the current ones as well)."""
def UploadFile(filename, file_id, content, is_binary, status, is_base):
"""Uploads a file to the server."""
file_too_large = False
if is_base:
type = "base"
else:
type = "current"
if len(content) > MAX_UPLOAD_SIZE:
print ("Not uploading the %s file for %s because it's too large." %
(type, filename))
file_too_large = True
content = ""
checksum = md5.new(content).hexdigest()
if options.verbose > 0 and not file_too_large:
print "Uploading %s file for %s" % (type, filename)
url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id)
form_fields = [("filename", filename),
("status", status),
("checksum", checksum),
("is_binary", str(is_binary)),
("is_current", str(not is_base)),
]
if file_too_large:
form_fields.append(("file_too_large", "1"))
if options.email:
form_fields.append(("user", options.email))
ctype, body = EncodeMultipartFormData(form_fields,
[("data", filename, content)])
response_body = rpc_server.Send(url, body,
content_type=ctype)
if not response_body.startswith("OK"):
StatusUpdate(" --> %s" % response_body)
sys.exit(1)
patches = dict()
[patches.setdefault(v, k) for k, v in patch_list]
for filename in patches.keys():
base_content, new_content, is_binary, status = files[filename]
file_id_str = patches.get(filename)
if file_id_str.find("nobase") != -1:
base_content = None
file_id_str = file_id_str[file_id_str.rfind("_") + 1:]
file_id = int(file_id_str)
if base_content != None:
UploadFile(filename, file_id, base_content, is_binary, status, True)
if new_content != None:
UploadFile(filename, file_id, new_content, is_binary, status, False)
def IsImage(self, filename):
"""Returns true if the filename has an image extension."""
mimetype = mimetypes.guess_type(filename)[0]
if not mimetype:
return False
return mimetype.startswith("image/")
class SubversionVCS(VersionControlSystem):
"""Implementation of the VersionControlSystem interface for Subversion."""
def __init__(self, options):
super(SubversionVCS, self).__init__(options)
if self.options.revision:
match = re.match(r"(\d+)(:(\d+))?", self.options.revision)
if not match:
ErrorExit("Invalid Subversion revision %s." % self.options.revision)
self.rev_start = match.group(1)
self.rev_end = match.group(3)
else:
self.rev_start = self.rev_end = None
# Cache output from "svn list -r REVNO dirname".
# Keys: dirname, Values: 2-tuple (ouput for start rev and end rev).
self.svnls_cache = {}
# SVN base URL is required to fetch files deleted in an older revision.
# Result is cached to not guess it over and over again in GetBaseFile().
required = self.options.download_base or self.options.revision is not None
self.svn_base = self._GuessBase(required)
def GuessBase(self, required):
"""Wrapper for _GuessBase."""
return self.svn_base
def _GuessBase(self, required):
"""Returns the SVN base URL.
Args:
required: If true, exits if the url can't be guessed, otherwise None is
returned.
"""
info = RunShell(["svn", "info"])
for line in info.splitlines():
words = line.split()
if len(words) == 2 and words[0] == "URL:":
url = words[1]
scheme, netloc, path, params, query, fragment = urlparse.urlparse(url)
username, netloc = urllib.splituser(netloc)
if username:
logging.info("Removed username from base URL")
if netloc.endswith("svn.python.org"):
if netloc == "svn.python.org":
if path.startswith("/projects/"):
path = path[9:]
elif netloc != "pythondev@svn.python.org":
ErrorExit("Unrecognized Python URL: %s" % url)
base = "http://svn.python.org/view/*checkout*%s/" % path
logging.info("Guessed Python base = %s", base)
elif netloc.endswith("svn.collab.net"):
if path.startswith("/repos/"):
path = path[6:]
base = "http://svn.collab.net/viewvc/*checkout*%s/" % path
logging.info("Guessed CollabNet base = %s", base)
elif netloc.endswith(".googlecode.com"):
path = path + "/"
base = urlparse.urlunparse(("http", netloc, path, params,
query, fragment))
logging.info("Guessed Google Code base = %s", base)
else:
path = path + "/"
base = urlparse.urlunparse((scheme, netloc, path, params,
query, fragment))
logging.info("Guessed base = %s", base)
return base
if required:
ErrorExit("Can't find URL in output from svn info")
return None
def GenerateDiff(self, args):
cmd = ["svn", "diff"]
if self.options.revision:
cmd += ["-r", self.options.revision]
cmd.extend(args)
data = RunShell(cmd)
count = 0
for line in data.splitlines():
if line.startswith("Index:") or line.startswith("Property changes on:"):
count += 1
logging.info(line)
if not count:
ErrorExit("No valid patches found in output from svn diff")
return data
def _CollapseKeywords(self, content, keyword_str):
"""Collapses SVN keywords."""
# svn cat translates keywords but svn diff doesn't. As a result of this
# behavior patching.PatchChunks() fails with a chunk mismatch error.
# This part was originally written by the Review Board development team
# who had the same problem (http://reviews.review-board.org/r/276/).
# Mapping of keywords to known aliases
svn_keywords = {
# Standard keywords
'Date': ['Date', 'LastChangedDate'],
'Revision': ['Revision', 'LastChangedRevision', 'Rev'],
'Author': ['Author', 'LastChangedBy'],
'HeadURL': ['HeadURL', 'URL'],
'Id': ['Id'],
# Aliases
'LastChangedDate': ['LastChangedDate', 'Date'],
'LastChangedRevision': ['LastChangedRevision', 'Rev', 'Revision'],
'LastChangedBy': ['LastChangedBy', 'Author'],
'URL': ['URL', 'HeadURL'],
}
def repl(m):
if m.group(2):
return "$%s::%s$" % (m.group(1), " " * len(m.group(3)))
return "$%s$" % m.group(1)
keywords = [keyword
for name in keyword_str.split(" ")
for keyword in svn_keywords.get(name, [])]
return re.sub(r"\$(%s):(:?)([^\$]+)\$" % '|'.join(keywords), repl, content)
def GetUnknownFiles(self):
status = RunShell(["svn", "status", "--ignore-externals"], silent_ok=True)
unknown_files = []
for line in status.split("\n"):
if line and line[0] == "?":
unknown_files.append(line)
return unknown_files
def ReadFile(self, filename):
"""Returns the contents of a file."""
file = open(filename, 'rb')
result = ""
try:
result = file.read()
finally:
file.close()
return result
def GetStatus(self, filename):
"""Returns the status of a file."""
if not self.options.revision:
status = RunShell(["svn", "status", "--ignore-externals", filename])
if not status:
ErrorExit("svn status returned no output for %s" % filename)
status_lines = status.splitlines()
# If file is in a cl, the output will begin with
# "\n--- Changelist 'cl_name':\n". See
# http://svn.collab.net/repos/svn/trunk/notes/changelist-design.txt
if (len(status_lines) == 3 and
not status_lines[0] and
status_lines[1].startswith("--- Changelist")):
status = status_lines[2]
else:
status = status_lines[0]
# If we have a revision to diff against we need to run "svn list"
# for the old and the new revision and compare the results to get
# the correct status for a file.
else:
dirname, relfilename = os.path.split(filename)
if dirname not in self.svnls_cache:
cmd = ["svn", "list", "-r", self.rev_start, dirname or "."]
out, returncode = RunShellWithReturnCode(cmd)
if returncode:
ErrorExit("Failed to get status for %s." % filename)
old_files = out.splitlines()
args = ["svn", "list"]
if self.rev_end:
args += ["-r", self.rev_end]
cmd = args + [dirname or "."]
out, returncode = RunShellWithReturnCode(cmd)
if returncode:
ErrorExit("Failed to run command %s" % cmd)
self.svnls_cache[dirname] = (old_files, out.splitlines())
old_files, new_files = self.svnls_cache[dirname]
if relfilename in old_files and relfilename not in new_files:
status = "D "
elif relfilename in old_files and relfilename in new_files:
status = "M "
else:
status = "A "
return status
def GetBaseFile(self, filename):
status = self.GetStatus(filename)
base_content = None
new_content = None
# If a file is copied its status will be "A +", which signifies
# "addition-with-history". See "svn st" for more information. We need to
# upload the original file or else diff parsing will fail if the file was
# edited.
if status[0] == "A" and status[3] != "+":
# We'll need to upload the new content if we're adding a binary file
# since diff's output won't contain it.
mimetype = RunShell(["svn", "propget", "svn:mime-type", filename],
silent_ok=True)
base_content = ""
is_binary = mimetype and not mimetype.startswith("text/")
if is_binary and self.IsImage(filename):
new_content = self.ReadFile(filename)
elif (status[0] in ("M", "D", "R") or
(status[0] == "A" and status[3] == "+") or # Copied file.
(status[0] == " " and status[1] == "M")): # Property change.
args = []
if self.options.revision:
url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
else:
# Don't change filename, it's needed later.
url = filename
args += ["-r", "BASE"]
cmd = ["svn"] + args + ["propget", "svn:mime-type", url]
mimetype, returncode = RunShellWithReturnCode(cmd)
if returncode:
# File does not exist in the requested revision.
# Reset mimetype, it contains an error message.
mimetype = ""
get_base = False
is_binary = mimetype and not mimetype.startswith("text/")
if status[0] == " ":
# Empty base content just to force an upload.
base_content = ""
elif is_binary:
if self.IsImage(filename):
get_base = True
if status[0] == "M":
if not self.rev_end:
new_content = self.ReadFile(filename)
else:
url = "%s/%s@%s" % (self.svn_base, filename, self.rev_end)
new_content = RunShell(["svn", "cat", url],
universal_newlines=True, silent_ok=True)
else:
base_content = ""
else:
get_base = True
if get_base:
if is_binary:
universal_newlines = False
else:
universal_newlines = True
if self.rev_start:
# "svn cat -r REV delete_file.txt" doesn't work. cat requires
# the full URL with "@REV" appended instead of using "-r" option.
url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
base_content = RunShell(["svn", "cat", url],
universal_newlines=universal_newlines,
silent_ok=True)
else:
base_content = RunShell(["svn", "cat", filename],
universal_newlines=universal_newlines,
silent_ok=True)
if not is_binary:
args = []
if self.rev_start:
url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
else:
url = filename
args += ["-r", "BASE"]
cmd = ["svn"] + args + ["propget", "svn:keywords", url]
keywords, returncode = RunShellWithReturnCode(cmd)
if keywords and not returncode:
base_content = self._CollapseKeywords(base_content, keywords)
else:
StatusUpdate("svn status returned unexpected output: %s" % status)
sys.exit(1)
return base_content, new_content, is_binary, status[0:5]
class GitVCS(VersionControlSystem):
"""Implementation of the VersionControlSystem interface for Git."""
def __init__(self, options):
super(GitVCS, self).__init__(options)
# Map of filename -> hash of base file.
self.base_hashes = {}
def GenerateDiff(self, extra_args):
# This is more complicated than svn's GenerateDiff because we must convert
# the diff output to include an svn-style "Index:" line as well as record
# the hashes of the base files, so we can upload them along with our diff.
if self.options.revision:
extra_args = [self.options.revision] + extra_args
gitdiff = RunShell(["git", "diff", "--full-index"] + extra_args)
svndiff = []
filecount = 0
filename = None
for line in gitdiff.splitlines():
match = re.match(r"diff --git a/(.*) b/.*$", line)
if match:
filecount += 1
filename = match.group(1)
svndiff.append("Index: %s\n" % filename)
else:
# The "index" line in a git diff looks like this (long hashes elided):
# index 82c0d44..b2cee3f 100755
# We want to save the left hash, as that identifies the base file.
match = re.match(r"index (\w+)\.\.", line)
if match:
self.base_hashes[filename] = match.group(1)
svndiff.append(line + "\n")
if not filecount:
ErrorExit("No valid patches found in output from git diff")
return "".join(svndiff)
def GetUnknownFiles(self):
status = RunShell(["git", "ls-files", "--exclude-standard", "--others"],
silent_ok=True)
return status.splitlines()
def GetBaseFile(self, filename):
hash = self.base_hashes[filename]
base_content = None
new_content = None
is_binary = False
if hash == "0" * 40: # All-zero hash indicates no base file.
status = "A"
base_content = ""
else:
status = "M"
base_content, returncode = RunShellWithReturnCode(["git", "show", hash])
if returncode:
ErrorExit("Got error status from 'git show %s'" % hash)
return (base_content, new_content, is_binary, status)
class MercurialVCS(VersionControlSystem):
"""Implementation of the VersionControlSystem interface for Mercurial."""
def __init__(self, options, repo_dir):
super(MercurialVCS, self).__init__(options)
# Absolute path to repository (we can be in a subdir)
self.repo_dir = os.path.normpath(repo_dir)
# Compute the subdir
cwd = os.path.normpath(os.getcwd())
assert cwd.startswith(self.repo_dir)
self.subdir = cwd[len(self.repo_dir):].lstrip(r"\/")
if self.options.revision:
self.base_rev = self.options.revision
else:
self.base_rev = RunShell(["hg", "parent", "-q"]).split(':')[1].strip()
def _GetRelPath(self, filename):
"""Get relative path of a file according to the current directory,
given its logical path in the repo."""
assert filename.startswith(self.subdir), filename
return filename[len(self.subdir):].lstrip(r"\/")
def GenerateDiff(self, extra_args):
# If no file specified, restrict to the current subdir
extra_args = extra_args or ["."]
cmd = ["hg", "diff", "--git", "-r", self.base_rev] + extra_args
data = RunShell(cmd, silent_ok=True)
svndiff = []
filecount = 0
for line in data.splitlines():
m = re.match("diff --git a/(\S+) b/(\S+)", line)
if m:
# Modify line to make it look like as it comes from svn diff.
# With this modification no changes on the server side are required
# to make upload.py work with Mercurial repos.
# NOTE: for proper handling of moved/copied files, we have to use
# the second filename.
filename = m.group(2)
svndiff.append("Index: %s" % filename)
svndiff.append("=" * 67)
filecount += 1
logging.info(line)
else:
svndiff.append(line)
if not filecount:
ErrorExit("No valid patches found in output from hg diff")
return "\n".join(svndiff) + "\n"
def GetUnknownFiles(self):
"""Return a list of files unknown to the VCS."""
args = []
status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."],
silent_ok=True)
unknown_files = []
for line in status.splitlines():
st, fn = line.split(" ", 1)
if st == "?":
unknown_files.append(fn)
return unknown_files
def GetBaseFile(self, filename):
# "hg status" and "hg cat" both take a path relative to the current subdir
# rather than to the repo root, but "hg diff" has given us the full path
# to the repo root.
base_content = ""
new_content = None
is_binary = False
oldrelpath = relpath = self._GetRelPath(filename)
# "hg status -C" returns two lines for moved/copied files, one otherwise
out = RunShell(["hg", "status", "-C", "--rev", self.base_rev, relpath])
out = out.splitlines()
# HACK: strip error message about missing file/directory if it isn't in
# the working copy
if out[0].startswith('%s: ' % relpath):
out = out[1:]
if len(out) > 1:
# Moved/copied => considered as modified, use old filename to
# retrieve base contents
oldrelpath = out[1].strip()
status = "M"
else:
status, _ = out[0].split(' ', 1)
if status != "A":
base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath],
silent_ok=True)
is_binary = "\0" in base_content # Mercurial's heuristic
if status != "R":
new_content = open(relpath, "rb").read()
is_binary = is_binary or "\0" in new_content
if is_binary and base_content:
# Fetch again without converting newlines
base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath],
silent_ok=True, universal_newlines=False)
if not is_binary or not self.IsImage(relpath):
new_content = None
return base_content, new_content, is_binary, status
# NOTE: The SplitPatch function is duplicated in engine.py, keep them in sync.
def SplitPatch(data):
"""Splits a patch into separate pieces for each file.
Args:
data: A string containing the output of svn diff.
Returns:
A list of 2-tuple (filename, text) where text is the svn diff output
pertaining to filename.
"""
patches = []
filename = None
diff = []
for line in data.splitlines(True):
new_filename = None
if line.startswith('Index:'):
unused, new_filename = line.split(':', 1)
new_filename = new_filename.strip()
elif line.startswith('Property changes on:'):
unused, temp_filename = line.split(':', 1)
# When a file is modified, paths use '/' between directories, however
# when a property is modified '\' is used on Windows. Make them the same
# otherwise the file shows up twice.
temp_filename = temp_filename.strip().replace('\\', '/')
if temp_filename != filename:
# File has property changes but no modifications, create a new diff.
new_filename = temp_filename
if new_filename:
if filename and diff:
patches.append((filename, ''.join(diff)))
filename = new_filename
diff = [line]
continue
if diff is not None:
diff.append(line)
if filename and diff:
patches.append((filename, ''.join(diff)))
return patches
def UploadSeparatePatches(issue, rpc_server, patchset, data, options):
"""Uploads a separate patch for each file in the diff output.
Returns a list of [patch_key, filename] for each file.
"""
patches = SplitPatch(data)
rv = []
for patch in patches:
if len(patch[1]) > MAX_UPLOAD_SIZE:
print ("Not uploading the patch for " + patch[0] +
" because the file is too large.")
continue
form_fields = [("filename", patch[0])]
if not options.download_base:
form_fields.append(("content_upload", "1"))
files = [("data", "data.diff", patch[1])]
ctype, body = EncodeMultipartFormData(form_fields, files)
url = "/%d/upload_patch/%d" % (int(issue), int(patchset))
print "Uploading patch for " + patch[0]
response_body = rpc_server.Send(url, body, content_type=ctype)
lines = response_body.splitlines()
if not lines or lines[0] != "OK":
StatusUpdate(" --> %s" % response_body)
sys.exit(1)
rv.append([lines[1], patch[0]])
return rv
def GuessVCS(options):
"""Helper to guess the version control system.
This examines the current directory, guesses which VersionControlSystem
we're using, and returns an instance of the appropriate class. Exit with an
error if we can't figure it out.
Returns:
A VersionControlSystem instance. Exits if the VCS can't be guessed.
"""
# Mercurial has a command to get the base directory of a repository
# Try running it, but don't die if we don't have hg installed.
# NOTE: we try Mercurial first as it can sit on top of an SVN working copy.
try:
out, returncode = RunShellWithReturnCode(["hg", "root"])
if returncode == 0:
return MercurialVCS(options, out.strip())
except OSError, (errno, message):
if errno != 2: # ENOENT -- they don't have hg installed.
raise
# Subversion has a .svn in all working directories.
if os.path.isdir('.svn'):
logging.info("Guessed VCS = Subversion")
return SubversionVCS(options)
# Git has a command to test if you're in a git tree.
# Try running it, but don't die if we don't have git installed.
try:
out, returncode = RunShellWithReturnCode(["git", "rev-parse",
"--is-inside-work-tree"])
if returncode == 0:
return GitVCS(options)
except OSError, (errno, message):
if errno != 2: # ENOENT -- they don't have git installed.
raise
ErrorExit(("Could not guess version control system. "
"Are you in a working copy directory?"))
def RealMain(argv, data=None):
"""The real main function.
Args:
argv: Command line arguments.
data: Diff contents. If None (default) the diff is generated by
the VersionControlSystem implementation returned by GuessVCS().
Returns:
A 2-tuple (issue id, patchset id).
The patchset id is None if the base files are not uploaded by this
script (applies only to SVN checkouts).
"""
logging.basicConfig(format=("%(asctime).19s %(levelname)s %(filename)s:"
"%(lineno)s %(message)s "))
os.environ['LC_ALL'] = 'C'
options, args = parser.parse_args(argv[1:])
global verbosity
verbosity = options.verbose
if verbosity >= 3:
logging.getLogger().setLevel(logging.DEBUG)
elif verbosity >= 2:
logging.getLogger().setLevel(logging.INFO)
vcs = GuessVCS(options)
if isinstance(vcs, SubversionVCS):
# base field is only allowed for Subversion.
# Note: Fetching base files may become deprecated in future releases.
base = vcs.GuessBase(options.download_base)
else:
base = None
if not base and options.download_base:
options.download_base = True
logging.info("Enabled upload of base file")
if not options.assume_yes:
vcs.CheckForUnknownFiles()
if data is None:
data = vcs.GenerateDiff(args)
files = vcs.GetBaseFiles(data)
if verbosity >= 1:
print "Upload server:", options.server, "(change with -s/--server)"
if options.issue:
prompt = "Message describing this patch set: "
else:
prompt = "New issue subject: "
message = options.message or raw_input(prompt).strip()
if not message:
ErrorExit("A non-empty message is required")
rpc_server = GetRpcServer(options)
form_fields = [("subject", message)]
if base:
form_fields.append(("base", base))
if options.issue:
form_fields.append(("issue", str(options.issue)))
if options.email:
form_fields.append(("user", options.email))
if options.reviewers:
for reviewer in options.reviewers.split(','):
if "@" in reviewer and not reviewer.split("@")[1].count(".") == 1:
ErrorExit("Invalid email address: %s" % reviewer)
form_fields.append(("reviewers", options.reviewers))
if options.cc:
for cc in options.cc.split(','):
if "@" in cc and not cc.split("@")[1].count(".") == 1:
ErrorExit("Invalid email address: %s" % cc)
form_fields.append(("cc", options.cc))
description = options.description
if options.description_file:
if options.description:
ErrorExit("Can't specify description and description_file")
file = open(options.description_file, 'r')
description = file.read()
file.close()
if description:
form_fields.append(("description", description))
# Send a hash of all the base file so the server can determine if a copy
# already exists in an earlier patchset.
base_hashes = ""
for file, info in files.iteritems():
if not info[0] is None:
checksum = md5.new(info[0]).hexdigest()
if base_hashes:
base_hashes += "|"
base_hashes += checksum + ":" + file
form_fields.append(("base_hashes", base_hashes))
# If we're uploading base files, don't send the email before the uploads, so
# that it contains the file status.
if options.send_mail and options.download_base:
form_fields.append(("send_mail", "1"))
if not options.download_base:
form_fields.append(("content_upload", "1"))
if len(data) > MAX_UPLOAD_SIZE:
print "Patch is large, so uploading file patches separately."
uploaded_diff_file = []
form_fields.append(("separate_patches", "1"))
else:
uploaded_diff_file = [("data", "data.diff", data)]
ctype, body = EncodeMultipartFormData(form_fields, uploaded_diff_file)
response_body = rpc_server.Send("/upload", body, content_type=ctype)
patchset = None
if not options.download_base or not uploaded_diff_file:
lines = response_body.splitlines()
if len(lines) >= 2:
msg = lines[0]
patchset = lines[1].strip()
patches = [x.split(" ", 1) for x in lines[2:]]
else:
msg = response_body
else:
msg = response_body
StatusUpdate(msg)
if not response_body.startswith("Issue created.") and \
not response_body.startswith("Issue updated."):
sys.exit(0)
issue = msg[msg.rfind("/")+1:]
if not uploaded_diff_file:
result = UploadSeparatePatches(issue, rpc_server, patchset, data, options)
if not options.download_base:
patches = result
if not options.download_base:
vcs.UploadBaseFiles(issue, rpc_server, patches, patchset, options, files)
if options.send_mail:
rpc_server.Send("/" + issue + "/mail", payload="")
return issue, patchset
def main():
try:
RealMain(sys.argv)
except KeyboardInterrupt:
print
StatusUpdate("Interrupted.")
sys.exit(1)
if __name__ == "__main__":
main()
| gpl-2.0 |
kenwang815/KodiPlugins | script.module.oceanktv/lib/youtube_dl/extractor/yam.py | 17 | 4213 | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_urlparse
from ..utils import (
float_or_none,
month_by_abbreviation,
ExtractorError,
get_element_by_attribute,
)
class YamIE(InfoExtractor):
IE_DESC = '蕃薯藤yam天空部落'
_VALID_URL = r'https?://mymedia.yam.com/m/(?P<id>\d+)'
_TESTS = [{
# An audio hosted on Yam
'url': 'http://mymedia.yam.com/m/2283921',
'md5': 'c011b8e262a52d5473d9c2e3c9963b9c',
'info_dict': {
'id': '2283921',
'ext': 'mp3',
'title': '發現 - 趙薇 京華煙雲主題曲',
'description': '發現 - 趙薇 京華煙雲主題曲',
'uploader_id': 'princekt',
'upload_date': '20080807',
'duration': 313.0,
}
}, {
# An external video hosted on YouTube
'url': 'http://mymedia.yam.com/m/3599430',
'md5': '03127cf10d8f35d120a9e8e52e3b17c6',
'info_dict': {
'id': 'CNpEoQlrIgA',
'ext': 'mp4',
'upload_date': '20150306',
'uploader': '新莊社大瑜伽社',
'description': 'md5:11e2e405311633ace874f2e6226c8b17',
'uploader_id': '2323agoy',
'title': '20090412陽明山二子坪-1',
},
'skip': 'Video does not exist',
}, {
'url': 'http://mymedia.yam.com/m/3598173',
'info_dict': {
'id': '3598173',
'ext': 'mp4',
},
'skip': 'cause Yam system error',
}, {
'url': 'http://mymedia.yam.com/m/3599437',
'info_dict': {
'id': '3599437',
'ext': 'mp4',
},
'skip': 'invalid YouTube URL',
}, {
'url': 'http://mymedia.yam.com/m/2373534',
'md5': '7ff74b91b7a817269d83796f8c5890b1',
'info_dict': {
'id': '2373534',
'ext': 'mp3',
'title': '林俊傑&蔡卓妍-小酒窩',
'description': 'md5:904003395a0fcce6cfb25028ff468420',
'upload_date': '20080928',
'uploader_id': 'onliner2',
}
}]
def _real_extract(self, url):
video_id = self._match_id(url)
page = self._download_webpage(url, video_id)
# Check for errors
system_msg = self._html_search_regex(
r'系統訊息(?:<br>|\n|\r)*([^<>]+)<br>', page, 'system message',
default=None)
if system_msg:
raise ExtractorError(system_msg, expected=True)
# Is it hosted externally on YouTube?
youtube_url = self._html_search_regex(
r'<embed src="(http://www.youtube.com/[^"]+)"',
page, 'YouTube url', default=None)
if youtube_url:
return self.url_result(youtube_url, 'Youtube')
title = self._html_search_regex(
r'<h1[^>]+class="heading"[^>]*>\s*(.+)\s*</h1>', page, 'title')
api_page = self._download_webpage(
'http://mymedia.yam.com/api/a/?pID=' + video_id, video_id,
note='Downloading API page')
api_result_obj = compat_urlparse.parse_qs(api_page)
info_table = get_element_by_attribute('class', 'info', page)
uploader_id = self._html_search_regex(
r'<!-- 發表作者 -->:[\n ]+<a href="/([a-z0-9]+)"',
info_table, 'uploader id', fatal=False)
mobj = re.search(r'<!-- 發表於 -->(?P<mon>[A-Z][a-z]{2})\s+' +
r'(?P<day>\d{1,2}), (?P<year>\d{4})', page)
if mobj:
upload_date = '%s%02d%02d' % (
mobj.group('year'),
month_by_abbreviation(mobj.group('mon')),
int(mobj.group('day')))
else:
upload_date = None
duration = float_or_none(api_result_obj['totaltime'][0], scale=1000)
return {
'id': video_id,
'url': api_result_obj['mp3file'][0],
'title': title,
'description': self._html_search_meta('description', page),
'duration': duration,
'uploader_id': uploader_id,
'upload_date': upload_date,
}
| gpl-2.0 |
rnaveiras/vault | vendor/github.com/ugorji/go/codec/test.py | 181 | 4029 | #!/usr/bin/env python
# This will create golden files in a directory passed to it.
# A Test calls this internally to create the golden files
# So it can process them (so we don't have to checkin the files).
# Ensure msgpack-python and cbor are installed first, using:
# sudo apt-get install python-dev
# sudo apt-get install python-pip
# pip install --user msgpack-python msgpack-rpc-python cbor
# Ensure all "string" keys are utf strings (else encoded as bytes)
import cbor, msgpack, msgpackrpc, sys, os, threading
def get_test_data_list():
# get list with all primitive types, and a combo type
l0 = [
-8,
-1616,
-32323232,
-6464646464646464,
192,
1616,
32323232,
6464646464646464,
192,
-3232.0,
-6464646464.0,
3232.0,
6464.0,
6464646464.0,
False,
True,
u"null",
None,
u"some&day>some<day",
1328176922000002000,
u"",
-2206187877999998000,
u"bytestring",
270,
u"none",
-2013855847999995777,
#-6795364578871345152,
]
l1 = [
{ "true": True,
"false": False },
{ "true": u"True",
"false": False,
"uint16(1616)": 1616 },
{ "list": [1616, 32323232, True, -3232.0, {"TRUE":True, "FALSE":False}, [True, False] ],
"int32":32323232, "bool": True,
"LONG STRING": u"123456789012345678901234567890123456789012345678901234567890",
"SHORT STRING": u"1234567890" },
{ True: "true", 138: False, "false": 200 }
]
l = []
l.extend(l0)
l.append(l0)
l.append(1)
l.extend(l1)
return l
def build_test_data(destdir):
l = get_test_data_list()
for i in range(len(l)):
# packer = msgpack.Packer()
serialized = msgpack.dumps(l[i])
f = open(os.path.join(destdir, str(i) + '.msgpack.golden'), 'wb')
f.write(serialized)
f.close()
serialized = cbor.dumps(l[i])
f = open(os.path.join(destdir, str(i) + '.cbor.golden'), 'wb')
f.write(serialized)
f.close()
def doRpcServer(port, stopTimeSec):
class EchoHandler(object):
def Echo123(self, msg1, msg2, msg3):
return ("1:%s 2:%s 3:%s" % (msg1, msg2, msg3))
def EchoStruct(self, msg):
return ("%s" % msg)
addr = msgpackrpc.Address('127.0.0.1', port)
server = msgpackrpc.Server(EchoHandler())
server.listen(addr)
# run thread to stop it after stopTimeSec seconds if > 0
if stopTimeSec > 0:
def myStopRpcServer():
server.stop()
t = threading.Timer(stopTimeSec, myStopRpcServer)
t.start()
server.start()
def doRpcClientToPythonSvc(port):
address = msgpackrpc.Address('127.0.0.1', port)
client = msgpackrpc.Client(address, unpack_encoding='utf-8')
print client.call("Echo123", "A1", "B2", "C3")
print client.call("EchoStruct", {"A" :"Aa", "B":"Bb", "C":"Cc"})
def doRpcClientToGoSvc(port):
# print ">>>> port: ", port, " <<<<<"
address = msgpackrpc.Address('127.0.0.1', port)
client = msgpackrpc.Client(address, unpack_encoding='utf-8')
print client.call("TestRpcInt.Echo123", ["A1", "B2", "C3"])
print client.call("TestRpcInt.EchoStruct", {"A" :"Aa", "B":"Bb", "C":"Cc"})
def doMain(args):
if len(args) == 2 and args[0] == "testdata":
build_test_data(args[1])
elif len(args) == 3 and args[0] == "rpc-server":
doRpcServer(int(args[1]), int(args[2]))
elif len(args) == 2 and args[0] == "rpc-client-python-service":
doRpcClientToPythonSvc(int(args[1]))
elif len(args) == 2 and args[0] == "rpc-client-go-service":
doRpcClientToGoSvc(int(args[1]))
else:
print("Usage: test.py " +
"[testdata|rpc-server|rpc-client-python-service|rpc-client-go-service] ...")
if __name__ == "__main__":
doMain(sys.argv[1:])
| mpl-2.0 |
alexus37/AugmentedRealityChess | pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/OpenGL/raw/GLES2/OES/get_program_binary.py | 8 | 1053 | '''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GLES2 import _types as _cs
# End users want this...
from OpenGL.raw.GLES2._types import *
from OpenGL.raw.GLES2 import _errors
from OpenGL.constant import Constant as _C
import ctypes
_EXTENSION_NAME = 'GLES2_OES_get_program_binary'
def _f( function ):
return _p.createFunction( function,_p.PLATFORM.GLES2,'GLES2_OES_get_program_binary',error_checker=_errors._error_checker)
GL_NUM_PROGRAM_BINARY_FORMATS_OES=_C('GL_NUM_PROGRAM_BINARY_FORMATS_OES',0x87FE)
GL_PROGRAM_BINARY_FORMATS_OES=_C('GL_PROGRAM_BINARY_FORMATS_OES',0x87FF)
GL_PROGRAM_BINARY_LENGTH_OES=_C('GL_PROGRAM_BINARY_LENGTH_OES',0x8741)
@_f
@_p.types(None,_cs.GLuint,_cs.GLsizei,arrays.GLsizeiArray,arrays.GLuintArray,ctypes.c_void_p)
def glGetProgramBinaryOES(program,bufSize,length,binaryFormat,binary):pass
@_f
@_p.types(None,_cs.GLuint,_cs.GLenum,ctypes.c_void_p,_cs.GLint)
def glProgramBinaryOES(program,binaryFormat,binary,length):pass
| mit |
vishnu-kumar/PeformanceFramework | tests/unit/plugins/openstack/context/network/test_network.py | 8 | 4433 | # Copyright 2014: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import mock
import netaddr
from rally.plugins.openstack.context.network import networks as network_context
from tests.unit import test
NET = "rally.plugins.openstack.wrappers.network."
class NetworkTestCase(test.TestCase):
def get_context(self, **kwargs):
return {"task": {"uuid": "foo_task"},
"admin": {"endpoint": "foo_admin"},
"config": {"network": kwargs},
"users": [{"id": "foo_user", "tenant_id": "foo_tenant"},
{"id": "bar_user", "tenant_id": "bar_tenant"}],
"tenants": {"foo_tenant": {"networks": [{"id": "foo_net"}]},
"bar_tenant": {"networks": [{"id": "bar_net"}]}}}
def test_START_CIDR_DFLT(self):
netaddr.IPNetwork(network_context.Network.DEFAULT_CONFIG["start_cidr"])
@mock.patch("rally.osclients.Clients")
@mock.patch(NET + "wrap", return_value="foo_service")
def test__init__default(self, mock_wrap, mock_clients):
context = network_context.Network(self.get_context())
self.assertEqual(context.config["networks_per_tenant"], 1)
self.assertEqual(context.config["start_cidr"],
network_context.Network.DEFAULT_CONFIG["start_cidr"])
@mock.patch("rally.osclients.Clients")
@mock.patch(NET + "wrap", return_value="foo_service")
def test__init__explicit(self, mock_wrap, mock_clients):
context = network_context.Network(
self.get_context(start_cidr="foo_cidr", networks_per_tenant=42,
network_create_args={"fakearg": "fake"}))
self.assertEqual(context.config["networks_per_tenant"], 42)
self.assertEqual(context.config["start_cidr"], "foo_cidr")
self.assertDictEqual(context.config["network_create_args"],
{"fakearg": "fake"})
@mock.patch(NET + "wrap")
@mock.patch("rally.plugins.openstack.context.network.networks.utils")
@mock.patch("rally.osclients.Clients")
def test_setup(self, mock_clients, mock_utils, mock_wrap):
mock_utils.iterate_per_tenants.return_value = [
("foo_user", "foo_tenant"),
("bar_user", "bar_tenant")]
mock_create = mock.Mock(side_effect=lambda t, **kw: t + "-net")
mock_utils.generate_random_name = mock.Mock()
mock_wrap.return_value = mock.Mock(create_network=mock_create)
nets_per_tenant = 2
net_context = network_context.Network(
self.get_context(networks_per_tenant=nets_per_tenant,
network_create_args={"fakearg": "fake"}))
net_context.setup()
create_calls = [
mock.call(tenant, add_router=True,
subnets_num=1, network_create_args={"fakearg": "fake"})
for user, tenant in mock_utils.iterate_per_tenants.return_value]
mock_create.assert_has_calls(create_calls)
mock_utils.iterate_per_tenants.assert_called_once_with(
net_context.context["users"])
expected_networks = ["bar_tenant-net",
"foo_tenant-net"] * nets_per_tenant
actual_networks = []
for tenant_id, tenant_ctx in net_context.context["tenants"].items():
actual_networks.extend(tenant_ctx["networks"])
self.assertSequenceEqual(sorted(expected_networks),
sorted(actual_networks))
@mock.patch("rally.osclients.Clients")
@mock.patch(NET + "wrap")
def test_cleanup(self, mock_wrap, mock_clients):
net_context = network_context.Network(self.get_context())
net_context.cleanup()
mock_wrap().delete_network.assert_has_calls(
[mock.call({"id": "foo_net"}), mock.call({"id": "bar_net"})],
any_order=True)
| apache-2.0 |
ryanbackman/zulip | zerver/management/commands/export.py | 5 | 5741 | from __future__ import absolute_import
from __future__ import print_function
from typing import Any
from argparse import ArgumentParser, RawTextHelpFormatter
from django.core.management.base import BaseCommand, CommandError
from django.core.exceptions import ValidationError
import os
import shutil
import subprocess
import tempfile
import ujson
from zerver.lib.export import (
do_export_realm, do_write_stats_file_for_realm_export
)
from zerver.models import get_realm
class Command(BaseCommand):
help = """Exports all data from a Zulip realm
This command exports all significant data from a Zulip realm. The
result can be imported using the `./manage.py import` command.
Things that are exported:
* All user-accessible data in the Zulip database (Messages,
Streams, UserMessages, RealmEmoji, etc.)
* Copies of all uploaded files and avatar images along with
metadata needed to restore them even in the ab
Things that are not exported:
* Confirmation, MitUser, and PreregistrationUser (transient tables)
* Sessions (everyone will need to login again post-export)
* Users' passwords and API keys (users will need to use SSO or reset password)
* Mobile tokens for APNS/GCM (users will need to reconnect their mobile devices)
* ScheduledJob (Not relevant on a new server)
* Referral (Unused)
* Deployment (Unused)
* third_party_api_results cache (this means rerending all old
messages could be expensive)
Things that will break as a result of the export:
* Passwords will not be transferred. They will all need to go
through the password reset flow to obtain a new password (unless
they intend to only use e.g. Google Auth).
* Users will need to logout and re-login to the Zulip desktop and
mobile apps. The apps now all have an option on the login page
where you can specify which Zulip server to use; your users
should enter <domain name>.
* All bots will stop working since they will be pointing to the
wrong server URL, and all users' API keys have been rotated as
part of the migration. So to re-enable your integrations, you
will need to direct your integrations at the new server.
Usually this means updating the URL and the bots' API keys. You
can see a list of all the bots that have been configured for
your realm on the `/#organization` page, and use that list to
make sure you migrate them all.
The proper procedure for using this to export a realm is as follows:
* Use `./manage.py deactivate_realm` to deactivate the realm, so
nothing happens in the realm being exported during the export
process.
* Use `./manage.py export` to export the realm, producing a data
tarball.
* Transfer the tarball to the new server and unpack it.
* Use `./manage.py import` to import the realm
* Use `./manage.py reactivate_realm` to reactivate the realm, so
users can login again.
* Inform the users about the things broken above.
We recommend testing by exporting without having deactivated the
realm first, to make sure you have the procedure right and
minimize downtime.
Performance: In one test, the tool exported a realm with hundreds
of users and ~1M messages of history with --threads=1 in about 3
hours of serial runtime (goes down to ~50m with --threads=6 on a
machine with 8 CPUs). Importing that same data set took about 30
minutes. But this will vary a lot depending on the average number
of recipients of messages in the realm, hardware, etc."""
# Fix support for multi-line usage
def create_parser(self, *args, **kwargs):
# type: (*Any, **Any) -> ArgumentParser
parser = super(Command, self).create_parser(*args, **kwargs)
parser.formatter_class = RawTextHelpFormatter
return parser
def add_arguments(self, parser):
# type: (ArgumentParser) -> None
parser.add_argument('realm', metavar='<realm>', type=str,
help="realm to export")
parser.add_argument('--output',
dest='output_dir',
action="store",
default=None,
help='Directory to write exported data to.')
parser.add_argument('--threads',
dest='threads',
action="store",
default=6,
help='Threads to use in exporting UserMessage objects in parallel')
def handle(self, *args, **options):
# type: (*Any, **Any) -> None
try:
realm = get_realm(options["realm"])
except ValidationError:
raise CommandError("No such realm.")
output_dir = options["output_dir"]
if output_dir is None:
output_dir = tempfile.mkdtemp(prefix="/tmp/zulip-export-")
if os.path.exists(output_dir):
shutil.rmtree(output_dir)
os.makedirs(output_dir)
print("Exporting realm %s" % (realm.string_id,))
num_threads = int(options['threads'])
if num_threads < 1:
raise CommandError('You must have at least one thread.')
do_export_realm(realm, output_dir, threads=num_threads)
print("Finished exporting to %s; tarring" % (output_dir,))
do_write_stats_file_for_realm_export(output_dir)
tarball_path = output_dir.rstrip('/') + '.tar.gz'
os.chdir(os.path.dirname(output_dir))
subprocess.check_call(["tar", "-czf", tarball_path, os.path.basename(output_dir)])
print("Tarball written to %s" % (tarball_path,))
| apache-2.0 |
tencentyun/Cloud-Image-Migration-Tool | usr/sbin/oss_job_manager.py | 1 | 4204 | #!/usr/bin/env python
###############################################################################
# Copyright (c) 2015 Tencent Inc.
# Distributed under the MIT license
# (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
#
# Project: Cloud Image Migration Tool
# Filename: oss_job_manager.py
# Version: 2.0
# Author: Jamis Hoo
# E-mail: hoojamis@gmail.com
# Date: Sep 7, 2015
# Time: 14:29:44
###############################################################################
from base_job_manager import BaseJobManager
import os
import urlparse
import oss2
class OssJobManager(BaseJobManager):
"""
Derived class of BaseJobManager.
Traverse a oss account.
Attributes:
mandatory_options: Configuration options required by this class. This is
a list of tuples each of which contains two strings, section name and
property name, both of which are case-insensitive.
"""
mandatory_options = [
("oss", "oss.accesskey"),
("oss", "oss.secretkey"),
("oss", "oss.bucket"),
("oss", "oss.endpoint"),
("oss", "oss.iscname"),
]
def __init__(self, config):
"""
Initialize base class.
"""
super(OssJobManager, self).__init__(config)
@staticmethod
def check_config(config):
"""
Check whether all required options are provided.
Also check the validity of some options.
Args:
config: configuration dict
Returns:
Returns string containing error message if there are some errors.
Returns none otherwise.
"""
for section, option in OssJobManager.mandatory_options:
if section not in config or option not in config[section]:
return "Error: Option %s.%s is required. " % (section, option)
if config["oss"]["oss.iscname"].lower() not in [ "true", "false", "0", "1", "t", "f", "yes", "no", "y", "n" ]:
return "Error: Invalid oss.oss.iscname. "
def do(self):
"""
Implementation of abstract method.
Traverse a Oss account and submit each file.
File id of the job is key of the Oss file.
Src is download URL of the resource.
If resource requires a referer to download, the referer is also included
in src, which is seperated by a tab with download URL.
"""
access_key = self.config["oss"]["oss.accesskey"]
secret_key = self.config["oss"]["oss.secretkey"]
bucket_name = self.config["oss"]["oss.bucket"]
endpoint = self.config["oss"]["oss.endpoint"]
is_cname = self.config["oss"]["oss.iscname"].lower() in [ "true", "1", "t", "yes", "y" ]
if "oss" in self.config and "oss.referer" in self.config["oss"]:
referer = self.config["oss"]["oss.referer"]
else:
referer = None
auth = oss2.Auth(access_key, secret_key)
mybucket = oss2.Bucket(auth, endpoint, bucket_name, is_cname)
def get_list_object(bucket, prefix) :
marker = ''
trytime = 2
while True:
try:
lor=bucket.list_objects(prefix=prefix, marker=marker, max_keys=100)
except Exception as e:
trytime-=1
if trytime <= 0:
raise e
continue
trytime = 2
if lor.object_list:
for object in lor.object_list:
if object.is_prefix():
continue
elif object.key.endswith('/'):
continue
#if object.key.strip('/') != prefix.strip('/'):
# get_list_object(bucket, object.key)
else:
self.submit(object.key, '')
if not lor.is_truncated:
break
else:
marker = lor.next_marker
get_list_object(mybucket, '')
| mit |
TeamBasedLearning/Service | pgtbl/accounts/models.py | 1 | 5059 | from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import (
AbstractBaseUser, PermissionsMixin, BaseUserManager
)
import uuid
class UserProfileManager(BaseUserManager):
"""
Object manager is another class that we can use to help manage the user
profiles that will give us some extra functionality like creating an
administrator user or creating a regular user.
"""
def create_user(self, email, name, password=None):
"""
Creates a new user profile objects.
"""
if not email:
raise ValueError(_("Users must have an email address."))
# This will convert the email to lowercase.
# Email will be standardized in the system.
email = self.normalize_email(email)
# Create a new user in the system.
user = self.model(
email=email,
name=name
)
# Set the encrypt password of user
user.set_password(password)
# Save the created user on database
user.save(using=self._db)
return user
def create_superuser(self, email, name, password):
"""
Create and saves a new superuser with given details.
"""
user = self.create_user(email, name, password)
# Inserts superuser privileges for the user
user.is_superuser = True
user.is_staff = True
# Save the created superuser on database
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
"""
Create the base of django standart user profile and allows us to
add permission to our user model.
"""
email = models.EmailField(
_('E-mail'),
help_text=_("Email that will be used as username."),
unique=True
)
name = models.CharField(
_('Name'),
help_text=_("Full user name."),
max_length=150
)
institution = models.CharField(
_('Institution'),
help_text=_("University or School in which the user is inserted."),
max_length=100,
blank=True
)
course = models.CharField(
_('Course'),
help_text=_("Course of university or Period of school."),
max_length=100,
blank=True
)
photo = models.ImageField(
upload_to='accounts',
help_text=_("Photo of user."),
verbose_name=_('Photo'),
blank=True,
null=True
)
is_teacher = models.BooleanField(
_('Is Teacher?'),
help_text=_("Verify if the user is teacher or student"),
default=False
)
# Use to determine if this user is currently active in the system
# You can use it to disable user accounts
is_active = models.BooleanField(
_('Is Active?'),
help_text=_("Verify if the user is active."),
default=True
)
# Transform the user to staff members that can manage de users
is_staff = models.BooleanField(
_('Is Staff?'),
help_text=_("Verify if the user is a staff."),
default=False
)
last_login = models.DateTimeField(
_('Last Login'),
help_text=_("Last moment the user logged in."),
blank=True,
null=True
)
created_at = models.DateTimeField(
_('Created at'),
help_text=_("Date that the user is created."),
auto_now_add=True
)
updated_at = models.DateTimeField(
_('Updated at'),
help_text=_("Date that the user is updated."),
auto_now=True
)
# Attribute used to logout the user
jwt_secret = models.UUIDField(default=uuid.uuid4)
# Help manager the user profile
objects = UserProfileManager()
# Is the field that going to be used as the username for this user
USERNAME_FIELD = 'email'
# Is a list of fields that are required for all users, the username don't
# need to be passed.
REQUIRED_FIELDS = ['name']
def __str__(self):
"""
Returns the object as a string, the attribute that will represent
the object.
"""
return self.email
def get_full_name(self):
"""
Used to get the user full name.
"""
return self.name
def get_short_name(self):
"""
Used to get the user short name.
"""
LAST_NAME = -1
FIRST_NAME = 0
if len(self.name.split(" ")) >= 2:
return str(
self.name.split(" ")[FIRST_NAME] +
" " +
self.name.split(" ")[LAST_NAME]
)
else:
return str(self.name)
class Meta:
"""
Some information about user class.
"""
verbose_name = _("User")
verbose_name_plural = _("Users")
ordering = ('email',)
def jwt_get_secret_key(user_model):
"""
Helper function allowing the REST Framework JWT library to access this secret_key field
"""
return user_model.jwt_secret | gpl-3.0 |
linvictor88/vse-lbaas-driver | quantum/tests/unit/nec/test_trema_driver.py | 3 | 13624 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 NEC Corporation. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
# @author: Ryota MIBU
import mox
from quantum import context
from quantum.openstack.common import uuidutils
from quantum.plugins.nec.common import ofc_client
from quantum.plugins.nec.db import api as ndb
from quantum.plugins.nec.db import models as nmodels
from quantum.plugins.nec import drivers
from quantum.tests import base
class TestConfig(object):
"""Configuration for this test."""
host = '127.0.0.1'
port = 8888
class TremaDriverTestBase(base.BaseTestCase):
driver_name = "trema"
def setUp(self):
super(TremaDriverTestBase, self).setUp()
self.mox = mox.Mox()
self.driver = drivers.get_driver(self.driver_name)(TestConfig)
self.mox.StubOutWithMock(ofc_client.OFCClient, 'do_request')
self.addCleanup(self.mox.UnsetStubs)
def get_ofc_item_random_params(self):
"""create random parameters for ofc_item test."""
tenant_id = uuidutils.generate_uuid()
network_id = uuidutils.generate_uuid()
port_id = uuidutils.generate_uuid()
portinfo = nmodels.PortInfo(id=port_id, datapath_id="0x123456789",
port_no=1234, vlan_id=321,
mac="11:22:33:44:55:66")
return tenant_id, network_id, portinfo
class TremaDriverNetworkTestBase(TremaDriverTestBase):
def testa_create_network(self):
t, n, p = self.get_ofc_item_random_params()
description = "desc of %s" % n
body = {'id': n, 'description': description}
ofc_client.OFCClient.do_request("POST", "/networks", body=body)
self.mox.ReplayAll()
ret = self.driver.create_network(t, description, n)
self.mox.VerifyAll()
self.assertEqual(ret, '/networks/%s' % n)
def testc_delete_network(self):
t, n, p = self.get_ofc_item_random_params()
net_path = "/networks/%s" % n
ofc_client.OFCClient.do_request("DELETE", net_path)
self.mox.ReplayAll()
self.driver.delete_network(net_path)
self.mox.VerifyAll()
class TremaPortBaseDriverTest(TremaDriverNetworkTestBase):
driver_name = "trema_port"
def testd_create_port(self):
_t, n, p = self.get_ofc_item_random_params()
net_path = "/networks/%s" % n
body = {'id': p.id,
'datapath_id': p.datapath_id,
'port': str(p.port_no),
'vid': str(p.vlan_id)}
ofc_client.OFCClient.do_request("POST",
"/networks/%s/ports" % n, body=body)
self.mox.ReplayAll()
ret = self.driver.create_port(net_path, p, p.id)
self.mox.VerifyAll()
self.assertEqual(ret, '/networks/%s/ports/%s' % (n, p.id))
def testd_delete_port(self):
t, n, p = self.get_ofc_item_random_params()
p_path = "/networks/%s/ports/%s" % (n, p.id)
ofc_client.OFCClient.do_request("DELETE", p_path)
self.mox.ReplayAll()
self.driver.delete_port(p_path)
self.mox.VerifyAll()
class TremaPortMACBaseDriverTest(TremaDriverNetworkTestBase):
driver_name = "trema_portmac"
def testd_create_port(self):
t, n, p = self.get_ofc_item_random_params()
dummy_port = "dummy-%s" % p.id
net_path = "/networks/%s" % n
path_1 = "/networks/%s/ports" % n
body_1 = {'id': dummy_port,
'datapath_id': p.datapath_id,
'port': str(p.port_no),
'vid': str(p.vlan_id)}
ofc_client.OFCClient.do_request("POST", path_1, body=body_1)
path_2 = "/networks/%s/ports/%s/attachments" % (n, dummy_port)
body_2 = {'id': p.id, 'mac': p.mac}
ofc_client.OFCClient.do_request("POST", path_2, body=body_2)
path_3 = "/networks/%s/ports/%s" % (n, dummy_port)
ofc_client.OFCClient.do_request("DELETE", path_3)
self.mox.ReplayAll()
ret = self.driver.create_port(net_path, p, p.id)
self.mox.VerifyAll()
port_path = "/networks/%s/ports/%s/attachments/%s" % (n, dummy_port,
p.id)
self.assertEqual(ret, port_path)
def testd_delete_port(self):
t, n, p = self.get_ofc_item_random_params()
dummy_port = "dummy-%s" % p.id
path = "/networks/%s/ports/%s/attachments/%s" % (n, dummy_port, p.id)
ofc_client.OFCClient.do_request("DELETE", path)
self.mox.ReplayAll()
self.driver.delete_port(path)
self.mox.VerifyAll()
class TremaMACBaseDriverTest(TremaDriverNetworkTestBase):
driver_name = "trema_mac"
def testd_create_port(self):
t, n, p = self.get_ofc_item_random_params()
net_path = "/networks/%s" % n
path = "/networks/%s/attachments" % n
body = {'id': p.id, 'mac': p.mac}
ofc_client.OFCClient.do_request("POST", path, body=body)
self.mox.ReplayAll()
ret = self.driver.create_port(net_path, p, p.id)
self.mox.VerifyAll()
self.assertEqual(ret, '/networks/%s/attachments/%s' % (n, p.id))
def testd_delete_port(self):
t, n, p = self.get_ofc_item_random_params()
path = "/networks/%s/attachments/%s" % (n, p.id)
ofc_client.OFCClient.do_request("DELETE", path)
self.mox.ReplayAll()
self.driver.delete_port(path)
self.mox.VerifyAll()
class TremaFilterDriverTest(TremaDriverTestBase):
def get_ofc_item_random_params(self):
"""create random parameters for ofc_item test."""
t, n, p = (super(TremaFilterDriverTest, self).
get_ofc_item_random_params())
filter_id = uuidutils.generate_uuid()
filter_dict = {'tenant_id': t,
'id': filter_id,
'network_id': n,
'priority': 123,
'action': "ACCEPT",
'in_port': p.id,
'src_mac': p.mac,
'dst_mac': "",
'eth_type': 0,
'src_cidr': "",
'dst_cidr': "",
'src_port': 0,
'dst_port': 0,
'protocol': "TCP",
'admin_state_up': True,
'status': "ACTIVE"}
filter_item = nmodels.PacketFilter(**filter_dict)
return t, n, p, filter_item
def testa_create_filter(self):
t, n, p, f = self.get_ofc_item_random_params()
net_path = "/networks/%s" % n
ofp_wildcards = 'dl_vlan,dl_vlan_pcp,nw_tos,dl_dst,' + \
'nw_src:32,nw_dst:32,tp_src,tp_dst'
body = {'id': f.id,
'action': 'ALLOW',
'priority': 123,
'slice': n,
'in_datapath_id': '0x123456789',
'in_port': 1234,
'nw_proto': '0x6',
'dl_type': '0x800',
'dl_src': p.mac,
'ofp_wildcards': ofp_wildcards}
ofc_client.OFCClient.do_request("POST", "/filters", body=body)
self.mox.ReplayAll()
ret = self.driver.create_filter(net_path, f, p, f.id)
self.mox.VerifyAll()
self.assertEqual(ret, '/filters/%s' % f.id)
def testb_delete_filter(self):
t, n, p, f = self.get_ofc_item_random_params()
f_path = "/filters/%s" % f.id
ofc_client.OFCClient.do_request("DELETE", f_path)
self.mox.ReplayAll()
self.driver.delete_filter(f_path)
self.mox.VerifyAll()
def generate_random_ids(count=1):
if count == 1:
return uuidutils.generate_uuid()
else:
return [uuidutils.generate_uuid() for i in xrange(count)]
class TremaIdConvertTest(base.BaseTestCase):
driver_name = 'trema'
def setUp(self):
super(TremaIdConvertTest, self).setUp()
self.driver = drivers.get_driver(self.driver_name)(TestConfig)
self.mox = mox.Mox()
self.ctx = self.mox.CreateMock(context.Context)
self.addCleanup(self.mox.UnsetStubs)
def test_convert_tenant_id(self):
ofc_t_id = generate_random_ids(1)
ret = self.driver.convert_ofc_tenant_id(self.ctx, ofc_t_id)
self.assertEqual(ret, '/tenants/%s' % ofc_t_id)
def test_convert_tenant_id_noconv(self):
ofc_t_id = '/tenants/%s' % generate_random_ids(1)
ret = self.driver.convert_ofc_tenant_id(self.ctx, ofc_t_id)
self.assertEqual(ret, ofc_t_id)
def test_convert_network_id(self):
t_id, ofc_t_id, ofc_n_id = generate_random_ids(3)
ret = self.driver.convert_ofc_network_id(self.ctx, ofc_n_id, t_id)
self.assertEqual(ret, ('/networks/%s' % ofc_n_id))
def test_convert_network_id_noconv(self):
t_id = 'dummy'
ofc_t_id, ofc_n_id = generate_random_ids(2)
ofc_n_id = '/networks/%s' % ofc_n_id
self.driver.convert_ofc_network_id(self.ctx, ofc_n_id, t_id)
def test_convert_filter_id(self):
ofc_f_id = generate_random_ids(1)
ret = self.driver.convert_ofc_filter_id(self.ctx, ofc_f_id)
self.assertEqual(ret, '/filters/%s' % ofc_f_id)
def test_convert_filter_id_noconv(self):
ofc_f_id = '/filters/%s' % generate_random_ids(1)
ret = self.driver.convert_ofc_filter_id(self.ctx, ofc_f_id)
self.assertEqual(ret, ofc_f_id)
class TremaIdConvertTestBase(base.BaseTestCase):
def setUp(self):
super(TremaIdConvertTestBase, self).setUp()
self.mox = mox.Mox()
self.driver = drivers.get_driver(self.driver_name)(TestConfig)
self.ctx = self.mox.CreateMock(context.Context)
self.ctx.session = "session"
self.mox.StubOutWithMock(ndb, 'get_ofc_id_lookup_both')
self.addCleanup(self.mox.UnsetStubs)
def _test_convert_port_id(self, port_path_template):
t_id, n_id = generate_random_ids(2)
ofc_n_id, ofc_p_id = generate_random_ids(2)
ndb.get_ofc_id_lookup_both(
self.ctx.session, 'ofc_network', n_id).AndReturn(ofc_n_id)
self.mox.ReplayAll()
ret = self.driver.convert_ofc_port_id(self.ctx, ofc_p_id, t_id, n_id)
exp = port_path_template % {'network': ofc_n_id, 'port': ofc_p_id}
self.assertEqual(ret, exp)
self.mox.VerifyAll()
def _test_convert_port_id_with_new_network_id(self, port_path_template):
t_id, n_id = generate_random_ids(2)
ofc_n_id, ofc_p_id = generate_random_ids(2)
ofc_n_path = '/networks/%s' % ofc_n_id
ndb.get_ofc_id_lookup_both(
self.ctx.session, 'ofc_network', n_id).AndReturn(ofc_n_path)
self.mox.ReplayAll()
ret = self.driver.convert_ofc_port_id(self.ctx, ofc_p_id, t_id, n_id)
exp = port_path_template % {'network': ofc_n_id, 'port': ofc_p_id}
print 'exp=', exp
print 'ret=', ret
self.assertEqual(ret, exp)
self.mox.VerifyAll()
def _test_convert_port_id_noconv(self, port_path_template):
t_id = n_id = 'dummy'
ofc_n_id, ofc_p_id = generate_random_ids(2)
ofc_p_id = port_path_template % {'network': ofc_n_id, 'port': ofc_p_id}
ret = self.driver.convert_ofc_port_id(self.ctx, ofc_p_id, t_id, n_id)
self.assertEqual(ret, ofc_p_id)
class TremaIdConvertPortBaseTest(TremaIdConvertTestBase):
driver_name = "trema_port"
def test_convert_port_id(self):
self._test_convert_port_id('/networks/%(network)s/ports/%(port)s')
def test_convert_port_id_with_new_network_id(self):
self._test_convert_port_id_with_new_network_id(
'/networks/%(network)s/ports/%(port)s')
def test_convert_port_id_noconv(self):
self._test_convert_port_id_noconv(
'/networs/%(network)s/ports/%(port)s')
class TremaIdConvertPortMACBaseTest(TremaIdConvertTestBase):
driver_name = "trema_portmac"
def test_convert_port_id(self):
self._test_convert_port_id(
'/networks/%(network)s/ports/dummy-%(port)s/attachments/%(port)s')
def test_convert_port_id_with_new_network_id(self):
self._test_convert_port_id_with_new_network_id(
'/networks/%(network)s/ports/dummy-%(port)s/attachments/%(port)s')
def test_convert_port_id_noconv(self):
self._test_convert_port_id_noconv(
'/networs/%(network)s/ports/dummy-%(port)s/attachments/%(port)s')
class TremaIdConvertMACBaseTest(TremaIdConvertTestBase):
driver_name = "trema_mac"
def test_convert_port_id(self):
self._test_convert_port_id(
'/networks/%(network)s/attachments/%(port)s')
def test_convert_port_id_with_new_network_id(self):
self._test_convert_port_id_with_new_network_id(
'/networks/%(network)s/attachments/%(port)s')
def test_convert_port_id_noconv(self):
self._test_convert_port_id_noconv(
'/networs/%(network)s/attachments/%(port)s')
| apache-2.0 |
LiuLang/bcloud | bcloud/Downloader.py | 10 | 11869 |
# Copyright (C) 2014-2015 LiuLang <gsushzhsosgsu@gmail.com>
# Use of this source code is governed by GPLv3 license that can be found
# in http://www.gnu.org/licenses/gpl-3.0.html
import json
import multiprocessing
import os
from queue import Queue
import re
import threading
import time
import traceback
from urllib import request
from gi.repository import GLib
from gi.repository import GObject
from bcloud import const
from bcloud.const import State, DownloadMode
from bcloud import net
from bcloud import pcs
from bcloud import util
from bcloud.log import logger
CHUNK_SIZE = 131072 # 128K
RETRIES = 3 # 连接失败时的重试次数
DOWNLOAD_RETRIES = 10 # 下载线程的重试次数
THRESHOLD_TO_FLUSH = 500 # 磁盘写入数据次数超过这个值时, 就进行一次同步.
SMALL_FILE_SIZE = 1048576 # 1M, 下载小文件时用单线程下载
(NAME_COL, PATH_COL, FSID_COL, SIZE_COL, CURRSIZE_COL, LINK_COL,
ISDIR_COL, SAVENAME_COL, SAVEDIR_COL, STATE_COL, STATENAME_COL,
HUMANSIZE_COL, PERCENT_COL) = list(range(13))
BATCH_FINISISHED, BATCH_ERROR = -1, -2
def get_tmp_filepath(dir_name, save_name):
'''返回最终路径名及临时路径名'''
filepath = os.path.join(dir_name, save_name)
return filepath, filepath + '.part', filepath + '.bcloud-stat'
class DownloadBatch(threading.Thread):
def __init__(self, id_, queue, url, lock, start_size, end_size, fh,
timeout):
super().__init__()
self.id_ = id_
self.queue = queue
self.url = url
self.lock = lock
self.start_size = start_size
self.end_size = end_size
self.fh = fh
self.timeout = timeout
self.stop_flag = False
def run(self):
self.download()
def stop(self):
self.stop_flag = True
def get_req(self, start_size, end_size):
'''打开socket'''
logger.debug('DownloadBatch.get_req: %s, %s' % (start_size, end_size))
opener = request.build_opener()
content_range = 'bytes={0}-{1}'.format(start_size, end_size)
opener.addheaders = [
('Range', content_range),
('User-Agent', const.USER_AGENT),
('Referer', const.PAN_REFERER),
]
for i in range(RETRIES):
try:
return opener.open(self.url, timeout=self.timeout)
except OSError:
logger.error(traceback.format_exc())
self.queue.put((self.id_, BATCH_ERROR), block=False)
return None
except:
self.queue.put((self.id_, BATCH_ERROR), block=False)
return None
else:
return None
def download(self):
offset = self.start_size
req = self.get_req(offset, self.end_size)
if not req:
self.queue.put((self.id_, BATCH_ERROR), block=False)
return
while not self.stop_flag:
for i in range(DOWNLOAD_RETRIES):
if not req:
req = self.get_req(offset, self.end_size)
logger.debug('DownloadBatch.download: socket reconnected')
try:
block = req.read(CHUNK_SIZE)
if block:
break
except (OSError, AttributeError):
#self.queue.put((self.id_, BATCH_ERROR), block=False)
logger.error(traceback.format_exc())
req = None
except :
req=None
logger.error( 'Time out occured.')
#self.queue.put((self.id_, BATCH_ERROR), block=False)
#return
else:
logger.error('DownloadBatch, block is empty: %s, %s, %s, %s' %
(offset, self.start_size, self.end_size,
len(block)))
self.queue.put((self.id_, BATCH_ERROR), block=False)
return
with self.lock:
if self.fh.closed:
return
self.fh.seek(offset)
self.fh.write(block)
self.queue.put((self.id_, len(block)), block=False)
offset = offset + len(block)
# 下载完成
if offset >= self.end_size:
self.queue.put((self.id_, BATCH_FINISISHED), block=False)
return
class Downloader(threading.Thread, GObject.GObject):
'''管理每个下载任务, 使用了多线程下载.
当程序退出时, 下载线程会保留现场, 以后可以继续下载.
断点续传功能基于HTTP/1.1 的Range, 百度网盘对它有很好的支持.
'''
__gsignals__ = {
'started': (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (str, )),
'received': (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE,
(str, GObject.TYPE_INT64, GObject.TYPE_INT64)),
'downloaded': (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (str, )),
# FSID, tmp-filepath
'disk-error': (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (str, str)),
'network-error': (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (str, )),
}
def __init__(self, parent, row):
threading.Thread.__init__(self)
self.daemon = True
GObject.GObject.__init__(self)
self.cookie = parent.app.cookie
self.tokens = parent.app.tokens
self.default_threads = int(parent.app.profile['download-segments'])
self.timeout = int(parent.app.profile['download-timeout'])
self.download_mode = parent.app.profile['download-mode']
self.row = row[:]
def download(self):
row = self.row
if not os.path.exists(row[SAVEDIR_COL]):
os.makedirs(row[SAVEDIR_COL], exist_ok=True)
filepath, tmp_filepath, conf_filepath = get_tmp_filepath(
row[SAVEDIR_COL], row[SAVENAME_COL])
if os.path.exists(filepath):
if self.download_mode == DownloadMode.IGNORE:
self.emit('downloaded', row[FSID_COL])
logger.debug('File exists, ignored!')
return
elif self.download_mode == DownloadMode.NEWCOPY:
name, ext = os.path.splitext(filepath)
filepath = '{0}_{1}{2}'.format(name, util.curr_time(), ext)
url = pcs.get_download_link(self.cookie, self.tokens, row[PATH_COL])
if not url:
row[STATE_COL] = State.ERROR
self.emit('network-error', row[FSID_COL])
logger.warn('Failed to get url to download')
return
if os.path.exists(conf_filepath) and os.path.exists(tmp_filepath):
with open(conf_filepath) as conf_fh:
status = json.load(conf_fh)
threads = len(status)
file_exists = True
fh = open(tmp_filepath, 'rb+')
fh.seek(0)
else:
req = net.urlopen_simple(url)
if not req:
logger.warn('Failed to get url to download')
self.emit('network-error', row[FSID_COL])
return
content_length = req.getheader('Content-Length')
# Fixed: baiduPCS using non iso-8859-1 codec in http headers
if not content_length:
match = re.search('\sContent-Length:\s*(\d+)', str(req.headers))
if not match:
logger.warn('Failed to get url to download')
self.emit('network-error', row[FSID_COL])
return
content_length = match.group(1)
size = int(content_length)
if size == 0:
open(filepath, 'a').close()
self.emit('downloaded', row[FSID_COL])
return
elif size <= SMALL_FILE_SIZE:
threads = 1
else:
threads = self.default_threads
average_size, pad_size = divmod(size, threads)
file_exists = False
status = []
fh = open(tmp_filepath, 'wb')
try:
fh.truncate(size)
except (OSError, IOError):
e = truncate.format_exc()
logger.error(e)
self.emit('disk-error', row[FSID_COL], tmp_filepath)
return
# task list
tasks = []
# message queue
queue = Queue()
# threads lock
lock = threading.RLock()
for id_ in range(threads):
if file_exists:
start_size, end_size, received = status[id_]
if start_size + received >= end_size:
# part of file has been downloaded
continue
start_size += received
else:
start_size = id_ * average_size
end_size = start_size + average_size - 1
if id_ == threads - 1:
end_size = end_size + pad_size + 1
status.append([start_size, end_size, 0])
task = DownloadBatch(id_, queue, url, lock, start_size, end_size,
fh, self.timeout)
tasks.append(task)
for task in tasks:
task.start()
try:
conf_count = 0
done = 0
self.emit('started', row[FSID_COL])
while row[STATE_COL] == State.DOWNLOADING:
id_, received = queue.get()
# FINISHED
if received == BATCH_FINISISHED:
done += 1
if done == len(tasks):
row[STATE_COL] = State.FINISHED
break
else:
continue
# error occurs
elif received == BATCH_ERROR:
row[STATE_COL] = State.ERROR
break
status[id_][2] += received
conf_count += 1
# flush data and status to disk
if conf_count > THRESHOLD_TO_FLUSH:
with lock:
if not fh.closed:
fh.flush()
with open(conf_filepath, 'w') as fh:
json.dump(status, fh)
conf_count = 0
received_total = sum(t[2] for t in status)
self.emit('received', row[FSID_COL], received, received_total)
except Exception:
logger.error(traceback.format_exc())
row[STATE_COL] = State.ERROR
with lock:
if not fh.closed:
fh.close()
for task in tasks:
if task.isAlive():
task.stop()
with open(conf_filepath, 'w') as fh:
json.dump(status, fh)
if row[STATE_COL] == State.CANCELED:
os.remove(tmp_filepath)
if os.path.exists(conf_filepath):
os.remove(conf_filepath)
elif row[STATE_COL] == State.ERROR:
self.emit('network-error', row[FSID_COL])
elif row[STATE_COL] == State.FINISHED:
self.emit('downloaded', row[FSID_COL])
os.rename(tmp_filepath, filepath)
if os.path.exists(conf_filepath):
os.remove(conf_filepath)
def destroy(self):
'''自毁'''
self.pause()
def run(self):
'''实现了Thread的方法, 线程启动入口'''
self.download()
def pause(self):
'''暂停下载任务'''
self.row[STATE_COL] = State.PAUSED
def stop(self):
'''停止下载, 并删除之前下载的片段'''
self.row[STATE_COL] = State.CANCELED
GObject.type_register(Downloader)
| gpl-3.0 |
appliedx/edx-platform | lms/djangoapps/instructor_task/tasks.py | 28 | 12671 | """
This file contains tasks that are designed to perform background operations on the
running state of a course.
At present, these tasks all operate on StudentModule objects in one way or another,
so they share a visitor architecture. Each task defines an "update function" that
takes a module_descriptor, a particular StudentModule object, and xmodule_instance_args.
A task may optionally specify a "filter function" that takes a query for StudentModule
objects, and adds additional filter clauses.
A task also passes through "xmodule_instance_args", that are used to provide
information to our code that instantiates xmodule instances.
The task definition then calls the traversal function, passing in the three arguments
above, along with the id value for an InstructorTask object. The InstructorTask
object contains a 'task_input' row which is a JSON-encoded dict containing
a problem URL and optionally a student. These are used to set up the initial value
of the query for traversing StudentModule objects.
"""
import logging
from functools import partial
from django.conf import settings
from django.utils.translation import ugettext_noop
from celery import task
from bulk_email.tasks import perform_delegate_email_batches
from instructor_task.tasks_helper import (
run_main_task,
BaseInstructorTask,
perform_module_state_update,
rescore_problem_module_state,
reset_attempts_module_state,
delete_problem_module_state,
upload_problem_responses_csv,
upload_grades_csv,
upload_problem_grade_report,
upload_students_csv,
cohort_students_and_upload,
upload_enrollment_report,
upload_may_enroll_csv,
upload_exec_summary_report,
generate_students_certificates,
upload_proctored_exam_results_report
)
TASK_LOG = logging.getLogger('edx.celery.task')
@task(base=BaseInstructorTask) # pylint: disable=not-callable
def rescore_problem(entry_id, xmodule_instance_args):
"""Rescores a problem in a course, for all students or one specific student.
`entry_id` is the id value of the InstructorTask entry that corresponds to this task.
The entry contains the `course_id` that identifies the course, as well as the
`task_input`, which contains task-specific input.
The task_input should be a dict with the following entries:
'problem_url': the full URL to the problem to be rescored. (required)
'student': the identifier (username or email) of a particular user whose
problem submission should be rescored. If not specified, all problem
submissions for the problem will be rescored.
`xmodule_instance_args` provides information needed by _get_module_instance_for_task()
to instantiate an xmodule instance.
"""
# Translators: This is a past-tense verb that is inserted into task progress messages as {action}.
action_name = ugettext_noop('rescored')
update_fcn = partial(rescore_problem_module_state, xmodule_instance_args)
def filter_fcn(modules_to_update):
"""Filter that matches problems which are marked as being done"""
return modules_to_update.filter(state__contains='"done": true')
visit_fcn = partial(perform_module_state_update, update_fcn, filter_fcn)
return run_main_task(entry_id, visit_fcn, action_name)
@task(base=BaseInstructorTask) # pylint: disable=not-callable
def reset_problem_attempts(entry_id, xmodule_instance_args):
"""Resets problem attempts to zero for a particular problem for all students in a course.
`entry_id` is the id value of the InstructorTask entry that corresponds to this task.
The entry contains the `course_id` that identifies the course, as well as the
`task_input`, which contains task-specific input.
The task_input should be a dict with the following entries:
'problem_url': the full URL to the problem to be rescored. (required)
`xmodule_instance_args` provides information needed by _get_module_instance_for_task()
to instantiate an xmodule instance.
"""
# Translators: This is a past-tense verb that is inserted into task progress messages as {action}.
action_name = ugettext_noop('reset')
update_fcn = partial(reset_attempts_module_state, xmodule_instance_args)
visit_fcn = partial(perform_module_state_update, update_fcn, None)
return run_main_task(entry_id, visit_fcn, action_name)
@task(base=BaseInstructorTask) # pylint: disable=not-callable
def delete_problem_state(entry_id, xmodule_instance_args):
"""Deletes problem state entirely for all students on a particular problem in a course.
`entry_id` is the id value of the InstructorTask entry that corresponds to this task.
The entry contains the `course_id` that identifies the course, as well as the
`task_input`, which contains task-specific input.
The task_input should be a dict with the following entries:
'problem_url': the full URL to the problem to be rescored. (required)
`xmodule_instance_args` provides information needed by _get_module_instance_for_task()
to instantiate an xmodule instance.
"""
# Translators: This is a past-tense verb that is inserted into task progress messages as {action}.
action_name = ugettext_noop('deleted')
update_fcn = partial(delete_problem_module_state, xmodule_instance_args)
visit_fcn = partial(perform_module_state_update, update_fcn, None)
return run_main_task(entry_id, visit_fcn, action_name)
@task(base=BaseInstructorTask) # pylint: disable=not-callable
def send_bulk_course_email(entry_id, _xmodule_instance_args):
"""Sends emails to recipients enrolled in a course.
`entry_id` is the id value of the InstructorTask entry that corresponds to this task.
The entry contains the `course_id` that identifies the course, as well as the
`task_input`, which contains task-specific input.
The task_input should be a dict with the following entries:
'email_id': the full URL to the problem to be rescored. (required)
`_xmodule_instance_args` provides information needed by _get_module_instance_for_task()
to instantiate an xmodule instance. This is unused here.
"""
# Translators: This is a past-tense verb that is inserted into task progress messages as {action}.
action_name = ugettext_noop('emailed')
visit_fcn = perform_delegate_email_batches
return run_main_task(entry_id, visit_fcn, action_name)
@task(base=BaseInstructorTask, routing_key=settings.GRADES_DOWNLOAD_ROUTING_KEY) # pylint: disable=not-callable
def calculate_problem_responses_csv(entry_id, xmodule_instance_args):
"""
Compute student answers to a given problem and upload the CSV to
an S3 bucket for download.
"""
# Translators: This is a past-tense verb that is inserted into task progress messages as {action}.
action_name = ugettext_noop('generated')
task_fn = partial(upload_problem_responses_csv, xmodule_instance_args)
return run_main_task(entry_id, task_fn, action_name)
@task(base=BaseInstructorTask, routing_key=settings.GRADES_DOWNLOAD_ROUTING_KEY) # pylint: disable=not-callable
def calculate_grades_csv(entry_id, xmodule_instance_args):
"""
Grade a course and push the results to an S3 bucket for download.
"""
# Translators: This is a past-tense verb that is inserted into task progress messages as {action}.
action_name = ugettext_noop('graded')
TASK_LOG.info(
u"Task: %s, InstructorTask ID: %s, Task type: %s, Preparing for task execution",
xmodule_instance_args.get('task_id'), entry_id, action_name
)
task_fn = partial(upload_grades_csv, xmodule_instance_args)
return run_main_task(entry_id, task_fn, action_name)
@task(base=BaseInstructorTask, routing_key=settings.GRADES_DOWNLOAD_ROUTING_KEY) # pylint: disable=not-callable
def calculate_problem_grade_report(entry_id, xmodule_instance_args):
"""
Generate a CSV for a course containing all students' problem
grades and push the results to an S3 bucket for download.
"""
# Translators: This is a past-tense phrase that is inserted into task progress messages as {action}.
action_name = ugettext_noop('problem distribution graded')
TASK_LOG.info(
u"Task: %s, InstructorTask ID: %s, Task type: %s, Preparing for task execution",
xmodule_instance_args.get('task_id'), entry_id, action_name
)
task_fn = partial(upload_problem_grade_report, xmodule_instance_args)
return run_main_task(entry_id, task_fn, action_name)
@task(base=BaseInstructorTask, routing_key=settings.GRADES_DOWNLOAD_ROUTING_KEY) # pylint: disable=not-callable
def calculate_students_features_csv(entry_id, xmodule_instance_args):
"""
Compute student profile information for a course and upload the
CSV to an S3 bucket for download.
"""
# Translators: This is a past-tense verb that is inserted into task progress messages as {action}.
action_name = ugettext_noop('generated')
task_fn = partial(upload_students_csv, xmodule_instance_args)
return run_main_task(entry_id, task_fn, action_name)
@task(base=BaseInstructorTask, routing_key=settings.GRADES_DOWNLOAD_ROUTING_KEY) # pylint: disable=not-callable
def enrollment_report_features_csv(entry_id, xmodule_instance_args):
"""
Compute student profile information for a course and upload the
CSV to an S3 bucket for download.
"""
# Translators: This is a past-tense verb that is inserted into task progress messages as {action}.
action_name = ugettext_noop('generating_enrollment_report')
task_fn = partial(upload_enrollment_report, xmodule_instance_args)
return run_main_task(entry_id, task_fn, action_name)
@task(base=BaseInstructorTask, routing_key=settings.GRADES_DOWNLOAD_ROUTING_KEY) # pylint: disable=not-callable
def exec_summary_report_csv(entry_id, xmodule_instance_args):
"""
Compute executive summary report for a course and upload the
Html generated report to an S3 bucket for download.
"""
# Translators: This is a past-tense verb that is inserted into task progress messages as {action}.
action_name = 'generating_exec_summary_report'
task_fn = partial(upload_exec_summary_report, xmodule_instance_args)
return run_main_task(entry_id, task_fn, action_name)
@task(base=BaseInstructorTask, routing_key=settings.GRADES_DOWNLOAD_ROUTING_KEY) # pylint: disable=not-callable
def proctored_exam_results_csv(entry_id, xmodule_instance_args):
"""
Compute proctored exam results report for a course and upload the
CSV for download.
"""
action_name = 'generating_proctored_exam_results_report'
task_fn = partial(upload_proctored_exam_results_report, xmodule_instance_args)
return run_main_task(entry_id, task_fn, action_name)
@task(base=BaseInstructorTask, routing_key=settings.GRADES_DOWNLOAD_ROUTING_KEY) # pylint: disable=not-callable
def calculate_may_enroll_csv(entry_id, xmodule_instance_args):
"""
Compute information about invited students who have not enrolled
in a given course yet and upload the CSV to an S3 bucket for
download.
"""
# Translators: This is a past-tense verb that is inserted into task progress messages as {action}.
action_name = ugettext_noop('generated')
task_fn = partial(upload_may_enroll_csv, xmodule_instance_args)
return run_main_task(entry_id, task_fn, action_name)
@task(base=BaseInstructorTask, routing_key=settings.GRADES_DOWNLOAD_ROUTING_KEY) # pylint: disable=not-callable
def generate_certificates(entry_id, xmodule_instance_args):
"""
Grade students and generate certificates.
"""
# Translators: This is a past-tense verb that is inserted into task progress messages as {action}.
action_name = ugettext_noop('certificates generated')
TASK_LOG.info(
u"Task: %s, InstructorTask ID: %s, Task type: %s, Preparing for task execution",
xmodule_instance_args.get('task_id'), entry_id, action_name
)
task_fn = partial(generate_students_certificates, xmodule_instance_args)
return run_main_task(entry_id, task_fn, action_name)
@task(base=BaseInstructorTask) # pylint: disable=E1102
def cohort_students(entry_id, xmodule_instance_args):
"""
Cohort students in bulk, and upload the results.
"""
# Translators: This is a past-tense verb that is inserted into task progress messages as {action}.
# An example of such a message is: "Progress: {action} {succeeded} of {attempted} so far"
action_name = ugettext_noop('cohorted')
task_fn = partial(cohort_students_and_upload, xmodule_instance_args)
return run_main_task(entry_id, task_fn, action_name)
| agpl-3.0 |
liuyonggg/learning_python | leetcode/expressionAddOperator.py | 1 | 2979 | '''
Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value.
Examples:
"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []
'''
def getOp(ops, num):
ops2 = map(tuple, (ops,)) * num
res = [[]]
for op in ops2:
res = [x+[y] for x in res for y in op]
for op in res:
yield tuple(op)
class OpIterator():
'''
iterate all operator combinations
'''
def __init__(self, ops, num):
self.num = num
self.ops = []
self.idx = 0
ops2 = map(tuple, (ops,)) * self.num
res = [[]]
for op in ops2:
res = [x+[y] for x in res for y in op]
self.ops = res
def __iter__(self):
self.idx = 0
return self
def next(self):
if self.idx == len(self.ops):
raise StopIteration
res = tuple(self.ops[self.idx])
self.idx = self.idx + 1
return res
class Solution(object):
def __init__(self):
self.exprs = []
self.idx = 0
def __iter__(self):
self.idx = 0
return self
def next(self):
if self.idx == len(self.expr):
raise StopIteration
res = self.exprs[self.idx]
self.idx = self.idx + 1
return res
def addOperators(self, num, target):
"""
:type num: str
:type target: int
:rtype: List[str]
"""
assert (num)
if len(num) == 1:
return None if eval(num) != target else num
for ops in OpIterator('+-*', len(num)-1):
expr = num[0]
for i in xrange(len(num)-1):
expr = expr + ops[i] + num[i+1]
self.exprs.append(expr)
res = []
for expr in self.exprs:
if eval(expr) == target:
res.append(expr)
return res
def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
'''
for s in OpIterator('+-*', 2):
print s
for s in product('+-*', repeat=2):
print s
for s in getOp('+-*', 2):
print s
'''
if __name__ == "__main__":
s = Solution()
res = s.addOperators('123', 6)
assert (res == ['1+2+3', '1*2*3'])
s = Solution()
res = s.addOperators('232', 8)
assert (set(res) == set(['2*3+2', '2+3*2']))
s = Solution()
res = s.addOperators('105', 5)
assert (set(res) == set(['1*0+5' ]))
s = Solution()
res = s.addOperators('00', 0)
assert (set(res) == set(["0+0", "0-0", "0*0"]))
| mit |
vvw/linearAlgebra-coursera | assignment 7/matrix-hw7/mat.py | 24 | 4760 | from vec import Vec
def getitem(M, k):
"Returns the value of entry k in M. The value of k should be a pair."
assert k[0] in M.D[0] and k[1] in M.D[1]
if (k[0], k[1]) in M.f.keys():
return M.f[(k[0], k[1])]
else:
return 0
def setitem(M, k, val):
"Sets the element of v with label k to be val. The value of k should be a pair"
assert k[0] in M.D[0] and k[1] in M.D[1]
M.f[(k[0], k[1])] = val
def add(A, B):
"Returns the sum of A and B"
assert A.D == B.D
added_matrix = Mat(A.D, {})
for key, val in A.f.items():
added_matrix.f[key] = val
for key, val in B.f.items():
if key in added_matrix.f.keys():
added_matrix.f[key] += val
else:
added_matrix.f[key] = val
return added_matrix
def scalar_mul(M, alpha):
"Returns the product of scalar alpha with M"
return Mat(M.D, {key: (val * alpha) for key, val in M.f.items()})
def equal(A, B):
"Returns true iff A is equal to B"
assert A.D == B.D
for r in A.D[0]:
for c in A.D[1]:
if (r, c) not in A.f.keys():
A.f[(r, c)] = 0
for r in B.D[0]:
for c in B.D[1]:
if (r, c) not in B.f.keys():
B.f[(r, c)] = 0
return A.f == B.f
def transpose(M):
"Returns the transpose of M"
return Mat((M.D[1], M.D[0]), { (q, p):v for (p, q), v in M.f.items() })
def vector_matrix_mul(v, M):
"Returns the product of vector v and matrix M"
assert M.D[0] == v.D
ret_v = Vec(M.D[1], {})
for d in ret_v.D:
ret_v.f[d] = 0
for (k1, k2), val in M.f.items():
ret_v.f[k2] += val * v[k1]
return ret_v
def matrix_vector_mul(M, v):
"Returns the product of matrix M and vector v"
assert M.D[1] == v.D
ret_v = Vec(M.D[0], {})
for d in ret_v.D:
ret_v.f[d] = 0
for (k1, k2), val in M.f.items():
ret_v.f[k1] += val * v[k2]
return ret_v
def matrix_matrix_mul(A, B):
"Returns the product of A and B"
from matutil import mat2coldict, mat2rowdict
assert A.D[1] == B.D[0]
ret_mat = Mat((A.D[0], B.D[1]), {})
a_row = mat2rowdict(A)
b_col = mat2coldict(B)
for key, val in a_row.items():
for key2, val2 in b_col.items():
ret_mat.f[(key, key2)] = val * val2
return ret_mat
################################################################################
class Mat:
def __init__(self, labels, function):
self.D = labels
self.f = function
__getitem__ = getitem
__setitem__ = setitem
transpose = transpose
def __neg__(self):
return (-1)*self
def __mul__(self,other):
if Mat == type(other):
return matrix_matrix_mul(self,other)
elif Vec == type(other):
return matrix_vector_mul(self,other)
else:
return scalar_mul(self,other)
#this will only be used if other is scalar (or not-supported). mat and vec both have __mul__ implemented
def __rmul__(self, other):
if Vec == type(other):
return vector_matrix_mul(other, self)
else: # Assume scalar
return scalar_mul(self, other)
__add__ = add
def __sub__(a,b):
return a+(-b)
__eq__ = equal
def copy(self):
return Mat(self.D, self.f.copy())
def __str__(M, rows=None, cols=None):
"string representation for print()"
if rows == None:
try:
rows = sorted(M.D[0])
except TypeError:
rows = sorted(M.D[0], key=hash)
if cols == None:
try:
cols = sorted(M.D[1])
except TypeError:
cols = sorted(M.D[1], key=hash)
separator = ' | '
numdec = 3
pre = 1+max([len(str(r)) for r in rows])
colw = {col:(1+max([len(str(col))] + [len('{0:.{1}G}'.format(M[row,col],numdec)) if isinstance(M[row,col], int) or isinstance(M[row,col], float) else len(str(M[row,col])) for row in rows])) for col in cols}
s1 = ' '*(1+ pre + len(separator))
s2 = ''.join(['{0:>{1}}'.format(c,colw[c]) for c in cols])
s3 = ' '*(pre+len(separator)) + '-'*(sum(list(colw.values())) + 1)
s4 = ''.join(['{0:>{1}} {2}'.format(r, pre,separator)+''.join(['{0:>{1}.{2}G}'.format(M[r,c],colw[c],numdec) if isinstance(M[r,c], int) or isinstance(M[r,c], float) else '{0:>{1}}'.format(M[r,c], colw[c]) for c in cols])+'\n' for r in rows])
return '\n' + s1 + s2 + '\n' + s3 + '\n' + s4
def pp(self, rows, cols):
print(self.__str__(rows, cols))
def __repr__(self):
"evaluatable representation"
return "Mat(" + str(self.D) +", " + str(self.f) + ")"
| mit |
defionscode/ansible | test/units/modules/network/nxos/test_nxos_ospf_vrf.py | 44 | 2763 | # (c) 2016 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch
from ansible.modules.network.nxos import nxos_ospf_vrf
from .nxos_module import TestNxosModule, set_module_args
class TestNxosOspfVrfModule(TestNxosModule):
module = nxos_ospf_vrf
def setUp(self):
super(TestNxosOspfVrfModule, self).setUp()
self.mock_load_config = patch('ansible.modules.network.nxos.nxos_ospf_vrf.load_config')
self.load_config = self.mock_load_config.start()
self.mock_get_config = patch('ansible.modules.network.nxos.nxos_ospf_vrf.get_config')
self.get_config = self.mock_get_config.start()
def tearDown(self):
super(TestNxosOspfVrfModule, self).tearDown()
self.mock_load_config.stop()
self.mock_get_config.stop()
def load_fixtures(self, commands=None, device=''):
self.load_config.return_value = None
def test_nxos_ospf_vrf_present(self):
set_module_args(dict(ospf=1,
vrf='test',
timer_throttle_spf_start=50,
timer_throttle_spf_hold=1000,
timer_throttle_spf_max=2000,
timer_throttle_lsa_start=60,
timer_throttle_lsa_hold=1100,
timer_throttle_lsa_max=3000,
state='present'))
result = self.execute_module(changed=True)
self.assertEqual(sorted(result['commands']),
sorted(['router ospf 1',
'vrf test',
'timers throttle lsa 60 1100 3000',
'timers throttle spf 50 1000 2000',
'vrf test']))
def test_nxos_ospf_vrf_absent(self):
set_module_args(dict(ospf=1, vrf='test', state='absent'))
result = self.execute_module(changed=False)
self.assertEqual(result['commands'], [])
| gpl-3.0 |
schleichdi2/OPENNFR-6.0-CORE | bitbake/lib/bb/tests/utils.py | 5 | 17025 | # ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
#
# BitBake Tests for utils.py
#
# Copyright (C) 2012 Richard Purdie
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
import unittest
import bb
import os
import tempfile
import re
class VerCmpString(unittest.TestCase):
def test_vercmpstring(self):
result = bb.utils.vercmp_string('1', '2')
self.assertTrue(result < 0)
result = bb.utils.vercmp_string('2', '1')
self.assertTrue(result > 0)
result = bb.utils.vercmp_string('1', '1.0')
self.assertTrue(result < 0)
result = bb.utils.vercmp_string('1', '1.1')
self.assertTrue(result < 0)
result = bb.utils.vercmp_string('1.1', '1_p2')
self.assertTrue(result < 0)
result = bb.utils.vercmp_string('1.0', '1.0+1.1-beta1')
self.assertTrue(result < 0)
result = bb.utils.vercmp_string('1.1', '1.0+1.1-beta1')
self.assertTrue(result > 0)
def test_explode_dep_versions(self):
correctresult = {"foo" : ["= 1.10"]}
result = bb.utils.explode_dep_versions2("foo (= 1.10)")
self.assertEqual(result, correctresult)
result = bb.utils.explode_dep_versions2("foo (=1.10)")
self.assertEqual(result, correctresult)
result = bb.utils.explode_dep_versions2("foo ( = 1.10)")
self.assertEqual(result, correctresult)
result = bb.utils.explode_dep_versions2("foo ( =1.10)")
self.assertEqual(result, correctresult)
result = bb.utils.explode_dep_versions2("foo ( = 1.10 )")
self.assertEqual(result, correctresult)
result = bb.utils.explode_dep_versions2("foo ( =1.10 )")
self.assertEqual(result, correctresult)
def test_vercmp_string_op(self):
compareops = [('1', '1', '=', True),
('1', '1', '==', True),
('1', '1', '!=', False),
('1', '1', '>', False),
('1', '1', '<', False),
('1', '1', '>=', True),
('1', '1', '<=', True),
('1', '0', '=', False),
('1', '0', '==', False),
('1', '0', '!=', True),
('1', '0', '>', True),
('1', '0', '<', False),
('1', '0', '>>', True),
('1', '0', '<<', False),
('1', '0', '>=', True),
('1', '0', '<=', False),
('0', '1', '=', False),
('0', '1', '==', False),
('0', '1', '!=', True),
('0', '1', '>', False),
('0', '1', '<', True),
('0', '1', '>>', False),
('0', '1', '<<', True),
('0', '1', '>=', False),
('0', '1', '<=', True)]
for arg1, arg2, op, correctresult in compareops:
result = bb.utils.vercmp_string_op(arg1, arg2, op)
self.assertEqual(result, correctresult, 'vercmp_string_op("%s", "%s", "%s") != %s' % (arg1, arg2, op, correctresult))
# Check that clearly invalid operator raises an exception
self.assertRaises(bb.utils.VersionStringException, bb.utils.vercmp_string_op, '0', '0', '$')
class Path(unittest.TestCase):
def test_unsafe_delete_path(self):
checkitems = [('/', True),
('//', True),
('///', True),
(os.getcwd().count(os.sep) * ('..' + os.sep), True),
(os.environ.get('HOME', '/home/test'), True),
('/home/someone', True),
('/home/other/', True),
('/home/other/subdir', False),
('', False)]
for arg1, correctresult in checkitems:
result = bb.utils._check_unsafe_delete_path(arg1)
self.assertEqual(result, correctresult, '_check_unsafe_delete_path("%s") != %s' % (arg1, correctresult))
class EditMetadataFile(unittest.TestCase):
_origfile = """
# A comment
HELLO = "oldvalue"
THIS = "that"
# Another comment
NOCHANGE = "samevalue"
OTHER = 'anothervalue'
MULTILINE = "a1 \\
a2 \\
a3"
MULTILINE2 := " \\
b1 \\
b2 \\
b3 \\
"
MULTILINE3 = " \\
c1 \\
c2 \\
c3 \\
"
do_functionname() {
command1 ${VAL1} ${VAL2}
command2 ${VAL3} ${VAL4}
}
"""
def _testeditfile(self, varvalues, compareto, dummyvars=None):
if dummyvars is None:
dummyvars = []
with tempfile.NamedTemporaryFile('w', delete=False) as tf:
tf.write(self._origfile)
tf.close()
try:
varcalls = []
def handle_file(varname, origvalue, op, newlines):
self.assertIn(varname, varvalues, 'Callback called for variable %s not in the list!' % varname)
self.assertNotIn(varname, dummyvars, 'Callback called for variable %s in dummy list!' % varname)
varcalls.append(varname)
return varvalues[varname]
bb.utils.edit_metadata_file(tf.name, varvalues.keys(), handle_file)
with open(tf.name) as f:
modfile = f.readlines()
# Ensure the output matches the expected output
self.assertEqual(compareto.splitlines(True), modfile)
# Ensure the callback function was called for every variable we asked for
# (plus allow testing behaviour when a requested variable is not present)
self.assertEqual(sorted(varvalues.keys()), sorted(varcalls + dummyvars))
finally:
os.remove(tf.name)
def test_edit_metadata_file_nochange(self):
# Test file doesn't get modified with nothing to do
self._testeditfile({}, self._origfile)
# Test file doesn't get modified with only dummy variables
self._testeditfile({'DUMMY1': ('should_not_set', None, 0, True),
'DUMMY2': ('should_not_set_again', None, 0, True)}, self._origfile, dummyvars=['DUMMY1', 'DUMMY2'])
# Test file doesn't get modified with some the same values
self._testeditfile({'THIS': ('that', None, 0, True),
'OTHER': ('anothervalue', None, 0, True),
'MULTILINE3': (' c1 c2 c3 ', None, 4, False)}, self._origfile)
def test_edit_metadata_file_1(self):
newfile1 = """
# A comment
HELLO = "newvalue"
THIS = "that"
# Another comment
NOCHANGE = "samevalue"
OTHER = 'anothervalue'
MULTILINE = "a1 \\
a2 \\
a3"
MULTILINE2 := " \\
b1 \\
b2 \\
b3 \\
"
MULTILINE3 = " \\
c1 \\
c2 \\
c3 \\
"
do_functionname() {
command1 ${VAL1} ${VAL2}
command2 ${VAL3} ${VAL4}
}
"""
self._testeditfile({'HELLO': ('newvalue', None, 4, True)}, newfile1)
def test_edit_metadata_file_2(self):
newfile2 = """
# A comment
HELLO = "oldvalue"
THIS = "that"
# Another comment
NOCHANGE = "samevalue"
OTHER = 'anothervalue'
MULTILINE = " \\
d1 \\
d2 \\
d3 \\
"
MULTILINE2 := " \\
b1 \\
b2 \\
b3 \\
"
MULTILINE3 = "nowsingle"
do_functionname() {
command1 ${VAL1} ${VAL2}
command2 ${VAL3} ${VAL4}
}
"""
self._testeditfile({'MULTILINE': (['d1','d2','d3'], None, 4, False),
'MULTILINE3': ('nowsingle', None, 4, True),
'NOTPRESENT': (['a', 'b'], None, 4, False)}, newfile2, dummyvars=['NOTPRESENT'])
def test_edit_metadata_file_3(self):
newfile3 = """
# A comment
HELLO = "oldvalue"
# Another comment
NOCHANGE = "samevalue"
OTHER = "yetanothervalue"
MULTILINE = "e1 \\
e2 \\
e3 \\
"
MULTILINE2 := "f1 \\
\tf2 \\
\t"
MULTILINE3 = " \\
c1 \\
c2 \\
c3 \\
"
do_functionname() {
othercommand_one a b c
othercommand_two d e f
}
"""
self._testeditfile({'do_functionname()': (['othercommand_one a b c', 'othercommand_two d e f'], None, 4, False),
'MULTILINE2': (['f1', 'f2'], None, '\t', True),
'MULTILINE': (['e1', 'e2', 'e3'], None, -1, True),
'THIS': (None, None, 0, False),
'OTHER': ('yetanothervalue', None, 0, True)}, newfile3)
def test_edit_metadata_file_4(self):
newfile4 = """
# A comment
HELLO = "oldvalue"
THIS = "that"
# Another comment
OTHER = 'anothervalue'
MULTILINE = "a1 \\
a2 \\
a3"
MULTILINE2 := " \\
b1 \\
b2 \\
b3 \\
"
"""
self._testeditfile({'NOCHANGE': (None, None, 0, False),
'MULTILINE3': (None, None, 0, False),
'THIS': ('that', None, 0, False),
'do_functionname()': (None, None, 0, False)}, newfile4)
def test_edit_metadata(self):
newfile5 = """
# A comment
HELLO = "hithere"
# A new comment
THIS += "that"
# Another comment
NOCHANGE = "samevalue"
OTHER = 'anothervalue'
MULTILINE = "a1 \\
a2 \\
a3"
MULTILINE2 := " \\
b1 \\
b2 \\
b3 \\
"
MULTILINE3 = " \\
c1 \\
c2 \\
c3 \\
"
NEWVAR = "value"
do_functionname() {
command1 ${VAL1} ${VAL2}
command2 ${VAL3} ${VAL4}
}
"""
def handle_var(varname, origvalue, op, newlines):
if varname == 'THIS':
newlines.append('# A new comment\n')
elif varname == 'do_functionname()':
newlines.append('NEWVAR = "value"\n')
newlines.append('\n')
valueitem = varvalues.get(varname, None)
if valueitem:
return valueitem
else:
return (origvalue, op, 0, True)
varvalues = {'HELLO': ('hithere', None, 0, True), 'THIS': ('that', '+=', 0, True)}
varlist = ['HELLO', 'THIS', 'do_functionname()']
(updated, newlines) = bb.utils.edit_metadata(self._origfile.splitlines(True), varlist, handle_var)
self.assertTrue(updated, 'List should be updated but isn\'t')
self.assertEqual(newlines, newfile5.splitlines(True))
# Make sure the orig value matches what we expect it to be
def test_edit_metadata_origvalue(self):
origfile = """
MULTILINE = " stuff \\
morestuff"
"""
expected_value = "stuff morestuff"
global value_in_callback
value_in_callback = ""
def handle_var(varname, origvalue, op, newlines):
global value_in_callback
value_in_callback = origvalue
return (origvalue, op, -1, False)
bb.utils.edit_metadata(origfile.splitlines(True),
['MULTILINE'],
handle_var)
testvalue = re.sub('\s+', ' ', value_in_callback.strip())
self.assertEqual(expected_value, testvalue)
class EditBbLayersConf(unittest.TestCase):
def _test_bblayers_edit(self, before, after, add, remove, notadded, notremoved):
with tempfile.NamedTemporaryFile('w', delete=False) as tf:
tf.write(before)
tf.close()
try:
actual_notadded, actual_notremoved = bb.utils.edit_bblayers_conf(tf.name, add, remove)
with open(tf.name) as f:
actual_after = f.readlines()
self.assertEqual(after.splitlines(True), actual_after)
self.assertEqual(notadded, actual_notadded)
self.assertEqual(notremoved, actual_notremoved)
finally:
os.remove(tf.name)
def test_bblayers_remove(self):
before = r"""
# A comment
BBPATH = "${TOPDIR}"
BBFILES ?= ""
BBLAYERS = " \
/home/user/path/layer1 \
/home/user/path/layer2 \
/home/user/path/subpath/layer3 \
/home/user/path/layer4 \
"
"""
after = r"""
# A comment
BBPATH = "${TOPDIR}"
BBFILES ?= ""
BBLAYERS = " \
/home/user/path/layer1 \
/home/user/path/subpath/layer3 \
/home/user/path/layer4 \
"
"""
self._test_bblayers_edit(before, after,
None,
'/home/user/path/layer2',
[],
[])
def test_bblayers_add(self):
before = r"""
# A comment
BBPATH = "${TOPDIR}"
BBFILES ?= ""
BBLAYERS = " \
/home/user/path/layer1 \
/home/user/path/layer2 \
/home/user/path/subpath/layer3 \
/home/user/path/layer4 \
"
"""
after = r"""
# A comment
BBPATH = "${TOPDIR}"
BBFILES ?= ""
BBLAYERS = " \
/home/user/path/layer1 \
/home/user/path/layer2 \
/home/user/path/subpath/layer3 \
/home/user/path/layer4 \
/other/path/to/layer5 \
"
"""
self._test_bblayers_edit(before, after,
'/other/path/to/layer5/',
None,
[],
[])
def test_bblayers_add_remove(self):
before = r"""
# A comment
BBPATH = "${TOPDIR}"
BBFILES ?= ""
BBLAYERS = " \
/home/user/path/layer1 \
/home/user/path/layer2 \
/home/user/path/subpath/layer3 \
/home/user/path/layer4 \
"
"""
after = r"""
# A comment
BBPATH = "${TOPDIR}"
BBFILES ?= ""
BBLAYERS = " \
/home/user/path/layer1 \
/home/user/path/layer2 \
/home/user/path/layer4 \
/other/path/to/layer5 \
"
"""
self._test_bblayers_edit(before, after,
['/other/path/to/layer5', '/home/user/path/layer2/'], '/home/user/path/subpath/layer3/',
['/home/user/path/layer2'],
[])
def test_bblayers_add_remove_home(self):
before = r"""
# A comment
BBPATH = "${TOPDIR}"
BBFILES ?= ""
BBLAYERS = " \
~/path/layer1 \
~/path/layer2 \
~/otherpath/layer3 \
~/path/layer4 \
"
"""
after = r"""
# A comment
BBPATH = "${TOPDIR}"
BBFILES ?= ""
BBLAYERS = " \
~/path/layer2 \
~/path/layer4 \
~/path2/layer5 \
"
"""
self._test_bblayers_edit(before, after,
[os.environ['HOME'] + '/path/layer4', '~/path2/layer5'],
[os.environ['HOME'] + '/otherpath/layer3', '~/path/layer1', '~/path/notinlist'],
[os.environ['HOME'] + '/path/layer4'],
['~/path/notinlist'])
def test_bblayers_add_remove_plusequals(self):
before = r"""
# A comment
BBPATH = "${TOPDIR}"
BBFILES ?= ""
BBLAYERS += " \
/home/user/path/layer1 \
/home/user/path/layer2 \
"
"""
after = r"""
# A comment
BBPATH = "${TOPDIR}"
BBFILES ?= ""
BBLAYERS += " \
/home/user/path/layer2 \
/home/user/path/layer3 \
"
"""
self._test_bblayers_edit(before, after,
'/home/user/path/layer3',
'/home/user/path/layer1',
[],
[])
def test_bblayers_add_remove_plusequals2(self):
before = r"""
# A comment
BBPATH = "${TOPDIR}"
BBFILES ?= ""
BBLAYERS += " \
/home/user/path/layer1 \
/home/user/path/layer2 \
/home/user/path/layer3 \
"
BBLAYERS += "/home/user/path/layer4"
BBLAYERS += "/home/user/path/layer5"
"""
after = r"""
# A comment
BBPATH = "${TOPDIR}"
BBFILES ?= ""
BBLAYERS += " \
/home/user/path/layer2 \
/home/user/path/layer3 \
"
BBLAYERS += "/home/user/path/layer5"
BBLAYERS += "/home/user/otherpath/layer6"
"""
self._test_bblayers_edit(before, after,
['/home/user/otherpath/layer6', '/home/user/path/layer3'], ['/home/user/path/layer1', '/home/user/path/layer4', '/home/user/path/layer7'],
['/home/user/path/layer3'],
['/home/user/path/layer7'])
| gpl-2.0 |
bealdav/OCB | addons/stock_account/wizard/stock_invoice_onshipping.py | 120 | 6111 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
from openerp.tools.translate import _
class stock_invoice_onshipping(osv.osv_memory):
def _get_journal(self, cr, uid, context=None):
journal_obj = self.pool.get('account.journal')
journal_type = self._get_journal_type(cr, uid, context=context)
journals = journal_obj.search(cr, uid, [('type', '=', journal_type)])
return journals and journals[0] or False
def _get_journal_type(self, cr, uid, context=None):
if context is None:
context = {}
res_ids = context and context.get('active_ids', [])
pick_obj = self.pool.get('stock.picking')
pickings = pick_obj.browse(cr, uid, res_ids, context=context)
vals = []
pick = pickings and pickings[0]
if not pick or not pick.move_lines:
return 'sale'
src_usage = pick.move_lines[0].location_id.usage
dest_usage = pick.move_lines[0].location_dest_id.usage
type = pick.picking_type_id.code
if type == 'outgoing' and dest_usage == 'supplier':
journal_type = 'purchase_refund'
elif type == 'outgoing' and dest_usage == 'customer':
journal_type = 'sale'
elif type == 'incoming' and src_usage == 'supplier':
journal_type = 'purchase'
elif type == 'incoming' and src_usage == 'customer':
journal_type = 'sale_refund'
else:
journal_type = 'sale'
return journal_type
_name = "stock.invoice.onshipping"
_description = "Stock Invoice Onshipping"
_columns = {
'journal_id': fields.many2one('account.journal', 'Destination Journal', required=True),
'journal_type': fields.selection([('purchase_refund', 'Refund Purchase'), ('purchase', 'Create Supplier Invoice'),
('sale_refund', 'Refund Sale'), ('sale', 'Create Customer Invoice')], 'Journal Type', readonly=True),
'group': fields.boolean("Group by partner"),
'invoice_date': fields.date('Invoice Date'),
}
_defaults = {
'journal_type': _get_journal_type,
'journal_id' : _get_journal,
}
def view_init(self, cr, uid, fields_list, context=None):
if context is None:
context = {}
res = super(stock_invoice_onshipping, self).view_init(cr, uid, fields_list, context=context)
pick_obj = self.pool.get('stock.picking')
count = 0
active_ids = context.get('active_ids',[])
for pick in pick_obj.browse(cr, uid, active_ids, context=context):
if pick.invoice_state != '2binvoiced':
count += 1
if len(active_ids) == count:
raise osv.except_osv(_('Warning!'), _('None of these picking lists require invoicing.'))
return res
def open_invoice(self, cr, uid, ids, context=None):
if context is None:
context = {}
invoice_ids = self.create_invoice(cr, uid, ids, context=context)
if not invoice_ids:
raise osv.except_osv(_('Error!'), _('No invoice created!'))
data = self.browse(cr, uid, ids[0], context=context)
action_model = False
action = {}
journal2type = {'sale':'out_invoice', 'purchase':'in_invoice' , 'sale_refund':'out_refund', 'purchase_refund':'in_refund'}
inv_type = journal2type.get(data.journal_type) or 'out_invoice'
data_pool = self.pool.get('ir.model.data')
if inv_type == "out_invoice":
action_id = data_pool.xmlid_to_res_id(cr, uid, 'account.action_invoice_tree1')
elif inv_type == "in_invoice":
action_id = data_pool.xmlid_to_res_id(cr, uid, 'account.action_invoice_tree2')
elif inv_type == "out_refund":
action_id = data_pool.xmlid_to_res_id(cr, uid, 'account.action_invoice_tree3')
elif inv_type == "in_refund":
action_id = data_pool.xmlid_to_res_id(cr, uid, 'account.action_invoice_tree4')
if action_id:
action_pool = self.pool['ir.actions.act_window']
action = action_pool.read(cr, uid, action_id, context=context)
action['domain'] = "[('id','in', ["+','.join(map(str,invoice_ids))+"])]"
return action
return True
def create_invoice(self, cr, uid, ids, context=None):
context = dict(context or {})
picking_pool = self.pool.get('stock.picking')
data = self.browse(cr, uid, ids[0], context=context)
journal2type = {'sale':'out_invoice', 'purchase':'in_invoice', 'sale_refund':'out_refund', 'purchase_refund':'in_refund'}
context['date_inv'] = data.invoice_date
acc_journal = self.pool.get("account.journal")
inv_type = journal2type.get(data.journal_type) or 'out_invoice'
context['inv_type'] = inv_type
active_ids = context.get('active_ids', [])
res = picking_pool.action_invoice_create(cr, uid, active_ids,
journal_id = data.journal_id.id,
group = data.group,
type = inv_type,
context=context)
return res
| agpl-3.0 |
MCMic/Sick-Beard | cherrypy/__init__.py | 35 | 20462 | """CherryPy is a pythonic, object-oriented HTTP framework.
CherryPy consists of not one, but four separate API layers.
The APPLICATION LAYER is the simplest. CherryPy applications are written as
a tree of classes and methods, where each branch in the tree corresponds to
a branch in the URL path. Each method is a 'page handler', which receives
GET and POST params as keyword arguments, and returns or yields the (HTML)
body of the response. The special method name 'index' is used for paths
that end in a slash, and the special method name 'default' is used to
handle multiple paths via a single handler. This layer also includes:
* the 'exposed' attribute (and cherrypy.expose)
* cherrypy.quickstart()
* _cp_config attributes
* cherrypy.tools (including cherrypy.session)
* cherrypy.url()
The ENVIRONMENT LAYER is used by developers at all levels. It provides
information about the current request and response, plus the application
and server environment, via a (default) set of top-level objects:
* cherrypy.request
* cherrypy.response
* cherrypy.engine
* cherrypy.server
* cherrypy.tree
* cherrypy.config
* cherrypy.thread_data
* cherrypy.log
* cherrypy.HTTPError, NotFound, and HTTPRedirect
* cherrypy.lib
The EXTENSION LAYER allows advanced users to construct and share their own
plugins. It consists of:
* Hook API
* Tool API
* Toolbox API
* Dispatch API
* Config Namespace API
Finally, there is the CORE LAYER, which uses the core API's to construct
the default components which are available at higher layers. You can think
of the default components as the 'reference implementation' for CherryPy.
Megaframeworks (and advanced users) may replace the default components
with customized or extended components. The core API's are:
* Application API
* Engine API
* Request API
* Server API
* WSGI API
These API's are described in the CherryPy specification:
http://www.cherrypy.org/wiki/CherryPySpec
"""
__version__ = "3.2.0rc1"
from urlparse import urljoin as _urljoin
from urllib import urlencode as _urlencode
class _AttributeDocstrings(type):
"""Metaclass for declaring docstrings for class attributes."""
# The full docstring for this type is down in the __init__ method so
# that it doesn't show up in help() for every consumer class.
def __init__(cls, name, bases, dct):
'''Metaclass for declaring docstrings for class attributes.
Base Python doesn't provide any syntax for setting docstrings on
'data attributes' (non-callables). This metaclass allows class
definitions to follow the declaration of a data attribute with
a docstring for that attribute; the attribute docstring will be
popped from the class dict and folded into the class docstring.
The naming convention for attribute docstrings is:
<attrname> + "__doc".
For example:
class Thing(object):
"""A thing and its properties."""
__metaclass__ = cherrypy._AttributeDocstrings
height = 50
height__doc = """The height of the Thing in inches."""
In which case, help(Thing) starts like this:
>>> help(mod.Thing)
Help on class Thing in module pkg.mod:
class Thing(__builtin__.object)
| A thing and its properties.
|
| height [= 50]:
| The height of the Thing in inches.
|
The benefits of this approach over hand-edited class docstrings:
1. Places the docstring nearer to the attribute declaration.
2. Makes attribute docs more uniform ("name (default): doc").
3. Reduces mismatches of attribute _names_ between
the declaration and the documentation.
4. Reduces mismatches of attribute default _values_ between
the declaration and the documentation.
The benefits of a metaclass approach over other approaches:
1. Simpler ("less magic") than interface-based solutions.
2. __metaclass__ can be specified at the module global level
for classic classes.
For various formatting reasons, you should write multiline docs
with a leading newline and not a trailing one:
response__doc = """
The response object for the current thread. In the main thread,
and any threads which are not HTTP requests, this is None."""
The type of the attribute is intentionally not included, because
that's not How Python Works. Quack.
'''
newdoc = [cls.__doc__ or ""]
dctkeys = dct.keys()
dctkeys.sort()
for name in dctkeys:
if name.endswith("__doc"):
# Remove the magic doc attribute.
if hasattr(cls, name):
delattr(cls, name)
# Make a uniformly-indented docstring from it.
val = '\n'.join([' ' + line.strip()
for line in dct[name].split('\n')])
# Get the default value.
attrname = name[:-5]
try:
attrval = getattr(cls, attrname)
except AttributeError:
attrval = "missing"
# Add the complete attribute docstring to our list.
newdoc.append("%s [= %r]:\n%s" % (attrname, attrval, val))
# Add our list of new docstrings to the class docstring.
cls.__doc__ = "\n\n".join(newdoc)
from cherrypy._cperror import HTTPError, HTTPRedirect, InternalRedirect
from cherrypy._cperror import NotFound, CherryPyException, TimeoutError
from cherrypy import _cpdispatch as dispatch
from cherrypy import _cptools
tools = _cptools.default_toolbox
Tool = _cptools.Tool
from cherrypy import _cprequest
from cherrypy.lib import httputil as _httputil
from cherrypy import _cptree
tree = _cptree.Tree()
from cherrypy._cptree import Application
from cherrypy import _cpwsgi as wsgi
from cherrypy import process
try:
from cherrypy.process import win32
engine = win32.Win32Bus()
engine.console_control_handler = win32.ConsoleCtrlHandler(engine)
del win32
except ImportError:
engine = process.bus
# Timeout monitor
class _TimeoutMonitor(process.plugins.Monitor):
def __init__(self, bus):
self.servings = []
process.plugins.Monitor.__init__(self, bus, self.run)
def acquire(self):
self.servings.append((serving.request, serving.response))
def release(self):
try:
self.servings.remove((serving.request, serving.response))
except ValueError:
pass
def run(self):
"""Check timeout on all responses. (Internal)"""
for req, resp in self.servings:
resp.check_timeout()
engine.timeout_monitor = _TimeoutMonitor(engine)
engine.timeout_monitor.subscribe()
engine.autoreload = process.plugins.Autoreloader(engine)
engine.autoreload.subscribe()
engine.thread_manager = process.plugins.ThreadManager(engine)
engine.thread_manager.subscribe()
engine.signal_handler = process.plugins.SignalHandler(engine)
from cherrypy import _cpserver
server = _cpserver.Server()
server.subscribe()
def quickstart(root=None, script_name="", config=None):
"""Mount the given root, start the builtin server (and engine), then block.
root: an instance of a "controller class" (a collection of page handler
methods) which represents the root of the application.
script_name: a string containing the "mount point" of the application.
This should start with a slash, and be the path portion of the URL
at which to mount the given root. For example, if root.index() will
handle requests to "http://www.example.com:8080/dept/app1/", then
the script_name argument would be "/dept/app1".
It MUST NOT end in a slash. If the script_name refers to the root
of the URI, it MUST be an empty string (not "/").
config: a file or dict containing application config. If this contains
a [global] section, those entries will be used in the global
(site-wide) config.
"""
if config:
_global_conf_alias.update(config)
tree.mount(root, script_name, config)
if hasattr(engine, "signal_handler"):
engine.signal_handler.subscribe()
if hasattr(engine, "console_control_handler"):
engine.console_control_handler.subscribe()
engine.start()
engine.block()
try:
from threading import local as _local
except ImportError:
from cherrypy._cpthreadinglocal import local as _local
class _Serving(_local):
"""An interface for registering request and response objects.
Rather than have a separate "thread local" object for the request and
the response, this class works as a single threadlocal container for
both objects (and any others which developers wish to define). In this
way, we can easily dump those objects when we stop/start a new HTTP
conversation, yet still refer to them as module-level globals in a
thread-safe way.
"""
__metaclass__ = _AttributeDocstrings
request = _cprequest.Request(_httputil.Host("127.0.0.1", 80),
_httputil.Host("127.0.0.1", 1111))
request__doc = """
The request object for the current thread. In the main thread,
and any threads which are not receiving HTTP requests, this is None."""
response = _cprequest.Response()
response__doc = """
The response object for the current thread. In the main thread,
and any threads which are not receiving HTTP requests, this is None."""
def load(self, request, response):
self.request = request
self.response = response
def clear(self):
"""Remove all attributes of self."""
self.__dict__.clear()
serving = _Serving()
class _ThreadLocalProxy(object):
__slots__ = ['__attrname__', '__dict__']
def __init__(self, attrname):
self.__attrname__ = attrname
def __getattr__(self, name):
child = getattr(serving, self.__attrname__)
return getattr(child, name)
def __setattr__(self, name, value):
if name in ("__attrname__",):
object.__setattr__(self, name, value)
else:
child = getattr(serving, self.__attrname__)
setattr(child, name, value)
def __delattr__(self, name):
child = getattr(serving, self.__attrname__)
delattr(child, name)
def _get_dict(self):
child = getattr(serving, self.__attrname__)
d = child.__class__.__dict__.copy()
d.update(child.__dict__)
return d
__dict__ = property(_get_dict)
def __getitem__(self, key):
child = getattr(serving, self.__attrname__)
return child[key]
def __setitem__(self, key, value):
child = getattr(serving, self.__attrname__)
child[key] = value
def __delitem__(self, key):
child = getattr(serving, self.__attrname__)
del child[key]
def __contains__(self, key):
child = getattr(serving, self.__attrname__)
return key in child
def __len__(self):
child = getattr(serving, self.__attrname__)
return len(child)
def __nonzero__(self):
child = getattr(serving, self.__attrname__)
return bool(child)
# Create request and response object (the same objects will be used
# throughout the entire life of the webserver, but will redirect
# to the "serving" object)
request = _ThreadLocalProxy('request')
response = _ThreadLocalProxy('response')
# Create thread_data object as a thread-specific all-purpose storage
class _ThreadData(_local):
"""A container for thread-specific data."""
thread_data = _ThreadData()
# Monkeypatch pydoc to allow help() to go through the threadlocal proxy.
# Jan 2007: no Googleable examples of anyone else replacing pydoc.resolve.
# The only other way would be to change what is returned from type(request)
# and that's not possible in pure Python (you'd have to fake ob_type).
def _cherrypy_pydoc_resolve(thing, forceload=0):
"""Given an object or a path to an object, get the object and its name."""
if isinstance(thing, _ThreadLocalProxy):
thing = getattr(serving, thing.__attrname__)
return _pydoc._builtin_resolve(thing, forceload)
try:
import pydoc as _pydoc
_pydoc._builtin_resolve = _pydoc.resolve
_pydoc.resolve = _cherrypy_pydoc_resolve
except ImportError:
pass
from cherrypy import _cplogging
class _GlobalLogManager(_cplogging.LogManager):
def __call__(self, *args, **kwargs):
# Do NOT use try/except here. See http://www.cherrypy.org/ticket/945
if hasattr(request, 'app') and hasattr(request.app, 'log'):
log = request.app.log
else:
log = self
return log.error(*args, **kwargs)
def access(self):
try:
return request.app.log.access()
except AttributeError:
return _cplogging.LogManager.access(self)
log = _GlobalLogManager()
# Set a default screen handler on the global log.
log.screen = True
log.error_file = ''
# Using an access file makes CP about 10% slower. Leave off by default.
log.access_file = ''
def _buslog(msg, level):
log.error(msg, 'ENGINE', severity=level)
engine.subscribe('log', _buslog)
# Helper functions for CP apps #
def expose(func=None, alias=None):
"""Expose the function, optionally providing an alias or set of aliases."""
def expose_(func):
func.exposed = True
if alias is not None:
if isinstance(alias, basestring):
parents[alias.replace(".", "_")] = func
else:
for a in alias:
parents[a.replace(".", "_")] = func
return func
import sys, types
if isinstance(func, (types.FunctionType, types.MethodType)):
if alias is None:
# @expose
func.exposed = True
return func
else:
# func = expose(func, alias)
parents = sys._getframe(1).f_locals
return expose_(func)
elif func is None:
if alias is None:
# @expose()
parents = sys._getframe(1).f_locals
return expose_
else:
# @expose(alias="alias") or
# @expose(alias=["alias1", "alias2"])
parents = sys._getframe(1).f_locals
return expose_
else:
# @expose("alias") or
# @expose(["alias1", "alias2"])
parents = sys._getframe(1).f_locals
alias = func
return expose_
def url(path="", qs="", script_name=None, base=None, relative=None):
"""Create an absolute URL for the given path.
If 'path' starts with a slash ('/'), this will return
(base + script_name + path + qs).
If it does not start with a slash, this returns
(base + script_name [+ request.path_info] + path + qs).
If script_name is None, cherrypy.request will be used
to find a script_name, if available.
If base is None, cherrypy.request.base will be used (if available).
Note that you can use cherrypy.tools.proxy to change this.
Finally, note that this function can be used to obtain an absolute URL
for the current request path (minus the querystring) by passing no args.
If you call url(qs=cherrypy.request.query_string), you should get the
original browser URL (assuming no internal redirections).
If relative is None or not provided, request.app.relative_urls will
be used (if available, else False). If False, the output will be an
absolute URL (including the scheme, host, vhost, and script_name).
If True, the output will instead be a URL that is relative to the
current request path, perhaps including '..' atoms. If relative is
the string 'server', the output will instead be a URL that is
relative to the server root; i.e., it will start with a slash.
"""
if isinstance(qs, (tuple, list, dict)):
qs = _urlencode(qs)
if qs:
qs = '?' + qs
if request.app:
if not path.startswith("/"):
# Append/remove trailing slash from path_info as needed
# (this is to support mistyped URL's without redirecting;
# if you want to redirect, use tools.trailing_slash).
pi = request.path_info
if request.is_index is True:
if not pi.endswith('/'):
pi = pi + '/'
elif request.is_index is False:
if pi.endswith('/') and pi != '/':
pi = pi[:-1]
if path == "":
path = pi
else:
path = _urljoin(pi, path)
if script_name is None:
script_name = request.script_name
if base is None:
base = request.base
newurl = base + script_name + path + qs
else:
# No request.app (we're being called outside a request).
# We'll have to guess the base from server.* attributes.
# This will produce very different results from the above
# if you're using vhosts or tools.proxy.
if base is None:
base = server.base()
path = (script_name or "") + path
newurl = base + path + qs
if './' in newurl:
# Normalize the URL by removing ./ and ../
atoms = []
for atom in newurl.split('/'):
if atom == '.':
pass
elif atom == '..':
atoms.pop()
else:
atoms.append(atom)
newurl = '/'.join(atoms)
# At this point, we should have a fully-qualified absolute URL.
if relative is None:
relative = getattr(request.app, "relative_urls", False)
# See http://www.ietf.org/rfc/rfc2396.txt
if relative == 'server':
# "A relative reference beginning with a single slash character is
# termed an absolute-path reference, as defined by <abs_path>..."
# This is also sometimes called "server-relative".
newurl = '/' + '/'.join(newurl.split('/', 3)[3:])
elif relative:
# "A relative reference that does not begin with a scheme name
# or a slash character is termed a relative-path reference."
old = url().split('/')[:-1]
new = newurl.split('/')
while old and new:
a, b = old[0], new[0]
if a != b:
break
old.pop(0)
new.pop(0)
new = (['..'] * len(old)) + new
newurl = '/'.join(new)
return newurl
# import _cpconfig last so it can reference other top-level objects
from cherrypy import _cpconfig
# Use _global_conf_alias so quickstart can use 'config' as an arg
# without shadowing cherrypy.config.
config = _global_conf_alias = _cpconfig.Config()
config.defaults = {
'tools.log_tracebacks.on': True,
'tools.log_headers.on': True,
'tools.trailing_slash.on': True,
'tools.encode.on': True
}
config.namespaces["log"] = lambda k, v: setattr(log, k, v)
config.namespaces["checker"] = lambda k, v: setattr(checker, k, v)
# Must reset to get our defaults applied.
config.reset()
from cherrypy import _cpchecker
checker = _cpchecker.Checker()
engine.subscribe('start', checker)
| gpl-3.0 |
amarandon/opencore | opencore/models/tests/test_attachments.py | 4 | 2026 | # Copyright (C) 2008-2009 Open Society Institute
# Thomas Moroz: tmoroz.org
# 2010-2011 Large Blue
# Fergus Doyle: fergus.doyle@largeblue.com
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License Version 2 as published
# by the Free Software Foundation. You may not use, modify or distribute
# this program under any other version of the GNU General Public License.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
import unittest
from repoze.bfg import testing
class AttachmentsFolderTests(unittest.TestCase):
def _getTargetClass(self):
from opencore.models.attachments import AttachmentsFolder
return AttachmentsFolder
def _makeOne(self):
return self._getTargetClass()()
def test_class_conforms_to_IAttachmentsFolder(self):
from zope.interface.verify import verifyClass
from opencore.models.interfaces import IAttachmentsFolder
verifyClass(IAttachmentsFolder, self._getTargetClass())
def test_instance_conforms_to_IAttachmentsFolder(self):
from zope.interface.verify import verifyObject
from opencore.models.interfaces import IAttachmentsFolder
verifyObject(IAttachmentsFolder, self._makeOne())
def test_next_id_nomembers(self):
attachments = self._makeOne()
self.assertEqual(attachments.next_id, '1')
def test_next_id_wthmembers(self):
attachments = self._makeOne()
attachments['1'] = testing.DummyModel()
self.assertEqual(attachments.next_id, '2')
| gpl-2.0 |
thisismyrobot/dsa | src/binary_tree.py | 1 | 1762 | """ A binary tree implementation.
"""
class Node(object):
""" A binary tree node.
"""
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def __str__(self):
return str(self.data)
class BinaryTree(object):
def __init__(self, root_node=None):
self.root_node = root_node
def insert(self, data):
node = Node(data)
if self.root_node is None:
self.root_node = node
return
# Walk the tree and insert/replace
cursor = self.root_node
while True:
if node.data < cursor.data:
if cursor.left:
cursor = cursor.left
continue
cursor.left = node
break
elif node.data > cursor.data:
if cursor.right:
cursor = cursor.right
continue
cursor.right = node
break
else:
cursor = node
def populate(self, data_items):
self.root_node = None
for data in data_items:
self.insert(data)
def inorder(self, node, result=None):
""" Recursive in-order traversal.
"""
if result is None:
result = []
if node:
self.inorder(node.left, result)
result.append(node.data)
self.inorder(node.right, result)
return result
def __str__(self):
""" Return an inorder representation of the tree.
"""
result = self.inorder(self.root_node)
return ' '.join(result)
| unlicense |
sol-ansano-kim/minimap | minimap/mayaFunction.py | 1 | 4363 | from maya import cmds
from maya import OpenMayaUI
from maya import OpenMaya
import os
## TODO
class View(object):
def __init__(self):
super(View, self).__init__()
self.view = OpenMayaUI.M3dView.active3dView()
self.camera = OpenMaya.MDagPath()
self.view.getCamera(self.camera)
def camera(self):
if (self.camera.isValid()):
return self.camera.partialPathName()
return None
def size(self):
return (self.view.portWidth(), self.view.portHeight())
class Camera(object):
PAN_H = "horizontalPan"
PAN_V = "verticalPan"
PAN_ZOOM = "zoom"
PAN_ENABLE = "panZoomEnabled"
ASPECT_H = "horizontalFilmAperture"
ASPECT_V = "verticalFilmAperture"
IMAGE_H = "sizeX"
IMAGE_V = "sizeY"
IMAGE_PATH = "imageName"
IMAGE_PLANE_TYPE = "imagePlane"
IMAGE_FIT = "fit"
def __init__(self, camera_name):
super(Camera, self).__init__()
self.image_plane = None
self.image_path = None
self.name = camera_name
self.getImagePlane()
def __attr(self, attr_name):
return "%s.%s" % (self.name, attr_name)
def __isSetable(self, attr):
if (cmds.listConnections(attr, s=1, d=0) != None):
cmds.warning("attr has a input connections : %s" % (attr))
return False
if (cmds.getAttr(attr, l=1)):
cmds.warning("attr is locked : %s" % (attr))
return False
return True
def __exists(self, attr_name):
if (self.exists() == False):
cmds.waning("could not find camera : %s" % (self.name))
return False
if (cmds.attributeQuery(attr_name, n=self.name, ex=1) == False):
cmds.warning("could not find the attribute : %s" % (attr_name))
return False
return True
def exists(self):
return cmds.objExists(self.name)
def getImagePlane(self):
cons = cmds.listConnections(self.name, s=1, d=0,
type=Camera.IMAGE_PLANE_TYPE)
if cons != None:
self.image_plane = cons[0]
img = cmds.getAttr("%s.%s" % (self.image_plane, Camera.IMAGE_PATH))
if img and os.path.isfile(img):
self.image_path = img
else:
self.image_path = None
else:
self.image_plane = None
self.image_path = None
def set(self, attr_name, value):
attr = self.__attr(attr_name)
if (self.__exists(attr_name) and self.__isSetable(attr)):
cmds.setAttr(attr, value)
def get(self, attr_name):
if (self.__exists(attr_name)):
return cmds.getAttr(self.__attr(attr_name))
return None
def aspectH(self):
if self.image_plane:
return cmds.getAttr("%s.%s" % (self.image_plane, Camera.IMAGE_H))
return self.get(Camera.ASPECT_H)
def aspectV(self):
if self.image_plane:
return cmds.getAttr("%s.%s" % (self.image_plane, Camera.IMAGE_V))
return self.get(Camera.ASPECT_V)
def checkPanEnable(self):
if (self.get(Camera.PAN_ENABLE) == False):
self.set(Camera.PAN_ENABLE, True)
def setH(self, value):
self.checkPanEnable()
self.set(Camera.PAN_H, value)
def setV(self, value):
self.set(Camera.PAN_V, value)
def setZoom(self, value):
self.set(Camera.PAN_ZOOM, value)
def getH(self):
return self.get(Camera.PAN_H)
def getV(self):
return self.get(Camera.PAN_V)
def getZoom(self):
return self.get(Camera.PAN_ZOOM)
def resetPan(self):
self.setZoom(1.0)
self.setV(0)
self.setH(0)
def fitType(self):
if self.image_plane:
return cmds.getAttr("%s.%s" % (self.image_plane, Camera.IMAGE_FIT))
def killExistenceWindow(window_name):
if cmds.window(window_name, q=1, ex=1):
cmds.deleteUI(window_name)
def getCamera():
sels = cmds.ls(sl=1)
if sels:
obj = sels[0]
if cmds.objectType(obj) == "transform":
shapes = cmds.listRelatives(obj, s=1)
if shapes:
obj = shapes[0]
if cmds.objectType(obj) == "camera":
return obj
cmds.warning("select a camera")
return None
| gpl-2.0 |
jkugler/ansible | lib/ansible/plugins/action/group_by.py | 172 | 1401 | # Copyright 2012, Jeroen Hoekx <jeroen@hoekx.be>
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.errors import *
from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
''' Create inventory groups based on variables '''
### We need to be able to modify the inventory
BYPASS_HOST_LOOP = True
TRANSFERS_FILES = False
def run(self, tmp=None, task_vars=dict()):
if not 'key' in self._task.args:
return dict(failed=True, msg="the 'key' param is required when using group_by")
group_name = self._task.args.get('key')
group_name = group_name.replace(' ','-')
return dict(changed=True, add_group=group_name)
| gpl-3.0 |
energicryptocurrency/energi | contrib/devtools/clang-format-diff.py | 142 | 6190 | #!/usr/bin/env python
#
#===- clang-format-diff.py - ClangFormat Diff Reformatter ----*- python -*--===#
#
# The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License.
#
# ============================================================
#
# University of Illinois/NCSA
# Open Source License
#
# Copyright (c) 2007-2015 University of Illinois at Urbana-Champaign.
# All rights reserved.
#
# Developed by:
#
# LLVM Team
#
# University of Illinois at Urbana-Champaign
#
# http://llvm.org
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal with
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimers.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimers in the
# documentation and/or other materials provided with the distribution.
#
# * Neither the names of the LLVM Team, University of Illinois at
# Urbana-Champaign, nor the names of its contributors may be used to
# endorse or promote products derived from this Software without specific
# prior written permission.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
# SOFTWARE.
#
# ============================================================
#
#===------------------------------------------------------------------------===#
r"""
ClangFormat Diff Reformatter
============================
This script reads input from a unified diff and reformats all the changed
lines. This is useful to reformat all the lines touched by a specific patch.
Example usage for git/svn users:
git diff -U0 HEAD^ | clang-format-diff.py -p1 -i
svn diff --diff-cmd=diff -x-U0 | clang-format-diff.py -i
"""
import argparse
import difflib
import re
import string
import subprocess
import StringIO
import sys
# Change this to the full path if clang-format is not on the path.
binary = 'clang-format'
def main():
parser = argparse.ArgumentParser(description=
'Reformat changed lines in diff. Without -i '
'option just output the diff that would be '
'introduced.')
parser.add_argument('-i', action='store_true', default=False,
help='apply edits to files instead of displaying a diff')
parser.add_argument('-p', metavar='NUM', default=0,
help='strip the smallest prefix containing P slashes')
parser.add_argument('-regex', metavar='PATTERN', default=None,
help='custom pattern selecting file paths to reformat '
'(case sensitive, overrides -iregex)')
parser.add_argument('-iregex', metavar='PATTERN', default=
r'.*\.(cpp|cc|c\+\+|cxx|c|cl|h|hpp|m|mm|inc|js|ts|proto'
r'|protodevel|java)',
help='custom pattern selecting file paths to reformat '
'(case insensitive, overridden by -regex)')
parser.add_argument('-sort-includes', action='store_true', default=False,
help='let clang-format sort include blocks')
parser.add_argument('-v', '--verbose', action='store_true',
help='be more verbose, ineffective without -i')
args = parser.parse_args()
# Extract changed lines for each file.
filename = None
lines_by_file = {}
for line in sys.stdin:
match = re.search('^\+\+\+\ (.*?/){%s}(\S*)' % args.p, line)
if match:
filename = match.group(2)
if filename == None:
continue
if args.regex is not None:
if not re.match('^%s$' % args.regex, filename):
continue
else:
if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE):
continue
match = re.search('^@@.*\+(\d+)(,(\d+))?', line)
if match:
start_line = int(match.group(1))
line_count = 1
if match.group(3):
line_count = int(match.group(3))
if line_count == 0:
continue
end_line = start_line + line_count - 1
lines_by_file.setdefault(filename, []).extend(
['-lines', str(start_line) + ':' + str(end_line)])
# Reformat files containing changes in place.
for filename, lines in lines_by_file.iteritems():
if args.i and args.verbose:
print 'Formatting', filename
command = [binary, filename]
if args.i:
command.append('-i')
if args.sort_includes:
command.append('-sort-includes')
command.extend(lines)
command.extend(['-style=file', '-fallback-style=none'])
p = subprocess.Popen(command, stdout=subprocess.PIPE,
stderr=None, stdin=subprocess.PIPE)
stdout, stderr = p.communicate()
if p.returncode != 0:
sys.exit(p.returncode)
if not args.i:
with open(filename) as f:
code = f.readlines()
formatted_code = StringIO.StringIO(stdout).readlines()
diff = difflib.unified_diff(code, formatted_code,
filename, filename,
'(before formatting)', '(after formatting)')
diff_string = string.join(diff, '')
if len(diff_string) > 0:
sys.stdout.write(diff_string)
if __name__ == '__main__':
main()
| mit |
zerobatu/edx-platform | common/lib/xmodule/xmodule/crowdsource_hinter.py | 177 | 17456 | """
Adds crowdsourced hinting functionality to lon-capa numerical response problems.
Currently experimental - not for instructor use, yet.
"""
import logging
import json
import random
import copy
from pkg_resources import resource_string
from lxml import etree
from xmodule.x_module import XModule, STUDENT_VIEW
from xmodule.raw_module import RawDescriptor
from xblock.fields import Scope, String, Integer, Boolean, Dict, List
from capa.responsetypes import FormulaResponse
from django.utils.html import escape
log = logging.getLogger(__name__)
class CrowdsourceHinterFields(object):
"""Defines fields for the crowdsource hinter module."""
has_children = True
moderate = String(help='String "True"/"False" - activates moderation', scope=Scope.content,
default='False')
debug = String(help='String "True"/"False" - allows multiple voting', scope=Scope.content,
default='False')
# Usage: hints[answer] = {str(pk): [hint_text, #votes]}
# hints is a dictionary that takes answer keys.
# Each value is itself a dictionary, accepting hint_pk strings as keys,
# and returning [hint text, #votes] pairs as values
hints = Dict(help='A dictionary containing all the active hints.', scope=Scope.content, default={})
mod_queue = Dict(help='A dictionary containing hints still awaiting approval', scope=Scope.content,
default={})
hint_pk = Integer(help='Used to index hints.', scope=Scope.content, default=0)
# A list of previous hints that a student viewed.
# Of the form [answer, [hint_pk_1, ...]] for each problem.
# Sorry about the variable name - I know it's confusing.
previous_answers = List(help='A list of hints viewed.', scope=Scope.user_state, default=[])
# user_submissions actually contains a list of previous answers submitted.
# (Originally, preivous_answers did this job, hence the name confusion.)
user_submissions = List(help='A list of previous submissions', scope=Scope.user_state, default=[])
user_voted = Boolean(help='Specifies if the user has voted on this problem or not.',
scope=Scope.user_state, default=False)
class CrowdsourceHinterModule(CrowdsourceHinterFields, XModule):
"""
An Xmodule that makes crowdsourced hints.
Currently, only works on capa problems with exactly one numerical response,
and no other parts.
Example usage:
<crowdsource_hinter>
<problem blah blah />
</crowdsource_hinter>
XML attributes:
-moderate="True" will not display hints until staff approve them in the hint manager.
-debug="True" will let users vote as often as they want.
"""
icon_class = 'crowdsource_hinter'
css = {'scss': [resource_string(__name__, 'css/crowdsource_hinter/display.scss')]}
js = {'coffee': [resource_string(__name__, 'js/src/crowdsource_hinter/display.coffee')],
'js': []}
js_module_name = "Hinter"
def __init__(self, *args, **kwargs):
super(CrowdsourceHinterModule, self).__init__(*args, **kwargs)
# We need to know whether we are working with a FormulaResponse problem.
try:
responder = self.get_display_items()[0].lcp.responders.values()[0]
except (IndexError, AttributeError):
log.exception('Unable to find a capa problem child.')
return
self.is_formula = isinstance(self, FormulaResponse)
if self.is_formula:
self.answer_to_str = self.formula_answer_to_str
else:
self.answer_to_str = self.numerical_answer_to_str
# compare_answer is expected to return whether its two inputs are close enough
# to be equal, or raise a StudentInputError if one of the inputs is malformatted.
if hasattr(responder, 'compare_answer') and hasattr(responder, 'validate_answer'):
self.compare_answer = responder.compare_answer
self.validate_answer = responder.validate_answer
else:
# This response type is not supported!
log.exception('Response type not supported for hinting: ' + str(responder))
def get_html(self):
"""
Puts a wrapper around the problem html. This wrapper includes ajax urls of the
hinter and of the problem.
- Dependent on lon-capa problem.
"""
if self.debug == 'True':
# Reset the user vote, for debugging only!
self.user_voted = False
if self.hints == {}:
# Force self.hints to be written into the database. (When an xmodule is initialized,
# fields are not added to the db until explicitly changed at least once.)
self.hints = {}
try:
child = self.get_display_items()[0]
out = child.render(STUDENT_VIEW).content
# The event listener uses the ajax url to find the child.
child_id = child.id
except IndexError:
out = u"Error in loading crowdsourced hinter - can't find child problem."
child_id = ''
# Wrap the module in a <section>. This lets us pass data attributes to the javascript.
out += u'<section class="crowdsource-wrapper" data-url="{ajax_url}" data-child-id="{child_id}"> </section>'.format(
ajax_url=self.runtime.ajax_url,
child_id=child_id
)
return out
def numerical_answer_to_str(self, answer):
"""
Converts capa numerical answer format to a string representation
of the answer.
-Lon-capa dependent.
-Assumes that the problem only has one part.
"""
return str(answer.values()[0])
def formula_answer_to_str(self, answer):
"""
Converts capa formula answer into a string.
-Lon-capa dependent.
-Assumes that the problem only has one part.
"""
return str(answer.values()[0])
def get_matching_answers(self, answer):
"""
Look in self.hints, and find all answer keys that are "equal with tolerance"
to the input answer.
"""
return [key for key in self.hints if self.compare_answer(key, answer)]
def handle_ajax(self, dispatch, data):
"""
This is the landing method for AJAX calls.
"""
if dispatch == 'get_hint':
out = self.get_hint(data)
elif dispatch == 'get_feedback':
out = self.get_feedback(data)
elif dispatch == 'vote':
out = self.tally_vote(data)
elif dispatch == 'submit_hint':
out = self.submit_hint(data)
else:
return json.dumps({'contents': 'Error - invalid operation.'})
if out is None:
out = {'op': 'empty'}
elif 'error' in out:
# Error in processing.
out.update({'op': 'error'})
else:
out.update({'op': dispatch})
return json.dumps({'contents': self.runtime.render_template('hinter_display.html', out)})
def get_hint(self, data):
"""
The student got the incorrect answer found in data. Give him a hint.
Called by hinter javascript after a problem is graded as incorrect.
Args:
`data` -- must be interpretable by answer_to_str.
Output keys:
- 'hints' is a list of hint strings to show to the user.
- 'answer' is the parsed answer that was submitted.
Will record the user's wrong answer in user_submissions, and the hints shown
in previous_answers.
"""
# First, validate our inputs.
try:
answer = self.answer_to_str(data)
except (ValueError, AttributeError):
# Sometimes, we get an answer that's just not parsable. Do nothing.
log.exception('Answer not parsable: ' + str(data))
return
if not self.validate_answer(answer):
# Answer is not in the right form.
log.exception('Answer not valid: ' + str(answer))
return
if answer not in self.user_submissions:
self.user_submissions += [answer]
# For all answers similar enough to our own, accumulate all hints together.
# Also track the original answer of each hint.
matching_answers = self.get_matching_answers(answer)
matching_hints = {}
for matching_answer in matching_answers:
temp_dict = copy.deepcopy(self.hints[matching_answer])
for key, value in temp_dict.items():
# Each value now has hint, votes, matching_answer.
temp_dict[key] = value + [matching_answer]
matching_hints.update(temp_dict)
# matching_hints now maps pk's to lists of [hint, votes, matching_answer]
# Finally, randomly choose a subset of matching_hints to actually show.
if not matching_hints:
# No hints to give. Return.
return
# Get the top hint, plus two random hints.
n_hints = len(matching_hints)
hints = []
# max(dict) returns the maximum key in dict.
# The key function takes each pk, and returns the number of votes for the
# hint with that pk.
best_hint_index = max(matching_hints, key=lambda pk: matching_hints[pk][1])
hints.append(matching_hints[best_hint_index][0])
best_hint_answer = matching_hints[best_hint_index][2]
# The brackets surrounding the index are for backwards compatability purposes.
# (It used to be that each answer was paired with multiple hints in a list.)
self.previous_answers += [[best_hint_answer, [best_hint_index]]]
for _ in xrange(min(2, n_hints - 1)):
# Keep making random hints until we hit a target, or run out.
while True:
# random.choice randomly chooses an element from its input list.
# (We then unpack the item, in this case data for a hint.)
(hint_index, (rand_hint, _, hint_answer)) =\
random.choice(matching_hints.items())
if rand_hint not in hints:
break
hints.append(rand_hint)
self.previous_answers += [[hint_answer, [hint_index]]]
return {'hints': hints,
'answer': answer}
def get_feedback(self, data):
"""
The student got it correct. Ask him to vote on hints, or submit a hint.
Args:
`data` -- not actually used. (It is assumed that the answer is correct.)
Output keys:
- 'answer_to_hints': a nested dictionary.
answer_to_hints[answer][hint_pk] returns the text of the hint.
- 'user_submissions': the same thing as self.user_submissions. A list of
the answers that the user previously submitted.
"""
# The student got it right.
# Did he submit at least one wrong answer?
if len(self.user_submissions) == 0:
# No. Nothing to do here.
return
# Make a hint-voting interface for each wrong answer. The student will only
# be allowed to make one vote / submission, but he can choose which wrong answer
# he wants to look at.
answer_to_hints = {} # answer_to_hints[answer text][hint pk] -> hint text
# Go through each previous answer, and populate index_to_hints and index_to_answer.
for i in xrange(len(self.previous_answers)):
answer, hints_offered = self.previous_answers[i]
if answer not in answer_to_hints:
answer_to_hints[answer] = {}
if answer in self.hints:
# Go through each hint, and add to index_to_hints
for hint_id in hints_offered:
if (hint_id is not None) and (hint_id not in answer_to_hints[answer]):
try:
answer_to_hints[answer][hint_id] = self.hints[answer][str(hint_id)][0]
except KeyError:
# Sometimes, the hint that a user saw will have been deleted by the instructor.
continue
return {'answer_to_hints': answer_to_hints,
'user_submissions': self.user_submissions}
def tally_vote(self, data):
"""
Tally a user's vote on his favorite hint.
Args:
`data` -- expected to have the following keys:
'answer': text of answer we're voting on
'hint': hint_pk
'pk_list': A list of [answer, pk] pairs, each of which representing a hint.
We will return a list of how many votes each hint in the list has so far.
It's up to the browser to specify which hints to return vote counts for.
Returns key 'hint_and_votes', a list of (hint_text, #votes) pairs.
"""
if self.user_voted:
return {'error': 'Sorry, but you have already voted!'}
ans = data['answer']
if not self.validate_answer(ans):
# Uh oh. Invalid answer.
log.exception('Failure in hinter tally_vote: Unable to parse answer: {ans}'.format(ans=ans))
return {'error': 'Failure in voting!'}
hint_pk = str(data['hint'])
# We use temp_dict because we need to do a direct write for the database to update.
temp_dict = self.hints
try:
temp_dict[ans][hint_pk][1] += 1
except KeyError:
log.exception('''Failure in hinter tally_vote: User voted for non-existant hint:
Answer={ans} pk={hint_pk}'''.format(ans=ans, hint_pk=hint_pk))
return {'error': 'Failure in voting!'}
self.hints = temp_dict
# Don't let the user vote again!
self.user_voted = True
# Return a list of how many votes each hint got.
pk_list = json.loads(data['pk_list'])
hint_and_votes = []
for answer, vote_pk in pk_list:
if not self.validate_answer(answer):
log.exception('In hinter tally_vote, couldn\'t parse {ans}'.format(ans=answer))
continue
try:
hint_and_votes.append(temp_dict[answer][str(vote_pk)])
except KeyError:
log.exception('In hinter tally_vote, couldn\'t find: {ans}, {vote_pk}'.format(
ans=answer, vote_pk=str(vote_pk)))
hint_and_votes.sort(key=lambda pair: pair[1], reverse=True)
# Reset self.previous_answers and user_submissions.
self.previous_answers = []
self.user_submissions = []
return {'hint_and_votes': hint_and_votes}
def submit_hint(self, data):
"""
Take a hint submission and add it to the database.
Args:
`data` -- expected to have the following keys:
'answer': text of answer
'hint': text of the new hint that the user is adding
Returns a thank-you message.
"""
# Do html escaping. Perhaps in the future do profanity filtering, etc. as well.
hint = escape(data['hint'])
answer = data['answer']
if not self.validate_answer(answer):
log.exception('Failure in hinter submit_hint: Unable to parse answer: {ans}'.format(
ans=answer))
return {'error': 'Could not submit answer'}
# Only allow a student to vote or submit a hint once.
if self.user_voted:
return {'message': 'Sorry, but you have already voted!'}
# Add the new hint to self.hints or self.mod_queue. (Awkward because a direct write
# is necessary.)
if self.moderate == 'True':
temp_dict = self.mod_queue
else:
temp_dict = self.hints
if answer in temp_dict:
temp_dict[answer][str(self.hint_pk)] = [hint, 1] # With one vote (the user himself).
else:
temp_dict[answer] = {str(self.hint_pk): [hint, 1]}
self.hint_pk += 1
if self.moderate == 'True':
self.mod_queue = temp_dict
else:
self.hints = temp_dict
# Mark the user has having voted; reset previous_answers
self.user_voted = True
self.previous_answers = []
self.user_submissions = []
return {'message': 'Thank you for your hint!'}
class CrowdsourceHinterDescriptor(CrowdsourceHinterFields, RawDescriptor):
module_class = CrowdsourceHinterModule
stores_state = True
@classmethod
def definition_from_xml(cls, xml_object, system):
children = []
for child in xml_object:
try:
child_block = system.process_xml(etree.tostring(child, encoding='unicode'))
children.append(child_block.scope_ids.usage_id)
except Exception as e:
log.exception("Unable to load child when parsing CrowdsourceHinter. Continuing...")
if system.error_tracker is not None:
system.error_tracker(u"ERROR: {0}".format(e))
continue
return {}, children
def definition_to_xml(self, resource_fs):
xml_object = etree.Element('crowdsource_hinter')
for child in self.get_children():
self.runtime.add_block_as_child_node(child, xml_object)
return xml_object
| agpl-3.0 |
Asalle/coala | tests/settings/SettingTest.py | 1 | 5508 | import os
import re
import unittest
from collections import OrderedDict
from coalib.bearlib.languages import Language
from coalib.settings.Setting import (
Setting, path, path_list, url, typed_dict, typed_list, typed_ordered_dict,
glob, glob_list,
language,
)
from coalib.parsing.Globbing import glob_escape
class SettingTest(unittest.TestCase):
def test_constructor_signature(self):
self.assertRaises(TypeError, Setting, '', 2, 2)
self.assertRaises(TypeError, Setting, '', '', '', from_cli=5)
self.assertRaisesRegex(TypeError, 'to_append',
Setting, '', '', '', to_append=10)
self.assertRaises(TypeError, Setting, 'a', 'b', list_delimiters=5)
self.assertRaises(TypeError, Setting, 'a', 'b', list_delimiters=None)
def test_empty_key(self):
with self.assertRaisesRegex(
ValueError, 'An empty key is not allowed for a setting'):
Setting('', 2)
def test_path(self):
self.uut = Setting(
'key', ' 22\n', '.' + os.path.sep, strip_whitespaces=True)
self.assertEqual(path(self.uut),
os.path.abspath(os.path.join('.', '22')))
abspath = os.path.abspath('.')
self.uut = Setting('key', re.escape(abspath))
self.assertEqual(path(self.uut), abspath)
self.uut = Setting('key', ' 22', '')
self.assertRaises(ValueError, path, self.uut)
self.assertEqual(path(self.uut,
origin='test' + os.path.sep),
os.path.abspath(os.path.join('test', '22')))
def test_glob(self):
self.uut = Setting('key', '.',
origin=os.path.join('test (1)', 'somefile'))
self.assertEqual(glob(self.uut),
glob_escape(os.path.abspath('test (1)')))
def test_path_list(self):
abspath = os.path.abspath('.')
# Need to escape backslashes since we use list conversion
self.uut = Setting('key', '., ' + abspath.replace('\\', '\\\\'),
origin=os.path.join('test', 'somefile'))
self.assertEqual(path_list(self.uut),
[os.path.abspath(os.path.join('test', '.')), abspath])
def test_url(self):
uut = Setting('key', 'http://google.com')
self.assertEqual(url(uut), 'http://google.com')
with self.assertRaises(ValueError):
uut = Setting('key', 'abc')
url(uut)
def test_glob_list(self):
abspath = glob_escape(os.path.abspath('.'))
# Need to escape backslashes since we use list conversion
self.uut = Setting('key', '., ' + abspath.replace('\\', '\\\\'),
origin=os.path.join('test (1)', 'somefile'))
self.assertEqual(
glob_list(self.uut),
[glob_escape(os.path.abspath(os.path.join('test (1)', '.'))),
abspath])
def test_language(self):
self.uut = Setting('key', 'python 3.4')
result = language(self.uut)
self.assertIsInstance(result, Language)
self.assertEqual(str(result), 'Python 3.4')
def test_language_invalid(self):
self.uut = Setting('key', 'not a language')
with self.assertRaisesRegexp(
ValueError,
'Language `not a language` is not a valid language name or '
'not recognized by coala.'):
language(self.uut)
def test_typed_list(self):
self.uut = Setting('key', '1, 2, 3')
self.assertEqual(typed_list(int)(self.uut),
[1, 2, 3])
with self.assertRaises(ValueError):
self.uut = Setting('key', '1, a, 3')
typed_list(int)(self.uut)
self.assertEqual(repr(typed_list(int)), 'typed_list(int)')
def test_typed_dict(self):
self.uut = Setting('key', '1, 2: t, 3')
self.assertEqual(typed_dict(int, str, None)(self.uut),
{1: None, 2: 't', 3: None})
with self.assertRaises(ValueError):
self.uut = Setting('key', '1, a, 3')
typed_dict(int, str, '')(self.uut)
self.assertEqual(repr(typed_dict(int, str, None)),
'typed_dict(int, str, default=None)')
def test_typed_ordered_dict(self):
self.uut = Setting('key', '1, 2: t, 3')
self.assertEqual(typed_ordered_dict(int, str, None)(self.uut),
OrderedDict([(1, None), (2, 't'), (3, None)]))
with self.assertRaises(ValueError):
self.uut = Setting('key', '1, a, 3')
typed_ordered_dict(int, str, '')(self.uut)
self.assertEqual(repr(typed_ordered_dict(int, str, None)),
'typed_ordered_dict(int, str, default=None)')
def test_inherited_conversions(self):
self.uut = Setting('key', ' 22\n', '.', strip_whitespaces=True)
self.assertEqual(str(self.uut), '22')
self.assertEqual(int(self.uut), 22)
self.assertRaises(ValueError, bool, self.uut)
def test_value_getter(self):
with self.assertRaisesRegex(ValueError, 'This property is invalid'):
self.uut = Setting('key', '22\n', '.', to_append=True)
self.uut.value
with self.assertRaisesRegex(ValueError,
'Iteration on this object is invalid'):
self.uut = Setting('key', '1, 2, 3', '.', to_append=True)
list(self.uut)
| agpl-3.0 |
joequery/django | django/views/debug.py | 18 | 46801 | from __future__ import unicode_literals
import re
import sys
import types
from django.conf import settings
from django.core.urlresolvers import Resolver404, resolve
from django.http import HttpResponse, HttpResponseNotFound
from django.template import Context, Engine, TemplateDoesNotExist
from django.template.defaultfilters import force_escape, pprint
from django.utils import lru_cache, six, timezone
from django.utils.datastructures import MultiValueDict
from django.utils.encoding import force_bytes, smart_text
from django.utils.module_loading import import_string
from django.utils.translation import ugettext as _
# Minimal Django templates engine to render the error templates
# regardless of the project's TEMPLATES setting.
DEBUG_ENGINE = Engine(debug=True)
HIDDEN_SETTINGS = re.compile('API|TOKEN|KEY|SECRET|PASS|SIGNATURE')
CLEANSED_SUBSTITUTE = '********************'
def linebreak_iter(template_source):
yield 0
p = template_source.find('\n')
while p >= 0:
yield p + 1
p = template_source.find('\n', p + 1)
yield len(template_source) + 1
class CallableSettingWrapper(object):
""" Object to wrap callable appearing in settings
* Not to call in the debug page (#21345).
* Not to break the debug page if the callable forbidding to set attributes (#23070).
"""
def __init__(self, callable_setting):
self._wrapped = callable_setting
def __repr__(self):
return repr(self._wrapped)
def cleanse_setting(key, value):
"""Cleanse an individual setting key/value of sensitive content.
If the value is a dictionary, recursively cleanse the keys in
that dictionary.
"""
try:
if HIDDEN_SETTINGS.search(key):
cleansed = CLEANSED_SUBSTITUTE
else:
if isinstance(value, dict):
cleansed = {k: cleanse_setting(k, v) for k, v in value.items()}
else:
cleansed = value
except TypeError:
# If the key isn't regex-able, just return as-is.
cleansed = value
if callable(cleansed):
# For fixing #21345 and #23070
cleansed = CallableSettingWrapper(cleansed)
return cleansed
def get_safe_settings():
"Returns a dictionary of the settings module, with sensitive settings blurred out."
settings_dict = {}
for k in dir(settings):
if k.isupper():
settings_dict[k] = cleanse_setting(k, getattr(settings, k))
return settings_dict
def technical_500_response(request, exc_type, exc_value, tb, status_code=500):
"""
Create a technical server error response. The last three arguments are
the values returned from sys.exc_info() and friends.
"""
reporter = ExceptionReporter(request, exc_type, exc_value, tb)
if request.is_ajax():
text = reporter.get_traceback_text()
return HttpResponse(text, status=status_code, content_type='text/plain')
else:
html = reporter.get_traceback_html()
return HttpResponse(html, status=status_code, content_type='text/html')
@lru_cache.lru_cache()
def get_default_exception_reporter_filter():
# Instantiate the default filter for the first time and cache it.
return import_string(settings.DEFAULT_EXCEPTION_REPORTER_FILTER)()
def get_exception_reporter_filter(request):
default_filter = get_default_exception_reporter_filter()
return getattr(request, 'exception_reporter_filter', default_filter)
class ExceptionReporterFilter(object):
"""
Base for all exception reporter filter classes. All overridable hooks
contain lenient default behaviors.
"""
def get_post_parameters(self, request):
if request is None:
return {}
else:
return request.POST
def get_traceback_frame_variables(self, request, tb_frame):
return list(tb_frame.f_locals.items())
class SafeExceptionReporterFilter(ExceptionReporterFilter):
"""
Use annotations made by the sensitive_post_parameters and
sensitive_variables decorators to filter out sensitive information.
"""
def is_active(self, request):
"""
This filter is to add safety in production environments (i.e. DEBUG
is False). If DEBUG is True then your site is not safe anyway.
This hook is provided as a convenience to easily activate or
deactivate the filter on a per request basis.
"""
return settings.DEBUG is False
def get_cleansed_multivaluedict(self, request, multivaluedict):
"""
Replaces the keys in a MultiValueDict marked as sensitive with stars.
This mitigates leaking sensitive POST parameters if something like
request.POST['nonexistent_key'] throws an exception (#21098).
"""
sensitive_post_parameters = getattr(request, 'sensitive_post_parameters', [])
if self.is_active(request) and sensitive_post_parameters:
multivaluedict = multivaluedict.copy()
for param in sensitive_post_parameters:
if param in multivaluedict:
multivaluedict[param] = CLEANSED_SUBSTITUTE
return multivaluedict
def get_post_parameters(self, request):
"""
Replaces the values of POST parameters marked as sensitive with
stars (*********).
"""
if request is None:
return {}
else:
sensitive_post_parameters = getattr(request, 'sensitive_post_parameters', [])
if self.is_active(request) and sensitive_post_parameters:
cleansed = request.POST.copy()
if sensitive_post_parameters == '__ALL__':
# Cleanse all parameters.
for k, v in cleansed.items():
cleansed[k] = CLEANSED_SUBSTITUTE
return cleansed
else:
# Cleanse only the specified parameters.
for param in sensitive_post_parameters:
if param in cleansed:
cleansed[param] = CLEANSED_SUBSTITUTE
return cleansed
else:
return request.POST
def cleanse_special_types(self, request, value):
try:
# If value is lazy or a complex object of another kind, this check
# might raise an exception. isinstance checks that lazy
# MultiValueDicts will have a return value.
is_multivalue_dict = isinstance(value, MultiValueDict)
except Exception as e:
return '{!r} while evaluating {!r}'.format(e, value)
if is_multivalue_dict:
# Cleanse MultiValueDicts (request.POST is the one we usually care about)
value = self.get_cleansed_multivaluedict(request, value)
return value
def get_traceback_frame_variables(self, request, tb_frame):
"""
Replaces the values of variables marked as sensitive with
stars (*********).
"""
# Loop through the frame's callers to see if the sensitive_variables
# decorator was used.
current_frame = tb_frame.f_back
sensitive_variables = None
while current_frame is not None:
if (current_frame.f_code.co_name == 'sensitive_variables_wrapper'
and 'sensitive_variables_wrapper' in current_frame.f_locals):
# The sensitive_variables decorator was used, so we take note
# of the sensitive variables' names.
wrapper = current_frame.f_locals['sensitive_variables_wrapper']
sensitive_variables = getattr(wrapper, 'sensitive_variables', None)
break
current_frame = current_frame.f_back
cleansed = {}
if self.is_active(request) and sensitive_variables:
if sensitive_variables == '__ALL__':
# Cleanse all variables
for name, value in tb_frame.f_locals.items():
cleansed[name] = CLEANSED_SUBSTITUTE
else:
# Cleanse specified variables
for name, value in tb_frame.f_locals.items():
if name in sensitive_variables:
value = CLEANSED_SUBSTITUTE
else:
value = self.cleanse_special_types(request, value)
cleansed[name] = value
else:
# Potentially cleanse the request and any MultiValueDicts if they
# are one of the frame variables.
for name, value in tb_frame.f_locals.items():
cleansed[name] = self.cleanse_special_types(request, value)
if (tb_frame.f_code.co_name == 'sensitive_variables_wrapper'
and 'sensitive_variables_wrapper' in tb_frame.f_locals):
# For good measure, obfuscate the decorated function's arguments in
# the sensitive_variables decorator's frame, in case the variables
# associated with those arguments were meant to be obfuscated from
# the decorated function's frame.
cleansed['func_args'] = CLEANSED_SUBSTITUTE
cleansed['func_kwargs'] = CLEANSED_SUBSTITUTE
return cleansed.items()
class ExceptionReporter(object):
"""
A class to organize and coordinate reporting on exceptions.
"""
def __init__(self, request, exc_type, exc_value, tb, is_email=False):
self.request = request
self.filter = get_exception_reporter_filter(self.request)
self.exc_type = exc_type
self.exc_value = exc_value
self.tb = tb
self.is_email = is_email
self.template_info = getattr(self.exc_value, 'template_debug', None)
self.template_does_not_exist = False
self.postmortem = None
# Handle deprecated string exceptions
if isinstance(self.exc_type, six.string_types):
self.exc_value = Exception('Deprecated String Exception: %r' % self.exc_type)
self.exc_type = type(self.exc_value)
def get_traceback_data(self):
"""Return a dictionary containing traceback information."""
if self.exc_type and issubclass(self.exc_type, TemplateDoesNotExist):
self.template_does_not_exist = True
self.postmortem = self.exc_value.chain or [self.exc_value]
frames = self.get_traceback_frames()
for i, frame in enumerate(frames):
if 'vars' in frame:
frame_vars = []
for k, v in frame['vars']:
v = pprint(v)
# The force_escape filter assume unicode, make sure that works
if isinstance(v, six.binary_type):
v = v.decode('utf-8', 'replace') # don't choke on non-utf-8 input
# Trim large blobs of data
if len(v) > 4096:
v = '%s... <trimmed %d bytes string>' % (v[0:4096], len(v))
frame_vars.append((k, force_escape(v)))
frame['vars'] = frame_vars
frames[i] = frame
unicode_hint = ''
if self.exc_type and issubclass(self.exc_type, UnicodeError):
start = getattr(self.exc_value, 'start', None)
end = getattr(self.exc_value, 'end', None)
if start is not None and end is not None:
unicode_str = self.exc_value.args[1]
unicode_hint = smart_text(
unicode_str[max(start - 5, 0):min(end + 5, len(unicode_str))],
'ascii', errors='replace'
)
from django import get_version
c = {
'is_email': self.is_email,
'unicode_hint': unicode_hint,
'frames': frames,
'request': self.request,
'filtered_POST': self.filter.get_post_parameters(self.request),
'settings': get_safe_settings(),
'sys_executable': sys.executable,
'sys_version_info': '%d.%d.%d' % sys.version_info[0:3],
'server_time': timezone.now(),
'django_version_info': get_version(),
'sys_path': sys.path,
'template_info': self.template_info,
'template_does_not_exist': self.template_does_not_exist,
'postmortem': self.postmortem,
}
# Check whether exception info is available
if self.exc_type:
c['exception_type'] = self.exc_type.__name__
if self.exc_value:
c['exception_value'] = smart_text(self.exc_value, errors='replace')
if frames:
c['lastframe'] = frames[-1]
return c
def get_traceback_html(self):
"Return HTML version of debug 500 HTTP error page."
t = DEBUG_ENGINE.from_string(TECHNICAL_500_TEMPLATE)
c = Context(self.get_traceback_data(), use_l10n=False)
return t.render(c)
def get_traceback_text(self):
"Return plain text version of debug 500 HTTP error page."
t = DEBUG_ENGINE.from_string(TECHNICAL_500_TEXT_TEMPLATE)
c = Context(self.get_traceback_data(), autoescape=False, use_l10n=False)
return t.render(c)
def _get_lines_from_file(self, filename, lineno, context_lines, loader=None, module_name=None):
"""
Returns context_lines before and after lineno from file.
Returns (pre_context_lineno, pre_context, context_line, post_context).
"""
source = None
if loader is not None and hasattr(loader, "get_source"):
try:
source = loader.get_source(module_name)
except ImportError:
pass
if source is not None:
source = source.splitlines()
if source is None:
try:
with open(filename, 'rb') as fp:
source = fp.read().splitlines()
except (OSError, IOError):
pass
if source is None:
return None, [], None, []
# If we just read the source from a file, or if the loader did not
# apply tokenize.detect_encoding to decode the source into a Unicode
# string, then we should do that ourselves.
if isinstance(source[0], six.binary_type):
encoding = 'ascii'
for line in source[:2]:
# File coding may be specified. Match pattern from PEP-263
# (http://www.python.org/dev/peps/pep-0263/)
match = re.search(br'coding[:=]\s*([-\w.]+)', line)
if match:
encoding = match.group(1).decode('ascii')
break
source = [six.text_type(sline, encoding, 'replace') for sline in source]
lower_bound = max(0, lineno - context_lines)
upper_bound = lineno + context_lines
pre_context = source[lower_bound:lineno]
context_line = source[lineno]
post_context = source[lineno + 1:upper_bound]
return lower_bound, pre_context, context_line, post_context
def get_traceback_frames(self):
def explicit_or_implicit_cause(exc_value):
explicit = getattr(exc_value, '__cause__', None)
implicit = getattr(exc_value, '__context__', None)
return explicit or implicit
# Get the exception and all its causes
exceptions = []
exc_value = self.exc_value
while exc_value:
exceptions.append(exc_value)
exc_value = explicit_or_implicit_cause(exc_value)
frames = []
# No exceptions were supplied to ExceptionReporter
if not exceptions:
return frames
# In case there's just one exception (always in Python 2,
# sometimes in Python 3), take the traceback from self.tb (Python 2
# doesn't have a __traceback__ attribute on Exception)
exc_value = exceptions.pop()
tb = self.tb if six.PY2 or not exceptions else exc_value.__traceback__
while tb is not None:
# Support for __traceback_hide__ which is used by a few libraries
# to hide internal frames.
if tb.tb_frame.f_locals.get('__traceback_hide__'):
tb = tb.tb_next
continue
filename = tb.tb_frame.f_code.co_filename
function = tb.tb_frame.f_code.co_name
lineno = tb.tb_lineno - 1
loader = tb.tb_frame.f_globals.get('__loader__')
module_name = tb.tb_frame.f_globals.get('__name__') or ''
pre_context_lineno, pre_context, context_line, post_context = self._get_lines_from_file(
filename, lineno, 7, loader, module_name,
)
if pre_context_lineno is not None:
frames.append({
'exc_cause': explicit_or_implicit_cause(exc_value),
'exc_cause_explicit': getattr(exc_value, '__cause__', True),
'tb': tb,
'type': 'django' if module_name.startswith('django.') else 'user',
'filename': filename,
'function': function,
'lineno': lineno + 1,
'vars': self.filter.get_traceback_frame_variables(self.request, tb.tb_frame),
'id': id(tb),
'pre_context': pre_context,
'context_line': context_line,
'post_context': post_context,
'pre_context_lineno': pre_context_lineno + 1,
})
# If the traceback for current exception is consumed, try the
# other exception.
if six.PY2:
tb = tb.tb_next
elif not tb.tb_next and exceptions:
exc_value = exceptions.pop()
tb = exc_value.__traceback__
else:
tb = tb.tb_next
return frames
def format_exception(self):
"""
Return the same data as from traceback.format_exception.
"""
import traceback
frames = self.get_traceback_frames()
tb = [(f['filename'], f['lineno'], f['function'], f['context_line']) for f in frames]
list = ['Traceback (most recent call last):\n']
list += traceback.format_list(tb)
list += traceback.format_exception_only(self.exc_type, self.exc_value)
return list
def technical_404_response(request, exception):
"Create a technical 404 error response. The exception should be the Http404."
try:
error_url = exception.args[0]['path']
except (IndexError, TypeError, KeyError):
error_url = request.path_info[1:] # Trim leading slash
try:
tried = exception.args[0]['tried']
except (IndexError, TypeError, KeyError):
tried = []
else:
if (not tried # empty URLconf
or (request.path == '/'
and len(tried) == 1 # default URLconf
and len(tried[0]) == 1
and getattr(tried[0][0], 'app_name', '') == getattr(tried[0][0], 'namespace', '') == 'admin')):
return default_urlconf(request)
urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
if isinstance(urlconf, types.ModuleType):
urlconf = urlconf.__name__
caller = ''
try:
resolver_match = resolve(request.path)
except Resolver404:
pass
else:
obj = resolver_match.func
if hasattr(obj, '__name__'):
caller = obj.__name__
elif hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'):
caller = obj.__class__.__name__
if hasattr(obj, '__module__'):
module = obj.__module__
caller = '%s.%s' % (module, caller)
t = DEBUG_ENGINE.from_string(TECHNICAL_404_TEMPLATE)
c = Context({
'urlconf': urlconf,
'root_urlconf': settings.ROOT_URLCONF,
'request_path': error_url,
'urlpatterns': tried,
'reason': force_bytes(exception, errors='replace'),
'request': request,
'settings': get_safe_settings(),
'raising_view_name': caller,
})
return HttpResponseNotFound(t.render(c), content_type='text/html')
def default_urlconf(request):
"Create an empty URLconf 404 error response."
t = DEBUG_ENGINE.from_string(DEFAULT_URLCONF_TEMPLATE)
c = Context({
"title": _("Welcome to Django"),
"heading": _("It worked!"),
"subheading": _("Congratulations on your first Django-powered page."),
"instructions": _("Of course, you haven't actually done any work yet. "
"Next, start your first app by running <code>python manage.py startapp [app_label]</code>."),
"explanation": _("You're seeing this message because you have <code>DEBUG = True</code> in your "
"Django settings file and you haven't configured any URLs. Get to work!"),
})
return HttpResponse(t.render(c), content_type='text/html')
#
# Templates are embedded in the file so that we know the error handler will
# always work even if the template loader is broken.
#
TECHNICAL_500_TEMPLATE = ("""
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="robots" content="NONE,NOARCHIVE">
<title>{% if exception_type %}{{ exception_type }}{% else %}Report{% endif %}"""
"""{% if request %} at {{ request.path_info|escape }}{% endif %}</title>
<style type="text/css">
html * { padding:0; margin:0; }
body * { padding:10px 20px; }
body * * { padding:0; }
body { font:small sans-serif; }
body>div { border-bottom:1px solid #ddd; }
h1 { font-weight:normal; }
h2 { margin-bottom:.8em; }
h2 span { font-size:80%; color:#666; font-weight:normal; }
h3 { margin:1em 0 .5em 0; }
h4 { margin:0 0 .5em 0; font-weight: normal; }
code, pre { font-size: 100%; white-space: pre-wrap; }
table { border:1px solid #ccc; border-collapse: collapse; width:100%; background:white; }
tbody td, tbody th { vertical-align:top; padding:2px 3px; }
thead th {
padding:1px 6px 1px 3px; background:#fefefe; text-align:left;
font-weight:normal; font-size:11px; border:1px solid #ddd;
}
tbody th { width:12em; text-align:right; color:#666; padding-right:.5em; }
table.vars { margin:5px 0 2px 40px; }
table.vars td, table.req td { font-family:monospace; }
table td.code { width:100%; }
table td.code pre { overflow:hidden; }
table.source th { color:#666; }
table.source td { font-family:monospace; white-space:pre; border-bottom:1px solid #eee; }
ul.traceback { list-style-type:none; color: #222; }
ul.traceback li.frame { padding-bottom:1em; color:#666; }
ul.traceback li.user { background-color:#e0e0e0; color:#000 }
div.context { padding:10px 0; overflow:hidden; }
div.context ol { padding-left:30px; margin:0 10px; list-style-position: inside; }
div.context ol li { font-family:monospace; white-space:pre; color:#777; cursor:pointer; padding-left: 2px; }
div.context ol li pre { display:inline; }
div.context ol.context-line li { color:#505050; background-color:#dfdfdf; padding: 3px 2px; }
div.context ol.context-line li span { position:absolute; right:32px; }
.user div.context ol.context-line li { background-color:#bbb; color:#000; }
.user div.context ol li { color:#666; }
div.commands { margin-left: 40px; }
div.commands a { color:#555; text-decoration:none; }
.user div.commands a { color: black; }
#summary { background: #ffc; }
#summary h2 { font-weight: normal; color: #666; }
#explanation { background:#eee; }
#template, #template-not-exist { background:#f6f6f6; }
#template-not-exist ul { margin: 0 0 10px 20px; }
#template-not-exist .postmortem-section { margin-bottom: 3px; }
#unicode-hint { background:#eee; }
#traceback { background:#eee; }
#requestinfo { background:#f6f6f6; padding-left:120px; }
#summary table { border:none; background:transparent; }
#requestinfo h2, #requestinfo h3 { position:relative; margin-left:-100px; }
#requestinfo h3 { margin-bottom:-1em; }
.error { background: #ffc; }
.specific { color:#cc3300; font-weight:bold; }
h2 span.commands { font-size:.7em;}
span.commands a:link {color:#5E5694;}
pre.exception_value { font-family: sans-serif; color: #666; font-size: 1.5em; margin: 10px 0 10px 0; }
.append-bottom { margin-bottom: 10px; }
</style>
{% if not is_email %}
<script type="text/javascript">
//<!--
function getElementsByClassName(oElm, strTagName, strClassName){
// Written by Jonathan Snook, http://www.snook.ca/jon; Add-ons by Robert Nyman, http://www.robertnyman.com
var arrElements = (strTagName == "*" && document.all)? document.all :
oElm.getElementsByTagName(strTagName);
var arrReturnElements = new Array();
strClassName = strClassName.replace(/\-/g, "\\-");
var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
var oElement;
for(var i=0; i<arrElements.length; i++){
oElement = arrElements[i];
if(oRegExp.test(oElement.className)){
arrReturnElements.push(oElement);
}
}
return (arrReturnElements)
}
function hideAll(elems) {
for (var e = 0; e < elems.length; e++) {
elems[e].style.display = 'none';
}
}
window.onload = function() {
hideAll(getElementsByClassName(document, 'table', 'vars'));
hideAll(getElementsByClassName(document, 'ol', 'pre-context'));
hideAll(getElementsByClassName(document, 'ol', 'post-context'));
hideAll(getElementsByClassName(document, 'div', 'pastebin'));
}
function toggle() {
for (var i = 0; i < arguments.length; i++) {
var e = document.getElementById(arguments[i]);
if (e) {
e.style.display = e.style.display == 'none' ? 'block': 'none';
}
}
return false;
}
function varToggle(link, id) {
toggle('v' + id);
var s = link.getElementsByTagName('span')[0];
var uarr = String.fromCharCode(0x25b6);
var darr = String.fromCharCode(0x25bc);
s.innerHTML = s.innerHTML == uarr ? darr : uarr;
return false;
}
function switchPastebinFriendly(link) {
s1 = "Switch to copy-and-paste view";
s2 = "Switch back to interactive view";
link.innerHTML = link.innerHTML.trim() == s1 ? s2: s1;
toggle('browserTraceback', 'pastebinTraceback');
return false;
}
//-->
</script>
{% endif %}
</head>
<body>
<div id="summary">
<h1>{% if exception_type %}{{ exception_type }}{% else %}Report{% endif %}"""
"""{% if request %} at {{ request.path_info|escape }}{% endif %}</h1>
<pre class="exception_value">"""
"""{% if exception_value %}{{ exception_value|force_escape }}{% else %}No exception message supplied{% endif %}"""
"""</pre>
<table class="meta">
{% if request %}
<tr>
<th>Request Method:</th>
<td>{{ request.META.REQUEST_METHOD }}</td>
</tr>
<tr>
<th>Request URL:</th>
<td>{{ request.get_raw_uri|escape }}</td>
</tr>
{% endif %}
<tr>
<th>Django Version:</th>
<td>{{ django_version_info }}</td>
</tr>
{% if exception_type %}
<tr>
<th>Exception Type:</th>
<td>{{ exception_type }}</td>
</tr>
{% endif %}
{% if exception_type and exception_value %}
<tr>
<th>Exception Value:</th>
<td><pre>{{ exception_value|force_escape }}</pre></td>
</tr>
{% endif %}
{% if lastframe %}
<tr>
<th>Exception Location:</th>
<td>{{ lastframe.filename|escape }} in {{ lastframe.function|escape }}, line {{ lastframe.lineno }}</td>
</tr>
{% endif %}
<tr>
<th>Python Executable:</th>
<td>{{ sys_executable|escape }}</td>
</tr>
<tr>
<th>Python Version:</th>
<td>{{ sys_version_info }}</td>
</tr>
<tr>
<th>Python Path:</th>
<td><pre>{{ sys_path|pprint }}</pre></td>
</tr>
<tr>
<th>Server time:</th>
<td>{{server_time|date:"r"}}</td>
</tr>
</table>
</div>
{% if unicode_hint %}
<div id="unicode-hint">
<h2>Unicode error hint</h2>
<p>The string that could not be encoded/decoded was: <strong>{{ unicode_hint|force_escape }}</strong></p>
</div>
{% endif %}
{% if template_does_not_exist %}
<div id="template-not-exist">
<h2>Template-loader postmortem</h2>
{% if postmortem %}
<p class="append-bottom">Django tried loading these templates, in this order:</p>
{% for entry in postmortem %}
<p class="postmortem-section">Using engine <code>{{ entry.backend.name }}</code>:</p>
<ul>
{% if entry.tried %}
{% for attempt in entry.tried %}
<li><code>{{ attempt.0.loader_name }}</code>: {{ attempt.0.name }} ({{ attempt.1 }})</li>
{% endfor %}
</ul>
{% else %}
<li>This engine did not provide a list of tried templates.</li>
{% endif %}
</ul>
{% endfor %}
{% else %}
<p>No templates were found because your 'TEMPLATES' setting is not configured.</p>
{% endif %}
</div>
{% endif %}
{% if template_info %}
<div id="template">
<h2>Error during template rendering</h2>
<p>In template <code>{{ template_info.name }}</code>, error at line <strong>{{ template_info.line }}</strong></p>
<h3>{{ template_info.message }}</h3>
<table class="source{% if template_info.top %} cut-top{% endif %}
{% if template_info.bottom != template_info.total %} cut-bottom{% endif %}">
{% for source_line in template_info.source_lines %}
{% if source_line.0 == template_info.line %}
<tr class="error"><th>{{ source_line.0 }}</th>
<td>{{ template_info.before }}"""
"""<span class="specific">{{ template_info.during }}</span>"""
"""{{ template_info.after }}</td>
</tr>
{% else %}
<tr><th>{{ source_line.0 }}</th>
<td>{{ source_line.1 }}</td></tr>
{% endif %}
{% endfor %}
</table>
</div>
{% endif %}
{% if frames %}
<div id="traceback">
<h2>Traceback <span class="commands">{% if not is_email %}<a href="#" onclick="return switchPastebinFriendly(this);">
Switch to copy-and-paste view</a></span>{% endif %}
</h2>
{% autoescape off %}
<div id="browserTraceback">
<ul class="traceback">
{% for frame in frames %}
{% ifchanged frame.exc_cause %}{% if frame.exc_cause %}
<li><h3>
{% if frame.exc_cause_explicit %}
The above exception ({{ frame.exc_cause }}) was the direct cause of the following exception:
{% else %}
During handling of the above exception ({{ frame.exc_cause }}), another exception occurred:
{% endif %}
</h3></li>
{% endif %}{% endifchanged %}
<li class="frame {{ frame.type }}">
<code>{{ frame.filename|escape }}</code> in <code>{{ frame.function|escape }}</code>
{% if frame.context_line %}
<div class="context" id="c{{ frame.id }}">
{% if frame.pre_context and not is_email %}
<ol start="{{ frame.pre_context_lineno }}" class="pre-context" id="pre{{ frame.id }}">
{% for line in frame.pre_context %}
<li onclick="toggle('pre{{ frame.id }}', 'post{{ frame.id }}')"><pre>{{ line|escape }}</pre></li>
{% endfor %}
</ol>
{% endif %}
<ol start="{{ frame.lineno }}" class="context-line">
<li onclick="toggle('pre{{ frame.id }}', 'post{{ frame.id }}')"><pre>
""" """{{ frame.context_line|escape }}</pre>{% if not is_email %} <span>...</span>{% endif %}</li></ol>
{% if frame.post_context and not is_email %}
<ol start='{{ frame.lineno|add:"1" }}' class="post-context" id="post{{ frame.id }}">
{% for line in frame.post_context %}
<li onclick="toggle('pre{{ frame.id }}', 'post{{ frame.id }}')"><pre>{{ line|escape }}</pre></li>
{% endfor %}
</ol>
{% endif %}
</div>
{% endif %}
{% if frame.vars %}
<div class="commands">
{% if is_email %}
<h2>Local Vars</h2>
{% else %}
<a href="#" onclick="return varToggle(this, '{{ frame.id }}')"><span>▶</span> Local vars</a>
{% endif %}
</div>
<table class="vars" id="v{{ frame.id }}">
<thead>
<tr>
<th>Variable</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{% for var in frame.vars|dictsort:"0" %}
<tr>
<td>{{ var.0|force_escape }}</td>
<td class="code"><pre>{{ var.1 }}</pre></td>
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
</li>
{% endfor %}
</ul>
</div>
{% endautoescape %}
<form action="http://dpaste.com/" name="pasteform" id="pasteform" method="post">
{% if not is_email %}
<div id="pastebinTraceback" class="pastebin">
<input type="hidden" name="language" value="PythonConsole">
<input type="hidden" name="title"
value="{{ exception_type|escape }}{% if request %} at {{ request.path_info|escape }}{% endif %}">
<input type="hidden" name="source" value="Django Dpaste Agent">
<input type="hidden" name="poster" value="Django">
<textarea name="content" id="traceback_area" cols="140" rows="25">
Environment:
{% if request %}
Request Method: {{ request.META.REQUEST_METHOD }}
Request URL: {{ request.get_raw_uri|escape }}
{% endif %}
Django Version: {{ django_version_info }}
Python Version: {{ sys_version_info }}
Installed Applications:
{{ settings.INSTALLED_APPS|pprint }}
Installed Middleware:
{{ settings.MIDDLEWARE_CLASSES|pprint }}
{% if template_does_not_exist %}Template loader postmortem
{% if postmortem %}Django tried loading these templates, in this order:
{% for entry in postmortem %}
Using engine {{ entry.backend.name }}:
{% if entry.tried %}{% for attempt in entry.tried %} * {{ attempt.0.loader_name }}: {{ attempt.0.name }} ({{ attempt.1 }})
{% endfor %}{% else %} This engine did not provide a list of tried templates.
{% endif %}{% endfor %}
{% else %}No templates were found because your 'TEMPLATES' setting is not configured.
{% endif %}
{% endif %}{% if template_info %}
Template error:
In template {{ template_info.name }}, error at line {{ template_info.line }}
{{ template_info.message }}"""
"{% for source_line in template_info.source_lines %}"
"{% if source_line.0 == template_info.line %}"
" {{ source_line.0 }} : {{ template_info.before }} {{ template_info.during }} {{ template_info.after }}"
"{% else %}"
" {{ source_line.0 }} : {{ source_line.1 }}"
"""{% endif %}{% endfor %}{% endif %}
Traceback:{% for frame in frames %}
{% ifchanged frame.exc_cause %}{% if frame.exc_cause %}{% if frame.exc_cause_explicit %}
The above exception ({{ frame.exc_cause }}) was the direct cause of the following exception:
{% else %}
During handling of the above exception ({{ frame.exc_cause }}), another exception occurred:
{% endif %}{% endif %}{% endifchanged %}
File "{{ frame.filename|escape }}" in {{ frame.function|escape }}
{% if frame.context_line %} {{ frame.lineno }}. {{ frame.context_line|escape }}{% endif %}{% endfor %}
Exception Type: {{ exception_type|escape }}{% if request %} at {{ request.path_info|escape }}{% endif %}
Exception Value: {{ exception_value|force_escape }}
</textarea>
<br><br>
<input type="submit" value="Share this traceback on a public Web site">
</div>
</form>
</div>
{% endif %}
{% endif %}
<div id="requestinfo">
<h2>Request information</h2>
{% if request %}
<h3 id="get-info">GET</h3>
{% if request.GET %}
<table class="req">
<thead>
<tr>
<th>Variable</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{% for var in request.GET.items %}
<tr>
<td>{{ var.0 }}</td>
<td class="code"><pre>{{ var.1|pprint }}</pre></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>No GET data</p>
{% endif %}
<h3 id="post-info">POST</h3>
{% if filtered_POST %}
<table class="req">
<thead>
<tr>
<th>Variable</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{% for var in filtered_POST.items %}
<tr>
<td>{{ var.0 }}</td>
<td class="code"><pre>{{ var.1|pprint }}</pre></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>No POST data</p>
{% endif %}
<h3 id="files-info">FILES</h3>
{% if request.FILES %}
<table class="req">
<thead>
<tr>
<th>Variable</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{% for var in request.FILES.items %}
<tr>
<td>{{ var.0 }}</td>
<td class="code"><pre>{{ var.1|pprint }}</pre></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>No FILES data</p>
{% endif %}
<h3 id="cookie-info">COOKIES</h3>
{% if request.COOKIES %}
<table class="req">
<thead>
<tr>
<th>Variable</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{% for var in request.COOKIES.items %}
<tr>
<td>{{ var.0 }}</td>
<td class="code"><pre>{{ var.1|pprint }}</pre></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>No cookie data</p>
{% endif %}
<h3 id="meta-info">META</h3>
<table class="req">
<thead>
<tr>
<th>Variable</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{% for var in request.META.items|dictsort:"0" %}
<tr>
<td>{{ var.0 }}</td>
<td class="code"><pre>{{ var.1|pprint }}</pre></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>Request data not supplied</p>
{% endif %}
<h3 id="settings-info">Settings</h3>
<h4>Using settings module <code>{{ settings.SETTINGS_MODULE }}</code></h4>
<table class="req">
<thead>
<tr>
<th>Setting</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{% for var in settings.items|dictsort:"0" %}
<tr>
<td>{{ var.0 }}</td>
<td class="code"><pre>{{ var.1|pprint }}</pre></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% if not is_email %}
<div id="explanation">
<p>
You're seeing this error because you have <code>DEBUG = True</code> in your
Django settings file. Change that to <code>False</code>, and Django will
display a standard page generated by the handler for this status code.
</p>
</div>
{% endif %}
</body>
</html>
""")
TECHNICAL_500_TEXT_TEMPLATE = ("""{% firstof exception_type 'Report' %}{% if request %} at {{ request.path_info }}{% endif %}
{% firstof exception_value 'No exception message supplied' %}
{% if request %}
Request Method: {{ request.META.REQUEST_METHOD }}
Request URL: {{ request.get_raw_uri }}{% endif %}
Django Version: {{ django_version_info }}
Python Executable: {{ sys_executable }}
Python Version: {{ sys_version_info }}
Python Path: {{ sys_path }}
Server time: {{server_time|date:"r"}}
Installed Applications:
{{ settings.INSTALLED_APPS|pprint }}
Installed Middleware:
{{ settings.MIDDLEWARE_CLASSES|pprint }}
{% if template_does_not_exist %}Template loader postmortem
{% if postmortem %}Django tried loading these templates, in this order:
{% for entry in postmortem %}
Using engine {{ entry.backend.name }}:
{% if entry.tried %}{% for attempt in entry.tried %} * {{ attempt.0.loader_name }}: {{ attempt.0.name }} ({{ attempt.1 }})
{% endfor %}{% else %} This engine did not provide a list of tried templates.
{% endif %}{% endfor %}
{% else %}No templates were found because your 'TEMPLATES' setting is not configured.
{% endif %}
{% endif %}{% if template_info %}
Template error:
In template {{ template_info.name }}, error at line {{ template_info.line }}
{{ template_info.message }}
{% for source_line in template_info.source_lines %}"""
"{% if source_line.0 == template_info.line %}"
" {{ source_line.0 }} : {{ template_info.before }} {{ template_info.during }} {{ template_info.after }}"
"{% else %}"
" {{ source_line.0 }} : {{ source_line.1 }}"
"""{% endif %}{% endfor %}{% endif %}{% if frames %}
Traceback:"""
"{% for frame in frames %}"
"{% ifchanged frame.exc_cause %}"
" {% if frame.exc_cause %}" """
{% if frame.exc_cause_explicit %}
The above exception ({{ frame.exc_cause }}) was the direct cause of the following exception:
{% else %}
During handling of the above exception ({{ frame.exc_cause }}), another exception occurred:
{% endif %}
{% endif %}
{% endifchanged %}
File "{{ frame.filename }}" in {{ frame.function }}
{% if frame.context_line %} {{ frame.lineno }}. {{ frame.context_line }}{% endif %}
{% endfor %}
{% if exception_type %}Exception Type: {{ exception_type }}{% if request %} at {{ request.path_info }}{% endif %}
{% if exception_value %}Exception Value: {{ exception_value }}{% endif %}{% endif %}{% endif %}
{% if request %}Request information:
GET:{% for k, v in request.GET.items %}
{{ k }} = {{ v|stringformat:"r" }}{% empty %} No GET data{% endfor %}
POST:{% for k, v in filtered_POST.items %}
{{ k }} = {{ v|stringformat:"r" }}{% empty %} No POST data{% endfor %}
FILES:{% for k, v in request.FILES.items %}
{{ k }} = {{ v|stringformat:"r" }}{% empty %} No FILES data{% endfor %}
COOKIES:{% for k, v in request.COOKIES.items %}
{{ k }} = {{ v|stringformat:"r" }}{% empty %} No cookie data{% endfor %}
META:{% for k, v in request.META.items|dictsort:"0" %}
{{ k }} = {{ v|stringformat:"r" }}{% endfor %}
{% else %}Request data not supplied
{% endif %}
Settings:
Using settings module {{ settings.SETTINGS_MODULE }}{% for k, v in settings.items|dictsort:"0" %}
{{ k }} = {{ v|stringformat:"r" }}{% endfor %}
{% if not is_email %}
You're seeing this error because you have DEBUG = True in your
Django settings file. Change that to False, and Django will
display a standard page generated by the handler for this status code.
{% endif %}
""")
TECHNICAL_404_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Page not found at {{ request.path_info|escape }}</title>
<meta name="robots" content="NONE,NOARCHIVE">
<style type="text/css">
html * { padding:0; margin:0; }
body * { padding:10px 20px; }
body * * { padding:0; }
body { font:small sans-serif; background:#eee; }
body>div { border-bottom:1px solid #ddd; }
h1 { font-weight:normal; margin-bottom:.4em; }
h1 span { font-size:60%; color:#666; font-weight:normal; }
table { border:none; border-collapse: collapse; width:100%; }
td, th { vertical-align:top; padding:2px 3px; }
th { width:12em; text-align:right; color:#666; padding-right:.5em; }
#info { background:#f6f6f6; }
#info ol { margin: 0.5em 4em; }
#info ol li { font-family: monospace; }
#summary { background: #ffc; }
#explanation { background:#eee; border-bottom: 0px none; }
</style>
</head>
<body>
<div id="summary">
<h1>Page not found <span>(404)</span></h1>
<table class="meta">
<tr>
<th>Request Method:</th>
<td>{{ request.META.REQUEST_METHOD }}</td>
</tr>
<tr>
<th>Request URL:</th>
<td>{{ request.build_absolute_uri|escape }}</td>
</tr>
{% if raising_view_name %}
<tr>
<th>Raised by:</th>
<td>{{ raising_view_name }}</td>
</tr>
{% endif %}
</table>
</div>
<div id="info">
{% if urlpatterns %}
<p>
Using the URLconf defined in <code>{{ urlconf }}</code>,
Django tried these URL patterns, in this order:
</p>
<ol>
{% for pattern in urlpatterns %}
<li>
{% for pat in pattern %}
{{ pat.regex.pattern }}
{% if forloop.last and pat.name %}[name='{{ pat.name }}']{% endif %}
{% endfor %}
</li>
{% endfor %}
</ol>
<p>The current URL, <code>{{ request_path|escape }}</code>, didn't match any of these.</p>
{% else %}
<p>{{ reason }}</p>
{% endif %}
</div>
<div id="explanation">
<p>
You're seeing this error because you have <code>DEBUG = True</code> in
your Django settings file. Change that to <code>False</code>, and Django
will display a standard 404 page.
</p>
</div>
</body>
</html>
"""
DEFAULT_URLCONF_TEMPLATE = """
<!DOCTYPE html>
<html lang="en"><head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="robots" content="NONE,NOARCHIVE"><title>{{ title }}</title>
<style type="text/css">
html * { padding:0; margin:0; }
body * { padding:10px 20px; }
body * * { padding:0; }
body { font:small sans-serif; }
body>div { border-bottom:1px solid #ddd; }
h1 { font-weight:normal; }
h2 { margin-bottom:.8em; }
h2 span { font-size:80%; color:#666; font-weight:normal; }
h3 { margin:1em 0 .5em 0; }
h4 { margin:0 0 .5em 0; font-weight: normal; }
table { border:1px solid #ccc; border-collapse: collapse; width:100%; background:white; }
tbody td, tbody th { vertical-align:top; padding:2px 3px; }
thead th {
padding:1px 6px 1px 3px; background:#fefefe; text-align:left;
font-weight:normal; font-size:11px; border:1px solid #ddd;
}
tbody th { width:12em; text-align:right; color:#666; padding-right:.5em; }
#summary { background: #e0ebff; }
#summary h2 { font-weight: normal; color: #666; }
#explanation { background:#eee; }
#instructions { background:#f6f6f6; }
#summary table { border:none; background:transparent; }
</style>
</head>
<body>
<div id="summary">
<h1>{{ heading }}</h1>
<h2>{{ subheading }}</h2>
</div>
<div id="instructions">
<p>
{{ instructions|safe }}
</p>
</div>
<div id="explanation">
<p>
{{ explanation|safe }}
</p>
</div>
</body></html>
"""
| bsd-3-clause |
pdellaert/ansible | test/units/module_utils/hwc/test_hwc_utils.py | 19 | 1152 | # -*- coding: utf-8 -*-
from units.compat import unittest
from ansible.module_utils.hwc_utils import (HwcModuleException, navigate_value)
class HwcUtilsTestCase(unittest.TestCase):
def test_navigate_value(self):
value = {
'foo': {
'quiet': {
'tree': 'test',
"trees": [0, 1]
},
}
}
self.assertEquals(navigate_value(value, ["foo", "quiet", "tree"]),
"test")
self.assertEquals(
navigate_value(value, ["foo", "quiet", "trees"],
{"foo.quiet.trees": 1}),
1)
self.assertRaisesRegexp(HwcModuleException,
r".* key\(q\) is not exist in dict",
navigate_value, value, ["foo", "q", "tree"])
self.assertRaisesRegexp(HwcModuleException,
r".* the index is out of list",
navigate_value, value,
["foo", "quiet", "trees"],
{"foo.quiet.trees": 2})
| gpl-3.0 |
vladikoff/fxa-mochitest | tests/venv/lib/python2.7/site-packages/pip/_vendor/html5lib/sanitizer.py | 805 | 16428 | from __future__ import absolute_import, division, unicode_literals
import re
from xml.sax.saxutils import escape, unescape
from .tokenizer import HTMLTokenizer
from .constants import tokenTypes
class HTMLSanitizerMixin(object):
""" sanitization of XHTML+MathML+SVG and of inline style attributes."""
acceptable_elements = ['a', 'abbr', 'acronym', 'address', 'area',
'article', 'aside', 'audio', 'b', 'big', 'blockquote', 'br', 'button',
'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup',
'command', 'datagrid', 'datalist', 'dd', 'del', 'details', 'dfn',
'dialog', 'dir', 'div', 'dl', 'dt', 'em', 'event-source', 'fieldset',
'figcaption', 'figure', 'footer', 'font', 'form', 'header', 'h1',
'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'input', 'ins',
'keygen', 'kbd', 'label', 'legend', 'li', 'm', 'map', 'menu', 'meter',
'multicol', 'nav', 'nextid', 'ol', 'output', 'optgroup', 'option',
'p', 'pre', 'progress', 'q', 's', 'samp', 'section', 'select',
'small', 'sound', 'source', 'spacer', 'span', 'strike', 'strong',
'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'time', 'tfoot',
'th', 'thead', 'tr', 'tt', 'u', 'ul', 'var', 'video']
mathml_elements = ['maction', 'math', 'merror', 'mfrac', 'mi',
'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom',
'mprescripts', 'mroot', 'mrow', 'mspace', 'msqrt', 'mstyle', 'msub',
'msubsup', 'msup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder',
'munderover', 'none']
svg_elements = ['a', 'animate', 'animateColor', 'animateMotion',
'animateTransform', 'clipPath', 'circle', 'defs', 'desc', 'ellipse',
'font-face', 'font-face-name', 'font-face-src', 'g', 'glyph', 'hkern',
'linearGradient', 'line', 'marker', 'metadata', 'missing-glyph',
'mpath', 'path', 'polygon', 'polyline', 'radialGradient', 'rect',
'set', 'stop', 'svg', 'switch', 'text', 'title', 'tspan', 'use']
acceptable_attributes = ['abbr', 'accept', 'accept-charset', 'accesskey',
'action', 'align', 'alt', 'autocomplete', 'autofocus', 'axis',
'background', 'balance', 'bgcolor', 'bgproperties', 'border',
'bordercolor', 'bordercolordark', 'bordercolorlight', 'bottompadding',
'cellpadding', 'cellspacing', 'ch', 'challenge', 'char', 'charoff',
'choff', 'charset', 'checked', 'cite', 'class', 'clear', 'color',
'cols', 'colspan', 'compact', 'contenteditable', 'controls', 'coords',
'data', 'datafld', 'datapagesize', 'datasrc', 'datetime', 'default',
'delay', 'dir', 'disabled', 'draggable', 'dynsrc', 'enctype', 'end',
'face', 'for', 'form', 'frame', 'galleryimg', 'gutter', 'headers',
'height', 'hidefocus', 'hidden', 'high', 'href', 'hreflang', 'hspace',
'icon', 'id', 'inputmode', 'ismap', 'keytype', 'label', 'leftspacing',
'lang', 'list', 'longdesc', 'loop', 'loopcount', 'loopend',
'loopstart', 'low', 'lowsrc', 'max', 'maxlength', 'media', 'method',
'min', 'multiple', 'name', 'nohref', 'noshade', 'nowrap', 'open',
'optimum', 'pattern', 'ping', 'point-size', 'poster', 'pqg', 'preload',
'prompt', 'radiogroup', 'readonly', 'rel', 'repeat-max', 'repeat-min',
'replace', 'required', 'rev', 'rightspacing', 'rows', 'rowspan',
'rules', 'scope', 'selected', 'shape', 'size', 'span', 'src', 'start',
'step', 'style', 'summary', 'suppress', 'tabindex', 'target',
'template', 'title', 'toppadding', 'type', 'unselectable', 'usemap',
'urn', 'valign', 'value', 'variable', 'volume', 'vspace', 'vrml',
'width', 'wrap', 'xml:lang']
mathml_attributes = ['actiontype', 'align', 'columnalign', 'columnalign',
'columnalign', 'columnlines', 'columnspacing', 'columnspan', 'depth',
'display', 'displaystyle', 'equalcolumns', 'equalrows', 'fence',
'fontstyle', 'fontweight', 'frame', 'height', 'linethickness', 'lspace',
'mathbackground', 'mathcolor', 'mathvariant', 'mathvariant', 'maxsize',
'minsize', 'other', 'rowalign', 'rowalign', 'rowalign', 'rowlines',
'rowspacing', 'rowspan', 'rspace', 'scriptlevel', 'selection',
'separator', 'stretchy', 'width', 'width', 'xlink:href', 'xlink:show',
'xlink:type', 'xmlns', 'xmlns:xlink']
svg_attributes = ['accent-height', 'accumulate', 'additive', 'alphabetic',
'arabic-form', 'ascent', 'attributeName', 'attributeType',
'baseProfile', 'bbox', 'begin', 'by', 'calcMode', 'cap-height',
'class', 'clip-path', 'color', 'color-rendering', 'content', 'cx',
'cy', 'd', 'dx', 'dy', 'descent', 'display', 'dur', 'end', 'fill',
'fill-opacity', 'fill-rule', 'font-family', 'font-size',
'font-stretch', 'font-style', 'font-variant', 'font-weight', 'from',
'fx', 'fy', 'g1', 'g2', 'glyph-name', 'gradientUnits', 'hanging',
'height', 'horiz-adv-x', 'horiz-origin-x', 'id', 'ideographic', 'k',
'keyPoints', 'keySplines', 'keyTimes', 'lang', 'marker-end',
'marker-mid', 'marker-start', 'markerHeight', 'markerUnits',
'markerWidth', 'mathematical', 'max', 'min', 'name', 'offset',
'opacity', 'orient', 'origin', 'overline-position',
'overline-thickness', 'panose-1', 'path', 'pathLength', 'points',
'preserveAspectRatio', 'r', 'refX', 'refY', 'repeatCount',
'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart',
'rotate', 'rx', 'ry', 'slope', 'stemh', 'stemv', 'stop-color',
'stop-opacity', 'strikethrough-position', 'strikethrough-thickness',
'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap',
'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity',
'stroke-width', 'systemLanguage', 'target', 'text-anchor', 'to',
'transform', 'type', 'u1', 'u2', 'underline-position',
'underline-thickness', 'unicode', 'unicode-range', 'units-per-em',
'values', 'version', 'viewBox', 'visibility', 'width', 'widths', 'x',
'x-height', 'x1', 'x2', 'xlink:actuate', 'xlink:arcrole',
'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type',
'xml:base', 'xml:lang', 'xml:space', 'xmlns', 'xmlns:xlink', 'y',
'y1', 'y2', 'zoomAndPan']
attr_val_is_uri = ['href', 'src', 'cite', 'action', 'longdesc', 'poster',
'xlink:href', 'xml:base']
svg_attr_val_allows_ref = ['clip-path', 'color-profile', 'cursor', 'fill',
'filter', 'marker', 'marker-start', 'marker-mid', 'marker-end',
'mask', 'stroke']
svg_allow_local_href = ['altGlyph', 'animate', 'animateColor',
'animateMotion', 'animateTransform', 'cursor', 'feImage', 'filter',
'linearGradient', 'pattern', 'radialGradient', 'textpath', 'tref',
'set', 'use']
acceptable_css_properties = ['azimuth', 'background-color',
'border-bottom-color', 'border-collapse', 'border-color',
'border-left-color', 'border-right-color', 'border-top-color', 'clear',
'color', 'cursor', 'direction', 'display', 'elevation', 'float', 'font',
'font-family', 'font-size', 'font-style', 'font-variant', 'font-weight',
'height', 'letter-spacing', 'line-height', 'overflow', 'pause',
'pause-after', 'pause-before', 'pitch', 'pitch-range', 'richness',
'speak', 'speak-header', 'speak-numeral', 'speak-punctuation',
'speech-rate', 'stress', 'text-align', 'text-decoration', 'text-indent',
'unicode-bidi', 'vertical-align', 'voice-family', 'volume',
'white-space', 'width']
acceptable_css_keywords = ['auto', 'aqua', 'black', 'block', 'blue',
'bold', 'both', 'bottom', 'brown', 'center', 'collapse', 'dashed',
'dotted', 'fuchsia', 'gray', 'green', '!important', 'italic', 'left',
'lime', 'maroon', 'medium', 'none', 'navy', 'normal', 'nowrap', 'olive',
'pointer', 'purple', 'red', 'right', 'solid', 'silver', 'teal', 'top',
'transparent', 'underline', 'white', 'yellow']
acceptable_svg_properties = ['fill', 'fill-opacity', 'fill-rule',
'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin',
'stroke-opacity']
acceptable_protocols = ['ed2k', 'ftp', 'http', 'https', 'irc',
'mailto', 'news', 'gopher', 'nntp', 'telnet', 'webcal',
'xmpp', 'callto', 'feed', 'urn', 'aim', 'rsync', 'tag',
'ssh', 'sftp', 'rtsp', 'afs']
# subclasses may define their own versions of these constants
allowed_elements = acceptable_elements + mathml_elements + svg_elements
allowed_attributes = acceptable_attributes + mathml_attributes + svg_attributes
allowed_css_properties = acceptable_css_properties
allowed_css_keywords = acceptable_css_keywords
allowed_svg_properties = acceptable_svg_properties
allowed_protocols = acceptable_protocols
# Sanitize the +html+, escaping all elements not in ALLOWED_ELEMENTS, and
# stripping out all # attributes not in ALLOWED_ATTRIBUTES. Style
# attributes are parsed, and a restricted set, # specified by
# ALLOWED_CSS_PROPERTIES and ALLOWED_CSS_KEYWORDS, are allowed through.
# attributes in ATTR_VAL_IS_URI are scanned, and only URI schemes specified
# in ALLOWED_PROTOCOLS are allowed.
#
# sanitize_html('<script> do_nasty_stuff() </script>')
# => <script> do_nasty_stuff() </script>
# sanitize_html('<a href="javascript: sucker();">Click here for $100</a>')
# => <a>Click here for $100</a>
def sanitize_token(self, token):
# accommodate filters which use token_type differently
token_type = token["type"]
if token_type in list(tokenTypes.keys()):
token_type = tokenTypes[token_type]
if token_type in (tokenTypes["StartTag"], tokenTypes["EndTag"],
tokenTypes["EmptyTag"]):
if token["name"] in self.allowed_elements:
return self.allowed_token(token, token_type)
else:
return self.disallowed_token(token, token_type)
elif token_type == tokenTypes["Comment"]:
pass
else:
return token
def allowed_token(self, token, token_type):
if "data" in token:
attrs = dict([(name, val) for name, val in
token["data"][::-1]
if name in self.allowed_attributes])
for attr in self.attr_val_is_uri:
if attr not in attrs:
continue
val_unescaped = re.sub("[`\000-\040\177-\240\s]+", '',
unescape(attrs[attr])).lower()
# remove replacement characters from unescaped characters
val_unescaped = val_unescaped.replace("\ufffd", "")
if (re.match("^[a-z0-9][-+.a-z0-9]*:", val_unescaped) and
(val_unescaped.split(':')[0] not in
self.allowed_protocols)):
del attrs[attr]
for attr in self.svg_attr_val_allows_ref:
if attr in attrs:
attrs[attr] = re.sub(r'url\s*\(\s*[^#\s][^)]+?\)',
' ',
unescape(attrs[attr]))
if (token["name"] in self.svg_allow_local_href and
'xlink:href' in attrs and re.search('^\s*[^#\s].*',
attrs['xlink:href'])):
del attrs['xlink:href']
if 'style' in attrs:
attrs['style'] = self.sanitize_css(attrs['style'])
token["data"] = [[name, val] for name, val in list(attrs.items())]
return token
def disallowed_token(self, token, token_type):
if token_type == tokenTypes["EndTag"]:
token["data"] = "</%s>" % token["name"]
elif token["data"]:
attrs = ''.join([' %s="%s"' % (k, escape(v)) for k, v in token["data"]])
token["data"] = "<%s%s>" % (token["name"], attrs)
else:
token["data"] = "<%s>" % token["name"]
if token.get("selfClosing"):
token["data"] = token["data"][:-1] + "/>"
if token["type"] in list(tokenTypes.keys()):
token["type"] = "Characters"
else:
token["type"] = tokenTypes["Characters"]
del token["name"]
return token
def sanitize_css(self, style):
# disallow urls
style = re.compile('url\s*\(\s*[^\s)]+?\s*\)\s*').sub(' ', style)
# gauntlet
if not re.match("""^([:,;#%.\sa-zA-Z0-9!]|\w-\w|'[\s\w]+'|"[\s\w]+"|\([\d,\s]+\))*$""", style):
return ''
if not re.match("^\s*([-\w]+\s*:[^:;]*(;\s*|$))*$", style):
return ''
clean = []
for prop, value in re.findall("([-\w]+)\s*:\s*([^:;]*)", style):
if not value:
continue
if prop.lower() in self.allowed_css_properties:
clean.append(prop + ': ' + value + ';')
elif prop.split('-')[0].lower() in ['background', 'border', 'margin',
'padding']:
for keyword in value.split():
if not keyword in self.acceptable_css_keywords and \
not re.match("^(#[0-9a-f]+|rgb\(\d+%?,\d*%?,?\d*%?\)?|\d{0,2}\.?\d{0,2}(cm|em|ex|in|mm|pc|pt|px|%|,|\))?)$", keyword):
break
else:
clean.append(prop + ': ' + value + ';')
elif prop.lower() in self.allowed_svg_properties:
clean.append(prop + ': ' + value + ';')
return ' '.join(clean)
class HTMLSanitizer(HTMLTokenizer, HTMLSanitizerMixin):
def __init__(self, stream, encoding=None, parseMeta=True, useChardet=True,
lowercaseElementName=False, lowercaseAttrName=False, parser=None):
# Change case matching defaults as we only output lowercase html anyway
# This solution doesn't seem ideal...
HTMLTokenizer.__init__(self, stream, encoding, parseMeta, useChardet,
lowercaseElementName, lowercaseAttrName, parser=parser)
def __iter__(self):
for token in HTMLTokenizer.__iter__(self):
token = self.sanitize_token(token)
if token:
yield token
| mpl-2.0 |
cpennington/edx-platform | lms/djangoapps/mobile_api/decorators.py | 4 | 2478 | """
Decorators for Mobile APIs.
"""
import functools
from django.http import Http404
from opaque_keys.edx.keys import CourseKey
from rest_framework import status
from rest_framework.response import Response
from lms.djangoapps.courseware.courses import get_course_with_access
from lms.djangoapps.courseware.courseware_access_exception import CoursewareAccessException
from lms.djangoapps.courseware.exceptions import CourseAccessRedirect
from openedx.core.lib.api.view_utils import view_auth_classes
from xmodule.modulestore.django import modulestore
def mobile_course_access(depth=0):
"""
Method decorator for a mobile API endpoint that verifies the user has access to the course in a mobile context.
"""
def _decorator(func):
"""Outer method decorator."""
@functools.wraps(func)
def _wrapper(self, request, *args, **kwargs):
"""
Expects kwargs to contain 'course_id'.
Passes the course descriptor to the given decorated function.
Raises 404 if access to course is disallowed.
"""
course_id = CourseKey.from_string(kwargs.pop('course_id'))
with modulestore().bulk_operations(course_id):
try:
course = get_course_with_access(
request.user,
'load_mobile',
course_id,
depth=depth,
check_if_enrolled=True,
)
except CoursewareAccessException as error:
return Response(data=error.to_json(), status=status.HTTP_404_NOT_FOUND)
except CourseAccessRedirect as error:
# If the redirect contains information about the triggering AccessError,
# return the information contained in the AccessError.
if error.access_error is not None:
return Response(data=error.access_error.to_json(), status=status.HTTP_404_NOT_FOUND)
# Raise a 404 if the user does not have course access
raise Http404
return func(self, request, course=course, *args, **kwargs)
return _wrapper
return _decorator
def mobile_view(is_user=False):
"""
Function and class decorator that abstracts the authentication and permission checks for mobile api views.
"""
return view_auth_classes(is_user)
| agpl-3.0 |
JohannesBuchner/doit | doit/cmd_info.py | 3 | 4162 | """command doit info - display info on task metadata"""
import pprint
from .cmd_base import DoitCmdBase
from .exceptions import InvalidCommand
opt_hide_status = {
'name': 'hide_status',
'long': 'no-status',
'type': bool,
'default': False,
'help': """Hides reasons why this task would be executed.
[default: %(default)s]"""
}
class Info(DoitCmdBase):
"""command doit info"""
doc_purpose = "show info about a task"
doc_usage = "TASK"
doc_description = None
cmd_options = (opt_hide_status, )
def _execute(self, pos_args, hide_status=False):
if len(pos_args) != 1:
msg = ('`info` failed, must select *one* task.'
'\nCheck `{} help info`.'.format(self.bin_name))
raise InvalidCommand(msg)
task_name = pos_args[0]
# dict of all tasks
tasks = dict([(t.name, t) for t in self.task_list])
printer = pprint.PrettyPrinter(indent=4, stream=self.outstream)
task = tasks[task_name]
task_attrs = (
('file_dep', 'list'),
('task_dep', 'list'),
('setup_tasks', 'list'),
('calc_dep', 'list'),
('targets', 'list'),
# these fields usually contains reference to python functions
# 'actions', 'clean', 'uptodate', 'teardown', 'title'
('getargs', 'dict'),
('params', 'list'),
('verbosity', 'scalar'),
('watch', 'list'),
)
self.outstream.write('\n{}\n'.format(task.name))
if task.doc:
self.outstream.write('\n{}\n'.format(task.doc))
# print reason task is not up-to-date
retcode = 0
if not hide_status:
status = self.dep_manager.get_status(task, tasks, get_log=True)
self.outstream.write('\n{:11s}: {}\n'
.format('status', status.status))
if status.status != 'up-to-date':
# status.status == 'run' or status.status == 'error'
self.outstream.write(self.get_reasons(status.reasons))
self.outstream.write('\n')
retcode = 1
for (attr, attr_type) in task_attrs:
value = getattr(task, attr)
# only print fields that have non-empty value
if value:
self.outstream.write('\n{:11s}: '.format(attr))
if attr_type == 'list':
self.outstream.write('\n')
for val in value:
self.outstream.write(' - {}\n'.format(val))
else:
printer.pprint(getattr(task, attr))
return retcode
@staticmethod
def get_reasons(reasons):
'''return string with description of reason task is not up-to-date'''
lines = []
if reasons['has_no_dependencies']:
lines.append(' * The task has no dependencies.')
if reasons['uptodate_false']:
lines.append(' * The following uptodate objects evaluate to false:')
for utd, utd_args, utd_kwargs in reasons['uptodate_false']:
msg = ' - {} (args={}, kwargs={})'
lines.append(msg.format(utd, utd_args, utd_kwargs))
if reasons['checker_changed']:
msg = ' * The file_dep checker changed from {0} to {1}.'
lines.append(msg.format(*reasons['checker_changed']))
sentences = {
'missing_target': 'The following targets do not exist:',
'changed_file_dep': 'The following file dependencies have changed:',
'missing_file_dep': 'The following file dependencies are missing:',
'removed_file_dep': 'The following file dependencies were removed:',
'added_file_dep': 'The following file dependencies were added:',
}
for reason, sentence in sentences.items():
entries = reasons.get(reason)
if entries:
lines.append(' * {}'.format(sentence))
for item in entries:
lines.append(' - {}'.format(item))
return '\n'.join(lines)
| mit |
garyd203/flying-circus | src/flyingcircus/_raw/opsworks.py | 1 | 8157 | """Raw representations of every data type in the AWS OpsWorks service.
See Also:
`AWS developer guide for OpsWorks
<https://docs.aws.amazon.com/opsworks/latest/userguide/index.html>`_
This file is automatically generated, and should not be directly edited.
"""
from attr import attrib
from attr import attrs
from ..core import ATTRSCONFIG
from ..core import Resource
from ..core import ResourceProperties
from ..core import create_object_converter
__all__ = [
"App",
"AppProperties",
"ElasticLoadBalancerAttachment",
"ElasticLoadBalancerAttachmentProperties",
"Instance",
"InstanceProperties",
"Layer",
"LayerProperties",
"Stack",
"StackProperties",
"UserProfile",
"UserProfileProperties",
"Volume",
"VolumeProperties",
]
@attrs(**ATTRSCONFIG)
class AppProperties(ResourceProperties):
AppSource = attrib(default=None)
Attributes = attrib(default=None)
DataSources = attrib(default=None)
Description = attrib(default=None)
Domains = attrib(default=None)
EnableSsl = attrib(default=None)
Environment = attrib(default=None)
Name = attrib(default=None)
Shortname = attrib(default=None)
SslConfiguration = attrib(default=None)
StackId = attrib(default=None)
Type = attrib(default=None)
@attrs(**ATTRSCONFIG)
class App(Resource):
"""A App for OpsWorks.
See Also:
`AWS Cloud Formation documentation for App
<http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-app.html>`_
"""
RESOURCE_TYPE = "AWS::OpsWorks::App"
Properties: AppProperties = attrib(
factory=AppProperties, converter=create_object_converter(AppProperties)
)
@attrs(**ATTRSCONFIG)
class ElasticLoadBalancerAttachmentProperties(ResourceProperties):
ElasticLoadBalancerName = attrib(default=None)
LayerId = attrib(default=None)
@attrs(**ATTRSCONFIG)
class ElasticLoadBalancerAttachment(Resource):
"""A Elastic Load Balancer Attachment for OpsWorks.
See Also:
`AWS Cloud Formation documentation for ElasticLoadBalancerAttachment
<http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-elbattachment.html>`_
"""
RESOURCE_TYPE = "AWS::OpsWorks::ElasticLoadBalancerAttachment"
Properties: ElasticLoadBalancerAttachmentProperties = attrib(
factory=ElasticLoadBalancerAttachmentProperties,
converter=create_object_converter(ElasticLoadBalancerAttachmentProperties),
)
@attrs(**ATTRSCONFIG)
class InstanceProperties(ResourceProperties):
AgentVersion = attrib(default=None)
AmiId = attrib(default=None)
Architecture = attrib(default=None)
AutoScalingType = attrib(default=None)
AvailabilityZone = attrib(default=None)
BlockDeviceMappings = attrib(default=None)
EbsOptimized = attrib(default=None)
ElasticIps = attrib(default=None)
Hostname = attrib(default=None)
InstallUpdatesOnBoot = attrib(default=None)
InstanceType = attrib(default=None)
LayerIds = attrib(default=None)
Os = attrib(default=None)
RootDeviceType = attrib(default=None)
SshKeyName = attrib(default=None)
StackId = attrib(default=None)
SubnetId = attrib(default=None)
Tenancy = attrib(default=None)
TimeBasedAutoScaling = attrib(default=None)
VirtualizationType = attrib(default=None)
Volumes = attrib(default=None)
@attrs(**ATTRSCONFIG)
class Instance(Resource):
"""A Instance for OpsWorks.
See Also:
`AWS Cloud Formation documentation for Instance
<http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html>`_
"""
RESOURCE_TYPE = "AWS::OpsWorks::Instance"
Properties: InstanceProperties = attrib(
factory=InstanceProperties,
converter=create_object_converter(InstanceProperties),
)
@attrs(**ATTRSCONFIG)
class LayerProperties(ResourceProperties):
Attributes = attrib(default=None)
AutoAssignElasticIps = attrib(default=None)
AutoAssignPublicIps = attrib(default=None)
CustomInstanceProfileArn = attrib(default=None)
CustomJson = attrib(default=None)
CustomRecipes = attrib(default=None)
CustomSecurityGroupIds = attrib(default=None)
EnableAutoHealing = attrib(default=None)
InstallUpdatesOnBoot = attrib(default=None)
LifecycleEventConfiguration = attrib(default=None)
LoadBasedAutoScaling = attrib(default=None)
Name = attrib(default=None)
Packages = attrib(default=None)
Shortname = attrib(default=None)
StackId = attrib(default=None)
Tags = attrib(default=None)
Type = attrib(default=None)
UseEbsOptimizedInstances = attrib(default=None)
VolumeConfigurations = attrib(default=None)
@attrs(**ATTRSCONFIG)
class Layer(Resource):
"""A Layer for OpsWorks.
See Also:
`AWS Cloud Formation documentation for Layer
<http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html>`_
"""
RESOURCE_TYPE = "AWS::OpsWorks::Layer"
Properties: LayerProperties = attrib(
factory=LayerProperties, converter=create_object_converter(LayerProperties)
)
@attrs(**ATTRSCONFIG)
class StackProperties(ResourceProperties):
AgentVersion = attrib(default=None)
Attributes = attrib(default=None)
ChefConfiguration = attrib(default=None)
CloneAppIds = attrib(default=None)
ClonePermissions = attrib(default=None)
ConfigurationManager = attrib(default=None)
CustomCookbooksSource = attrib(default=None)
CustomJson = attrib(default=None)
DefaultAvailabilityZone = attrib(default=None)
DefaultInstanceProfileArn = attrib(default=None)
DefaultOs = attrib(default=None)
DefaultRootDeviceType = attrib(default=None)
DefaultSshKeyName = attrib(default=None)
DefaultSubnetId = attrib(default=None)
EcsClusterArn = attrib(default=None)
ElasticIps = attrib(default=None)
HostnameTheme = attrib(default=None)
Name = attrib(default=None)
RdsDbInstances = attrib(default=None)
ServiceRoleArn = attrib(default=None)
SourceStackId = attrib(default=None)
Tags = attrib(default=None)
UseCustomCookbooks = attrib(default=None)
UseOpsworksSecurityGroups = attrib(default=None)
VpcId = attrib(default=None)
@attrs(**ATTRSCONFIG)
class Stack(Resource):
"""A Stack for OpsWorks.
See Also:
`AWS Cloud Formation documentation for Stack
<http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html>`_
"""
RESOURCE_TYPE = "AWS::OpsWorks::Stack"
Properties: StackProperties = attrib(
factory=StackProperties, converter=create_object_converter(StackProperties)
)
@attrs(**ATTRSCONFIG)
class UserProfileProperties(ResourceProperties):
AllowSelfManagement = attrib(default=None)
IamUserArn = attrib(default=None)
SshPublicKey = attrib(default=None)
SshUsername = attrib(default=None)
@attrs(**ATTRSCONFIG)
class UserProfile(Resource):
"""A User Profile for OpsWorks.
See Also:
`AWS Cloud Formation documentation for UserProfile
<http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-userprofile.html>`_
"""
RESOURCE_TYPE = "AWS::OpsWorks::UserProfile"
Properties: UserProfileProperties = attrib(
factory=UserProfileProperties,
converter=create_object_converter(UserProfileProperties),
)
@attrs(**ATTRSCONFIG)
class VolumeProperties(ResourceProperties):
Ec2VolumeId = attrib(default=None)
MountPoint = attrib(default=None)
Name = attrib(default=None)
StackId = attrib(default=None)
@attrs(**ATTRSCONFIG)
class Volume(Resource):
"""A Volume for OpsWorks.
See Also:
`AWS Cloud Formation documentation for Volume
<http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-volume.html>`_
"""
RESOURCE_TYPE = "AWS::OpsWorks::Volume"
Properties: VolumeProperties = attrib(
factory=VolumeProperties, converter=create_object_converter(VolumeProperties)
)
| lgpl-3.0 |
bl4ckdu5t/registron | old/e2etests/common/maketests.py | 9 | 3403 | #!/usr/bin/env python
# Copyright (C) 2011, Hartmut Goebel
# Copyright (C) 2005, Giovanni Bajo
# Based on previous work under copyright (c) 1999, 2002 McMillan Enterprises, Inc.
#
# 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 (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
import os
import optparse
import shutil
try:
import PyInstaller
except ImportError:
# if importing PyInstaller fails, try to load from parent
# directory to support running without installation
import imp
import os
if not hasattr(os, "getuid") or os.getuid() != 0:
imp.load_module('PyInstaller', *imp.find_module('PyInstaller',
[os.path.abspath(os.path.join(__file__, '..','..','..'))]))
from PyInstaller import is_win, is_linux
from PyInstaller import compat
utils_dir = os.path.normpath(os.path.join(__file__, '..', '..', '..', 'utils'))
makespec = os.path.join(utils_dir, 'Makespec.py')
build = os.path.join(utils_dir, 'Build.py')
if is_win:
stripopts = ('',)
consoleopts = ('', '--noconsole')
else:
stripopts = ('', '--strip')
consoleopts = ('',)
out_pattern = 't%d'
if is_linux:
import tempfile
out_pattern = os.path.join(tempfile.gettempdir(), 'hanoi', out_pattern)
dist_pattern_dir = os.path.join(out_pattern, 'dist', 'hanoi', 'hanoi')
dist_pattern_file = os.path.join(out_pattern, 'dist', 'hanoi')
script_name = os.path.abspath(os.path.join(__file__, '..', 'hanoi.py'))
def build_test(cnt, bldconfig, *options, **kwopts):
options = filter(None, options)
if kwopts['clean'] and os.path.isdir(out_pattern % cnt):
# remove/clean the working directory
shutil.rmtree(out_pattern % cnt)
compat.exec_python_rc(makespec, script_name,
'--out', out_pattern % cnt, bldconfig, *options)
compat.exec_python_rc(build, os.path.join(out_pattern % cnt, 'hanoi.spec'),
'--noconfirm')
if is_linux:
# create symlinks
if os.path.islink('hanoi%d' % cnt):
os.remove('hanoi%d' % cnt)
if bldconfig == '--onedir':
os.symlink(dist_pattern_dir % cnt, 'hanoi%d' % cnt)
else:
os.symlink(dist_pattern_file % cnt, 'hanoi%d' % cnt)
parser = optparse.OptionParser('%prog [NUM ...]')
parser.add_option('--clean', action='store_true',
help=('Perform clean builds '
'(remove target dirs prior to building).'))
opts, args = parser.parse_args()
args = map(int, args)
i = 1
for bldconfig in ('--onedir', '--onefile'):
for console in consoleopts:
for dbg in ('--debug', ''):
for stripopt in stripopts:
if not args or i in args:
build_test(i, bldconfig, console, dbg, stripopt, **opts.__dict__)
i += 1
| mit |
tquilian/exelearningTest | tools/po2json.py | 11 | 10686 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''Transecma is a Python solution for javascript internationalization,
written in 2012 by Nando Florestan.
Babel already has a javascript extractor (a function that goes through
javascript code finding translation strings and writing them to a
.POT translation template file).
In this module there is a jquery template extractor, so if you use jquery
templates, they can be internationalized using traditional gettext tools.
The .pot file can be converted to .po files using Babel or GNU gettext.
Each of these .po files is to contain a translation to one language.
These .po files are edited by translators in special utilities such as
*poedit* or *gtranslator*.
This module also contains po2json, a command that converts .po
translation files into javascript files, so the translation may finally
happen on the client, in a browser, through javascript code.
The final part of the solution is transecma.js, a javascript file that
contains functions to perform translations based on the
translation dictionary discussed above, as well as interpolate them
with values from your application.
So how do I set this up?
========================
In your javascript files and jquery template files, mark some strings for
internationalization::
alert(_("This is supposed to be translated."));
// You may use tr() and gettext() in addition to _().
Install bag and Babel::
easy_install -UZ bag Babel
In the locale/ directory of your web application, add a "js_mapping.conf"
file with contents like these::
[javascript: **.js]
[jquery_templates: **.tmpl.html]
The above tells Babel what extractor to use for what file extensions.
Now we start using pybabel according to
http://babel.edgewall.org/wiki/Documentation/0.9/cmdline.html
Refer to the above documentation in order to understand the following
commands.
First use ``pybabel extract`` to generate a js.pot translation template file::
pybabel extract -k tr --omit-header --sort-by-file
-F app/locale/js_mapping.conf -o app/locale/js.pot app/static/js/
(If you are using Pyramid, this is similar to ``setup.py extract_messages``,
however it focuses on javascript and creates a separate .pot file.)
Now and then you may create a new translation. Example for Portuguese::
pybabel init -l pt -D js -i app/locale/js.pot -d app/locale/
You will frequently use ``pybabel update`` to refresh the translations
based on new .pot contents::
pybabel update -D js -i app/locale/js.pot -d app/locale/
(This is similar to ``setup.py update_catalog``.)
Now you can use tools such as gtranslator or poedit to fill in the .po
translation files::
gtranslator app/locale/pt/LC_MESSAGES/js.po
Finally use the ``po2json`` command (available if you installed
the *bag* package) to "compile" translations into .js files::
po2json -i -d app/locale -o app/static/js/i18n/
(This is similar to ``setup.py compile_catalog``.)
Transecma does *not* help you with the problem of adding to your pages
a <script> tag that loads the javascript file that contains the translations
that correspond to your user's locale. This problem depends on which
web framework you are using, but it should be very easy to solve.
Here is an example using Pyramid and Genshi:
.. code-block:: html
<script py:if="not locale_code.startswith('en')" type='text/javascript'
src="${static_url('static/js/i18n/{}.js'.format(locale_code))}"
></script>
<script py:if="locale_code.startswith('en')" type='text/javascript'
src="${static_url('static/js/i18n/transecma.js')}"></script>
In the above example, we assume the default language of the application
is English. So, for languages other than English, we load the
corresponding translations file (which may include the transecma library).
For English, we only load the library itself, otherwise we would miss
its functions, especially interpol().
'''
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os
import re
here = os.path.abspath(os.path.dirname(__file__))
def exists(path):
'''Test whether a path exists. Returns False for broken symbolic links.'''
try:
os.stat(path)
except os.error:
return False
return True
def extract_jquery_templates(fileobj, keywords, comment_tags, options):
'''Extracts translation messages from query template files.
This is a plugin to Babel, written according to
http://babel.edgewall.org/wiki/Documentation/0.9/messages.html#writing-extraction-methods
:param fileobj: the file-like object the messages should be extracted
from
:param keywords: a list of keywords (i.e. function names) that should
be recognized as translation functions
:param comment_tags: a list of translator tags to search for and
include in the results
:param options: a dictionary of additional options (optional)
:return: an iterator over ``(lineno, funcname, message, comments)``
tuples
:rtype: ``iterator``
'''
# print('Keywords: {}. Options: {}'.format(keywords, options))
encoding = options.get('encoding', 'utf-8')
comments = []
funcname = message = None
def new_regex(keyword, quote):
# TODO: Allow plural messages, too
return re.compile(
keyword + \
"\(" + # open parentheses to call function
quote + # string start
# TODO: Allow an escaped quote:
"([^" + quote + "]+)" + # capture: anything but a quote
quote + # string end
"\)" # close parentheses (function call)
)
rx = []
for keyword in keywords:
rx.append(new_regex(keyword, '"'))
rx.append(new_regex(keyword, "'"))
# We have compiled our regular expressions, so now use them on the file
for lineno, line in enumerate(fileobj, 1):
line = line.decode(encoding)
for r in rx:
for match in r.finditer(line):
yield (lineno, funcname, match.group(1), comments)
def po2dict(stream, locale, use_fuzzy=False):
'''Given a *stream* (a file-like object) and a locale, returns a
dictionary of the message IDs and translation strings.
'''
from babel.messages.pofile import read_po
catalog = read_po(stream, locale)
messages = [m for m in catalog if m.string]
if not use_fuzzy:
messages[1:] = [m for m in messages[1:] if not m.fuzzy]
messages.sort()
return {message.id: message.string for message in messages}
def make_json(structure, variable_name=None, indent=1, **k):
'''Converts something into a json string, optionally attributing the result
to a variable.
It also escapes the forward slash, making the result suitable
to be included in an HTML <script> tag.
'''
import json
s = json.dumps(structure, indent=indent, **k).replace('/', '\/')
return "{0} = {1};\n".format(variable_name, s) if variable_name \
else s
def po2json(po_path, locale, variable_name=None, use_fuzzy=None):
'''Compiles one .po file into JSON and returns the resulting string.'''
with open(po_path) as file:
d = po2dict(file, locale, use_fuzzy=use_fuzzy)
return make_json(d, variable_name=variable_name)
def compile_dir(dir, domain, out_dir, variable_name=None, use_fuzzy=None,
encoding='utf8', include_lib=False):
'''Given a *dir*, goes through all locale subdirectories in it,
reads the .po translation files pertaining to *domain*, and then converts
the translations to javascript files, which are written out to the
directory *out_dir* and assigned to a *variable_name*.
If *include_lib* is True, the contents of transecma.js are appended to
the end of each of the output files.
'''
import codecs
if include_lib:
with codecs.open(os.path.join(here, 'transecma.js'),
encoding='utf8') as f:
lib = f.read()
else:
lib = ''
jobs = []
if not exists(out_dir):
os.makedirs(out_dir)
for locale in os.listdir(dir):
po_path = os.path.join(dir, locale, 'LC_MESSAGES', domain + '.po')
#po_path = os.path.join(dir, locale, domain + '_' + locale + '.po')
if os.path.exists(po_path):
out_path = os.path.join(out_dir, locale + '.js')
jobs.append((locale, po_path, out_path))
for locale, po_path, out_path in jobs:
print(' Creating {0}'.format(out_path))
s = po2json(po_path, locale, variable_name=variable_name,
use_fuzzy=use_fuzzy)
with codecs.open(out_path, 'w', encoding=encoding) as writer:
writer.write(s)
if include_lib:
writer.write('\n')
writer.write(lib)
def po2json_command():
'''This function is an entry point; it is turned into a console script
when the package is installed.
po2json is a command that converts .PO translation files into javascript
JSON files. This is a step in web application internationalization.
Example usage::
po2json -i -d $OUTDIR -o $JS_DIR
For help with the arguments, type::
po2json -h
'''
from argparse import ArgumentParser
p = ArgumentParser(description='Converts .po files into .js files ' \
'for web application internationalization.')
p.add_argument('--domain', '-D', dest='domain', default='js',
help="domain of PO files (default '%(default)s')")
p.add_argument('--directory', '-d', dest='dir',
metavar='DIR', help='base directory of catalog files')
p.add_argument('--output-dir', '-o', dest='out_dir', metavar='DIR',
help="name of the output directory for .js files")
p.add_argument('--use-fuzzy', '-f', dest='use_fuzzy', action='store_true',
default=False,
help='also include fuzzy translations (default %(default)s)')
p.add_argument('--variable', '-n', dest='variable_name',
default='translations',
help="javascript variable name for the translations object")
p.add_argument('--include-lib', '-i', dest='include_lib', default=False,
action='store_true', help='include transecma.js in the output')
d = p.parse_args()
if not d.dir:
p.print_usage()
return
compile_dir(d.dir, d.domain, d.out_dir, variable_name=d.variable_name,
use_fuzzy=d.use_fuzzy, include_lib=d.include_lib)
if __name__ == '__main__':
po2json_command()
| gpl-2.0 |
googleinterns/learnbase | learnbase/src/main/webapp/WEB-INF/Lib/unittest/test/test_suite.py | 111 | 12069 | import unittest
import sys
from .support import LoggingResult, TestEquality
### Support code for Test_TestSuite
################################################################
class Test(object):
class Foo(unittest.TestCase):
def test_1(self): pass
def test_2(self): pass
def test_3(self): pass
def runTest(self): pass
def _mk_TestSuite(*names):
return unittest.TestSuite(Test.Foo(n) for n in names)
################################################################
class Test_TestSuite(unittest.TestCase, TestEquality):
### Set up attributes needed by inherited tests
################################################################
# Used by TestEquality.test_eq
eq_pairs = [(unittest.TestSuite(), unittest.TestSuite()),
(unittest.TestSuite(), unittest.TestSuite([])),
(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]
# Used by TestEquality.test_ne
ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1')),
(unittest.TestSuite([]), _mk_TestSuite('test_1')),
(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3')),
(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]
################################################################
### /Set up attributes needed by inherited tests
### Tests for TestSuite.__init__
################################################################
# "class TestSuite([tests])"
#
# The tests iterable should be optional
def test_init__tests_optional(self):
suite = unittest.TestSuite()
self.assertEqual(suite.countTestCases(), 0)
# "class TestSuite([tests])"
# ...
# "If tests is given, it must be an iterable of individual test cases
# or other test suites that will be used to build the suite initially"
#
# TestSuite should deal with empty tests iterables by allowing the
# creation of an empty suite
def test_init__empty_tests(self):
suite = unittest.TestSuite([])
self.assertEqual(suite.countTestCases(), 0)
# "class TestSuite([tests])"
# ...
# "If tests is given, it must be an iterable of individual test cases
# or other test suites that will be used to build the suite initially"
#
# TestSuite should allow any iterable to provide tests
def test_init__tests_from_any_iterable(self):
def tests():
yield unittest.FunctionTestCase(lambda: None)
yield unittest.FunctionTestCase(lambda: None)
suite_1 = unittest.TestSuite(tests())
self.assertEqual(suite_1.countTestCases(), 2)
suite_2 = unittest.TestSuite(suite_1)
self.assertEqual(suite_2.countTestCases(), 2)
suite_3 = unittest.TestSuite(set(suite_1))
self.assertEqual(suite_3.countTestCases(), 2)
# "class TestSuite([tests])"
# ...
# "If tests is given, it must be an iterable of individual test cases
# or other test suites that will be used to build the suite initially"
#
# Does TestSuite() also allow other TestSuite() instances to be present
# in the tests iterable?
def test_init__TestSuite_instances_in_tests(self):
def tests():
ftc = unittest.FunctionTestCase(lambda: None)
yield unittest.TestSuite([ftc])
yield unittest.FunctionTestCase(lambda: None)
suite = unittest.TestSuite(tests())
self.assertEqual(suite.countTestCases(), 2)
################################################################
### /Tests for TestSuite.__init__
# Container types should support the iter protocol
def test_iter(self):
test1 = unittest.FunctionTestCase(lambda: None)
test2 = unittest.FunctionTestCase(lambda: None)
suite = unittest.TestSuite((test1, test2))
self.assertEqual(list(suite), [test1, test2])
# "Return the number of tests represented by the this test object.
# ...this method is also implemented by the TestSuite class, which can
# return larger [greater than 1] values"
#
# Presumably an empty TestSuite returns 0?
def test_countTestCases_zero_simple(self):
suite = unittest.TestSuite()
self.assertEqual(suite.countTestCases(), 0)
# "Return the number of tests represented by the this test object.
# ...this method is also implemented by the TestSuite class, which can
# return larger [greater than 1] values"
#
# Presumably an empty TestSuite (even if it contains other empty
# TestSuite instances) returns 0?
def test_countTestCases_zero_nested(self):
class Test1(unittest.TestCase):
def test(self):
pass
suite = unittest.TestSuite([unittest.TestSuite()])
self.assertEqual(suite.countTestCases(), 0)
# "Return the number of tests represented by the this test object.
# ...this method is also implemented by the TestSuite class, which can
# return larger [greater than 1] values"
def test_countTestCases_simple(self):
test1 = unittest.FunctionTestCase(lambda: None)
test2 = unittest.FunctionTestCase(lambda: None)
suite = unittest.TestSuite((test1, test2))
self.assertEqual(suite.countTestCases(), 2)
# "Return the number of tests represented by the this test object.
# ...this method is also implemented by the TestSuite class, which can
# return larger [greater than 1] values"
#
# Make sure this holds for nested TestSuite instances, too
def test_countTestCases_nested(self):
class Test1(unittest.TestCase):
def test1(self): pass
def test2(self): pass
test2 = unittest.FunctionTestCase(lambda: None)
test3 = unittest.FunctionTestCase(lambda: None)
child = unittest.TestSuite((Test1('test2'), test2))
parent = unittest.TestSuite((test3, child, Test1('test1')))
self.assertEqual(parent.countTestCases(), 4)
# "Run the tests associated with this suite, collecting the result into
# the test result object passed as result."
#
# And if there are no tests? What then?
def test_run__empty_suite(self):
events = []
result = LoggingResult(events)
suite = unittest.TestSuite()
suite.run(result)
self.assertEqual(events, [])
# "Note that unlike TestCase.run(), TestSuite.run() requires the
# "result object to be passed in."
def test_run__requires_result(self):
suite = unittest.TestSuite()
try:
suite.run()
except TypeError:
pass
else:
self.fail("Failed to raise TypeError")
# "Run the tests associated with this suite, collecting the result into
# the test result object passed as result."
def test_run(self):
events = []
result = LoggingResult(events)
class LoggingCase(unittest.TestCase):
def run(self, result):
events.append('run %s' % self._testMethodName)
def test1(self): pass
def test2(self): pass
tests = [LoggingCase('test1'), LoggingCase('test2')]
unittest.TestSuite(tests).run(result)
self.assertEqual(events, ['run test1', 'run test2'])
# "Add a TestCase ... to the suite"
def test_addTest__TestCase(self):
class Foo(unittest.TestCase):
def test(self): pass
test = Foo('test')
suite = unittest.TestSuite()
suite.addTest(test)
self.assertEqual(suite.countTestCases(), 1)
self.assertEqual(list(suite), [test])
# "Add a ... TestSuite to the suite"
def test_addTest__TestSuite(self):
class Foo(unittest.TestCase):
def test(self): pass
suite_2 = unittest.TestSuite([Foo('test')])
suite = unittest.TestSuite()
suite.addTest(suite_2)
self.assertEqual(suite.countTestCases(), 1)
self.assertEqual(list(suite), [suite_2])
# "Add all the tests from an iterable of TestCase and TestSuite
# instances to this test suite."
#
# "This is equivalent to iterating over tests, calling addTest() for
# each element"
def test_addTests(self):
class Foo(unittest.TestCase):
def test_1(self): pass
def test_2(self): pass
test_1 = Foo('test_1')
test_2 = Foo('test_2')
inner_suite = unittest.TestSuite([test_2])
def gen():
yield test_1
yield test_2
yield inner_suite
suite_1 = unittest.TestSuite()
suite_1.addTests(gen())
self.assertEqual(list(suite_1), list(gen()))
# "This is equivalent to iterating over tests, calling addTest() for
# each element"
suite_2 = unittest.TestSuite()
for t in gen():
suite_2.addTest(t)
self.assertEqual(suite_1, suite_2)
# "Add all the tests from an iterable of TestCase and TestSuite
# instances to this test suite."
#
# What happens if it doesn't get an iterable?
def test_addTest__noniterable(self):
suite = unittest.TestSuite()
try:
suite.addTests(5)
except TypeError:
pass
else:
self.fail("Failed to raise TypeError")
def test_addTest__noncallable(self):
suite = unittest.TestSuite()
self.assertRaises(TypeError, suite.addTest, 5)
def test_addTest__casesuiteclass(self):
suite = unittest.TestSuite()
self.assertRaises(TypeError, suite.addTest, Test_TestSuite)
self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)
def test_addTests__string(self):
suite = unittest.TestSuite()
self.assertRaises(TypeError, suite.addTests, "foo")
def test_function_in_suite(self):
def f(_):
pass
suite = unittest.TestSuite()
suite.addTest(f)
# when the bug is fixed this line will not crash
suite.run(unittest.TestResult())
def test_basetestsuite(self):
class Test(unittest.TestCase):
wasSetUp = False
wasTornDown = False
@classmethod
def setUpClass(cls):
cls.wasSetUp = True
@classmethod
def tearDownClass(cls):
cls.wasTornDown = True
def testPass(self):
pass
def testFail(self):
fail
class Module(object):
wasSetUp = False
wasTornDown = False
@staticmethod
def setUpModule():
Module.wasSetUp = True
@staticmethod
def tearDownModule():
Module.wasTornDown = True
Test.__module__ = 'Module'
sys.modules['Module'] = Module
self.addCleanup(sys.modules.pop, 'Module')
suite = unittest.BaseTestSuite()
suite.addTests([Test('testPass'), Test('testFail')])
self.assertEqual(suite.countTestCases(), 2)
result = unittest.TestResult()
suite.run(result)
self.assertFalse(Module.wasSetUp)
self.assertFalse(Module.wasTornDown)
self.assertFalse(Test.wasSetUp)
self.assertFalse(Test.wasTornDown)
self.assertEqual(len(result.errors), 1)
self.assertEqual(len(result.failures), 0)
self.assertEqual(result.testsRun, 2)
def test_overriding_call(self):
class MySuite(unittest.TestSuite):
called = False
def __call__(self, *args, **kw):
self.called = True
unittest.TestSuite.__call__(self, *args, **kw)
suite = MySuite()
result = unittest.TestResult()
wrapper = unittest.TestSuite()
wrapper.addTest(suite)
wrapper(result)
self.assertTrue(suite.called)
# reusing results should be permitted even if abominable
self.assertFalse(result._testRunEntered)
if __name__ == '__main__':
unittest.main()
| apache-2.0 |
sestrella/ansible | lib/ansible/modules/network/junos/junos_l2_interfaces.py | 20 | 9497 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2019 Red Hat
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#############################################
# WARNING #
#############################################
#
# This file is auto generated by the resource
# module builder playbook.
#
# Do not edit this file manually.
#
# Changes to this file will be over written
# by the resource module builder.
#
# Changes should be made in the model used to
# generate this file or in the resource module
# builder template.
#
#############################################
"""
The module file for junos_l2_interfaces
"""
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'
}
DOCUMENTATION = """
---
module: junos_l2_interfaces
version_added: 2.9
short_description: Manage Layer-2 interface on Juniper JUNOS devices
description: This module provides declarative management of a Layer-2 interface on Juniper JUNOS devices.
author: Ganesh Nalawade (@ganeshrn)
options:
config:
description: A dictionary of Layer-2 interface options
type: list
elements: dict
suboptions:
name:
description:
- Full name of interface, e.g. ge-0/0/1.
type: str
required: True
unit:
description:
- Logical interface number. Value of C(unit) should be of type
integer.
type: int
access:
description:
- Configure the interface as a Layer 2 access mode.
type: dict
suboptions:
vlan:
description:
- Configure the access VLAN ID.
type: str
trunk:
description:
- Configure the interface as a Layer 2 trunk mode.
type: dict
suboptions:
allowed_vlans:
description:
- List of VLANs to be configured in trunk port. It's used as the VLAN range to ADD or
REMOVE from the trunk.
type: list
native_vlan:
description:
- Native VLAN to be configured in trunk port. It is used as the trunk native VLAN ID.
type: str
enhanced_layer:
description:
- True if your device has Enhanced Layer 2 Software (ELS). If the l2 configuration is under
C(interface-mode) the value is True else if the l2 configuration is under C(port-mode) value
is False
type: bool
state:
choices:
- merged
- replaced
- overridden
- deleted
default: merged
description:
- The state of the configuration after module completion
type: str
requirements:
- ncclient (>=v0.6.4)
notes:
- This module requires the netconf system service be enabled on
the remote device being managed.
- Tested against vSRX JUNOS version 18.4R1.
- This module works with connection C(netconf). See L(the Junos OS Platform Options,../network/user_guide/platform_junos.html).
"""
EXAMPLES = """
# Using deleted
# Before state:
# -------------
#
# ansible@junos01# show interfaces
# ge-0/0/1 {
# description "L2 interface";
# speed 1g;
# unit 0 {
# family ethernet-switching {
# interface-mode access;
# vlan {
# members vlan30;
# }
# }
# }
#}
#ge-0/0/2 {
# description "non L2 interface";
# unit 0 {
# family inet {
# address 192.168.56.14/24;
# }
# }
- name: "Delete L2 attributes of given interfaces (Note: This won't delete the interface itself)."
junos_l2_interfaces:
config:
- name: ge-0/0/1
- name: ge-0/0/2
state: deleted
# After state:
# ------------
#
# ansible@junos01# show interfaces
# ge-0/0/1 {
# description "L2 interface";
# speed 1g;
# }
#ge-0/0/2 {
# description "non L2 interface";
# unit 0 {
# family inet {
# address 192.168.56.14/24;
# }
# }
# Using merged
# Before state:
# -------------
# ansible@junos01# show interfaces
# ge-0/0/3 {
# description "test interface";
# speed 1g;
#}
# ge-0/0/4 {
# description interface-trunk;
# native-vlan-id 100;
# unit 0 {
# family ethernet-switching {
# interface-mode trunk;
# vlan {
# members [ vlan40 ];
# }
# }
# }
# }
- name: "Merge provided configuration with device configuration (default operation is merge)"
junos_l2_interfaces:
config:
- name: ge-0/0/3
access:
vlan: v101
- name: ge-0/0/4
trunk:
allowed_vlans:
- vlan30
native_vlan: 50
state: merged
# After state:
# ------------
# user@junos01# show interfaces
# ge-0/0/3 {
# description "test interface";
# speed 1g;
# unit 0 {
# family ethernet-switching {
# interface-mode access;
# vlan {
# members v101;
# }
# }
# }
# }
# ge-0/0/4 {
# description interface-trunk;
# native-vlan-id 50;
# unit 0 {
# family ethernet-switching {
# interface-mode trunk;
# vlan {
# members [ vlan40 vlan30 ];
# }
# }
# }
# }
# Using overridden
# Before state:
# -------------
# ansible@junos01# show interfaces
# ge-0/0/3 {
# description "test interface";
# speed 1g;
#}
# ge-0/0/4 {
# description interface-trunk;
# native-vlan-id 100;
# unit 0 {
# family ethernet-switching {
# interface-mode trunk;
# vlan {
# members [ vlan40 ];
# }
# }
# }
# }
# ge-0/0/5 {
# description "Configured by Ansible-11";
# unit 0 {
# family ethernet-switching {
# interface-mode access;
# vlan {
# members v101;
# }
# }
# }
# }
- name: "Override provided configuration with device configuration"
junos_l2_interfaces:
config:
- name: ge-0/0/3
access:
vlan: v101
- name: ge-0/0/4
trunk:
allowed_vlans:
- vlan30
native_vlan: 50
state: overridden
# After state:
# ------------
# user@junos01# show interfaces
# ge-0/0/3 {
# unit 0 {
# family ethernet-switching {
# interface-mode access;
# vlan {
# members v101;
# }
# }
# }
# }
# ge-0/0/4 {
# description interface-trunk;
# native-vlan-id 50;
# unit 0 {
# family ethernet-switching {
# interface-mode trunk;
# vlan {
# members [ vlan30 ];
# }
# }
# }
# }
# Using replaced
# Before state:
# -------------
# ansible@junos01# show interfaces
# ge-0/0/3 {
# description "test interface";
# speed 1g;
#}
# ge-0/0/4 {
# description interface-trunk;
# native-vlan-id 100;
# unit 0 {
# family ethernet-switching {
# interface-mode trunk;
# vlan {
# members [ vlan40 ];
# }
# }
# }
# }
- name: "Replace provided configuration with device configuration"
junos_l2_interfaces:
config:
- name: ge-0/0/3
access:
vlan: v101
- name: ge-0/0/4
trunk:
allowed_vlans:
- vlan30
native_vlan: 50
state: replaced
# After state:
# ------------
# user@junos01# show interfaces
# ge-0/0/3 {
# unit 0 {
# family ethernet-switching {
# interface-mode access;
# vlan {
# members v101;
# }
# }
# }
# }
# ge-0/0/4 {
# description interface-trunk;
# native-vlan-id 50;
# unit 0 {
# family ethernet-switching {
# interface-mode trunk;
# vlan {
# members [ vlan30 ];
# }
# }
# }
# }
"""
RETURN = """
before:
description: The configuration as structured data prior to module invocation.
returned: always
type: list
sample: >
The configuration returned will always be in the same format
of the parameters above.
after:
description: The configuration as structured data after module completion.
returned: when changed
type: list
sample: >
The configuration returned will always be in the same format
of the parameters above.
commands:
description: The set of commands pushed to the remote device.
returned: always
type: list
sample: ['command 1', 'command 2', 'command 3']
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.junos.argspec.l2_interfaces.l2_interfaces import L2_interfacesArgs
from ansible.module_utils.network.junos.config.l2_interfaces.l2_interfaces import L2_interfaces
def main():
"""
Main entry point for module execution
:returns: the result form module invocation
"""
required_if = [('state', 'merged', ('config',)),
('state', 'replaced', ('config',)),
('state', 'overridden', ('config',))]
module = AnsibleModule(argument_spec=L2_interfacesArgs.argument_spec,
required_if=required_if,
supports_check_mode=True)
result = L2_interfaces(module).execute_module()
module.exit_json(**result)
if __name__ == '__main__':
main()
| gpl-3.0 |
teeple/pns_server | work/install/Python-2.7.4/Parser/asdl.py | 10 | 11320 | """An implementation of the Zephyr Abstract Syntax Definition Language.
See http://asdl.sourceforge.net/ and
http://www.cs.princeton.edu/research/techreps/TR-554-97
Only supports top level module decl, not view. I'm guessing that view
is intended to support the browser and I'm not interested in the
browser.
Changes for Python: Add support for module versions
"""
import os
import traceback
import spark
class Token(object):
# spark seems to dispatch in the parser based on a token's
# type attribute
def __init__(self, type, lineno):
self.type = type
self.lineno = lineno
def __str__(self):
return self.type
def __repr__(self):
return str(self)
class Id(Token):
def __init__(self, value, lineno):
self.type = 'Id'
self.value = value
self.lineno = lineno
def __str__(self):
return self.value
class String(Token):
def __init__(self, value, lineno):
self.type = 'String'
self.value = value
self.lineno = lineno
class ASDLSyntaxError(Exception):
def __init__(self, lineno, token=None, msg=None):
self.lineno = lineno
self.token = token
self.msg = msg
def __str__(self):
if self.msg is None:
return "Error at '%s', line %d" % (self.token, self.lineno)
else:
return "%s, line %d" % (self.msg, self.lineno)
class ASDLScanner(spark.GenericScanner, object):
def tokenize(self, input):
self.rv = []
self.lineno = 1
super(ASDLScanner, self).tokenize(input)
return self.rv
def t_id(self, s):
r"[\w\.]+"
# XXX doesn't distinguish upper vs. lower, which is
# significant for ASDL.
self.rv.append(Id(s, self.lineno))
def t_string(self, s):
r'"[^"]*"'
self.rv.append(String(s, self.lineno))
def t_xxx(self, s): # not sure what this production means
r"<="
self.rv.append(Token(s, self.lineno))
def t_punctuation(self, s):
r"[\{\}\*\=\|\(\)\,\?\:]"
self.rv.append(Token(s, self.lineno))
def t_comment(self, s):
r"\-\-[^\n]*"
pass
def t_newline(self, s):
r"\n"
self.lineno += 1
def t_whitespace(self, s):
r"[ \t]+"
pass
def t_default(self, s):
r" . +"
raise ValueError, "unmatched input: %s" % `s`
class ASDLParser(spark.GenericParser, object):
def __init__(self):
super(ASDLParser, self).__init__("module")
def typestring(self, tok):
return tok.type
def error(self, tok):
raise ASDLSyntaxError(tok.lineno, tok)
def p_module_0(self, (module, name, version, _0, _1)):
" module ::= Id Id version { } "
if module.value != "module":
raise ASDLSyntaxError(module.lineno,
msg="expected 'module', found %s" % module)
return Module(name, None, version)
def p_module(self, (module, name, version, _0, definitions, _1)):
" module ::= Id Id version { definitions } "
if module.value != "module":
raise ASDLSyntaxError(module.lineno,
msg="expected 'module', found %s" % module)
return Module(name, definitions, version)
def p_version(self, (version, V)):
"version ::= Id String"
if version.value != "version":
raise ASDLSyntaxError(version.lineno,
msg="expected 'version', found %" % version)
return V
def p_definition_0(self, (definition,)):
" definitions ::= definition "
return definition
def p_definition_1(self, (definitions, definition)):
" definitions ::= definition definitions "
return definitions + definition
def p_definition(self, (id, _, type)):
" definition ::= Id = type "
return [Type(id, type)]
def p_type_0(self, (product,)):
" type ::= product "
return product
def p_type_1(self, (sum,)):
" type ::= sum "
return Sum(sum)
def p_type_2(self, (sum, id, _0, attributes, _1)):
" type ::= sum Id ( fields ) "
if id.value != "attributes":
raise ASDLSyntaxError(id.lineno,
msg="expected attributes, found %s" % id)
if attributes:
attributes.reverse()
return Sum(sum, attributes)
def p_product(self, (_0, fields, _1)):
" product ::= ( fields ) "
# XXX can't I just construct things in the right order?
fields.reverse()
return Product(fields)
def p_sum_0(self, (constructor,)):
" sum ::= constructor "
return [constructor]
def p_sum_1(self, (constructor, _, sum)):
" sum ::= constructor | sum "
return [constructor] + sum
def p_sum_2(self, (constructor, _, sum)):
" sum ::= constructor | sum "
return [constructor] + sum
def p_constructor_0(self, (id,)):
" constructor ::= Id "
return Constructor(id)
def p_constructor_1(self, (id, _0, fields, _1)):
" constructor ::= Id ( fields ) "
# XXX can't I just construct things in the right order?
fields.reverse()
return Constructor(id, fields)
def p_fields_0(self, (field,)):
" fields ::= field "
return [field]
def p_fields_1(self, (field, _, fields)):
" fields ::= field , fields "
return fields + [field]
def p_field_0(self, (type,)):
" field ::= Id "
return Field(type)
def p_field_1(self, (type, name)):
" field ::= Id Id "
return Field(type, name)
def p_field_2(self, (type, _, name)):
" field ::= Id * Id "
return Field(type, name, seq=True)
def p_field_3(self, (type, _, name)):
" field ::= Id ? Id "
return Field(type, name, opt=True)
def p_field_4(self, (type, _)):
" field ::= Id * "
return Field(type, seq=True)
def p_field_5(self, (type, _)):
" field ::= Id ? "
return Field(type, opt=True)
builtin_types = ("identifier", "string", "int", "bool", "object")
# below is a collection of classes to capture the AST of an AST :-)
# not sure if any of the methods are useful yet, but I'm adding them
# piecemeal as they seem helpful
class AST(object):
pass # a marker class
class Module(AST):
def __init__(self, name, dfns, version):
self.name = name
self.dfns = dfns
self.version = version
self.types = {} # maps type name to value (from dfns)
for type in dfns:
self.types[type.name.value] = type.value
def __repr__(self):
return "Module(%s, %s)" % (self.name, self.dfns)
class Type(AST):
def __init__(self, name, value):
self.name = name
self.value = value
def __repr__(self):
return "Type(%s, %s)" % (self.name, self.value)
class Constructor(AST):
def __init__(self, name, fields=None):
self.name = name
self.fields = fields or []
def __repr__(self):
return "Constructor(%s, %s)" % (self.name, self.fields)
class Field(AST):
def __init__(self, type, name=None, seq=False, opt=False):
self.type = type
self.name = name
self.seq = seq
self.opt = opt
def __repr__(self):
if self.seq:
extra = ", seq=True"
elif self.opt:
extra = ", opt=True"
else:
extra = ""
if self.name is None:
return "Field(%s%s)" % (self.type, extra)
else:
return "Field(%s, %s%s)" % (self.type, self.name, extra)
class Sum(AST):
def __init__(self, types, attributes=None):
self.types = types
self.attributes = attributes or []
def __repr__(self):
if self.attributes is None:
return "Sum(%s)" % self.types
else:
return "Sum(%s, %s)" % (self.types, self.attributes)
class Product(AST):
def __init__(self, fields):
self.fields = fields
def __repr__(self):
return "Product(%s)" % self.fields
class VisitorBase(object):
def __init__(self, skip=False):
self.cache = {}
self.skip = skip
def visit(self, object, *args):
meth = self._dispatch(object)
if meth is None:
return
try:
meth(object, *args)
except Exception, err:
print "Error visiting", repr(object)
print err
traceback.print_exc()
# XXX hack
if hasattr(self, 'file'):
self.file.flush()
os._exit(1)
def _dispatch(self, object):
assert isinstance(object, AST), repr(object)
klass = object.__class__
meth = self.cache.get(klass)
if meth is None:
methname = "visit" + klass.__name__
if self.skip:
meth = getattr(self, methname, None)
else:
meth = getattr(self, methname)
self.cache[klass] = meth
return meth
class Check(VisitorBase):
def __init__(self):
super(Check, self).__init__(skip=True)
self.cons = {}
self.errors = 0
self.types = {}
def visitModule(self, mod):
for dfn in mod.dfns:
self.visit(dfn)
def visitType(self, type):
self.visit(type.value, str(type.name))
def visitSum(self, sum, name):
for t in sum.types:
self.visit(t, name)
def visitConstructor(self, cons, name):
key = str(cons.name)
conflict = self.cons.get(key)
if conflict is None:
self.cons[key] = name
else:
print "Redefinition of constructor %s" % key
print "Defined in %s and %s" % (conflict, name)
self.errors += 1
for f in cons.fields:
self.visit(f, key)
def visitField(self, field, name):
key = str(field.type)
l = self.types.setdefault(key, [])
l.append(name)
def visitProduct(self, prod, name):
for f in prod.fields:
self.visit(f, name)
def check(mod):
v = Check()
v.visit(mod)
for t in v.types:
if t not in mod.types and not t in builtin_types:
v.errors += 1
uses = ", ".join(v.types[t])
print "Undefined type %s, used in %s" % (t, uses)
return not v.errors
def parse(file):
scanner = ASDLScanner()
parser = ASDLParser()
buf = open(file).read()
tokens = scanner.tokenize(buf)
try:
return parser.parse(tokens)
except ASDLSyntaxError, err:
print err
lines = buf.split("\n")
print lines[err.lineno - 1] # lines starts at 0, files at 1
if __name__ == "__main__":
import glob
import sys
if len(sys.argv) > 1:
files = sys.argv[1:]
else:
testdir = "tests"
files = glob.glob(testdir + "/*.asdl")
for file in files:
print file
mod = parse(file)
print "module", mod.name
print len(mod.dfns), "definitions"
if not check(mod):
print "Check failed"
else:
for dfn in mod.dfns:
print dfn.type
| gpl-2.0 |
chombourger/efup | external/nss/external_tests/google_test/gtest/test/gtest_xml_output_unittest.py | 1815 | 14580 | #!/usr/bin/env python
#
# Copyright 2006, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit test for the gtest_xml_output module"""
__author__ = 'eefacm@gmail.com (Sean Mcafee)'
import datetime
import errno
import os
import re
import sys
from xml.dom import minidom, Node
import gtest_test_utils
import gtest_xml_test_utils
GTEST_FILTER_FLAG = '--gtest_filter'
GTEST_LIST_TESTS_FLAG = '--gtest_list_tests'
GTEST_OUTPUT_FLAG = "--gtest_output"
GTEST_DEFAULT_OUTPUT_FILE = "test_detail.xml"
GTEST_PROGRAM_NAME = "gtest_xml_output_unittest_"
SUPPORTS_STACK_TRACES = False
if SUPPORTS_STACK_TRACES:
STACK_TRACE_TEMPLATE = '\nStack trace:\n*'
else:
STACK_TRACE_TEMPLATE = ''
EXPECTED_NON_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="23" failures="4" disabled="2" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42">
<testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*">
<testcase name="Succeeds" status="run" time="*" classname="SuccessfulTest"/>
</testsuite>
<testsuite name="FailedTest" tests="1" failures="1" disabled="0" errors="0" time="*">
<testcase name="Fails" status="run" time="*" classname="FailedTest">
<failure message="gtest_xml_output_unittest_.cc:*
Value of: 2
Expected: 1" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Value of: 2
Expected: 1%(stack)s]]></failure>
</testcase>
</testsuite>
<testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" errors="0" time="*">
<testcase name="Succeeds" status="run" time="*" classname="MixedResultTest"/>
<testcase name="Fails" status="run" time="*" classname="MixedResultTest">
<failure message="gtest_xml_output_unittest_.cc:*
Value of: 2
Expected: 1" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Value of: 2
Expected: 1%(stack)s]]></failure>
<failure message="gtest_xml_output_unittest_.cc:*
Value of: 3
Expected: 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Value of: 3
Expected: 2%(stack)s]]></failure>
</testcase>
<testcase name="DISABLED_test" status="notrun" time="*" classname="MixedResultTest"/>
</testsuite>
<testsuite name="XmlQuotingTest" tests="1" failures="1" disabled="0" errors="0" time="*">
<testcase name="OutputsCData" status="run" time="*" classname="XmlQuotingTest">
<failure message="gtest_xml_output_unittest_.cc:*
Failed
XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]></top>" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Failed
XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]>]]><![CDATA[</top>%(stack)s]]></failure>
</testcase>
</testsuite>
<testsuite name="InvalidCharactersTest" tests="1" failures="1" disabled="0" errors="0" time="*">
<testcase name="InvalidCharactersInMessage" status="run" time="*" classname="InvalidCharactersTest">
<failure message="gtest_xml_output_unittest_.cc:*
Failed
Invalid characters in brackets []" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Failed
Invalid characters in brackets []%(stack)s]]></failure>
</testcase>
</testsuite>
<testsuite name="DisabledTest" tests="1" failures="0" disabled="1" errors="0" time="*">
<testcase name="DISABLED_test_not_run" status="notrun" time="*" classname="DisabledTest"/>
</testsuite>
<testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" errors="0" time="*" SetUpTestCase="yes" TearDownTestCase="aye">
<testcase name="OneProperty" status="run" time="*" classname="PropertyRecordingTest" key_1="1"/>
<testcase name="IntValuedProperty" status="run" time="*" classname="PropertyRecordingTest" key_int="1"/>
<testcase name="ThreeProperties" status="run" time="*" classname="PropertyRecordingTest" key_1="1" key_2="2" key_3="3"/>
<testcase name="TwoValuesForOneKeyUsesLastValue" status="run" time="*" classname="PropertyRecordingTest" key_1="2"/>
</testsuite>
<testsuite name="NoFixtureTest" tests="3" failures="0" disabled="0" errors="0" time="*">
<testcase name="RecordProperty" status="run" time="*" classname="NoFixtureTest" key="1"/>
<testcase name="ExternalUtilityThatCallsRecordIntValuedProperty" status="run" time="*" classname="NoFixtureTest" key_for_utility_int="1"/>
<testcase name="ExternalUtilityThatCallsRecordStringValuedProperty" status="run" time="*" classname="NoFixtureTest" key_for_utility_string="1"/>
</testsuite>
<testsuite name="Single/ValueParamTest" tests="4" failures="0" disabled="0" errors="0" time="*">
<testcase name="HasValueParamAttribute/0" value_param="33" status="run" time="*" classname="Single/ValueParamTest" />
<testcase name="HasValueParamAttribute/1" value_param="42" status="run" time="*" classname="Single/ValueParamTest" />
<testcase name="AnotherTestThatHasValueParamAttribute/0" value_param="33" status="run" time="*" classname="Single/ValueParamTest" />
<testcase name="AnotherTestThatHasValueParamAttribute/1" value_param="42" status="run" time="*" classname="Single/ValueParamTest" />
</testsuite>
<testsuite name="TypedTest/0" tests="1" failures="0" disabled="0" errors="0" time="*">
<testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="TypedTest/0" />
</testsuite>
<testsuite name="TypedTest/1" tests="1" failures="0" disabled="0" errors="0" time="*">
<testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="TypedTest/1" />
</testsuite>
<testsuite name="Single/TypeParameterizedTestCase/0" tests="1" failures="0" disabled="0" errors="0" time="*">
<testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="Single/TypeParameterizedTestCase/0" />
</testsuite>
<testsuite name="Single/TypeParameterizedTestCase/1" tests="1" failures="0" disabled="0" errors="0" time="*">
<testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="Single/TypeParameterizedTestCase/1" />
</testsuite>
</testsuites>""" % {'stack': STACK_TRACE_TEMPLATE}
EXPECTED_FILTERED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="1" failures="0" disabled="0" errors="0" time="*"
timestamp="*" name="AllTests" ad_hoc_property="42">
<testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0"
errors="0" time="*">
<testcase name="Succeeds" status="run" time="*" classname="SuccessfulTest"/>
</testsuite>
</testsuites>"""
EXPECTED_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="0" failures="0" disabled="0" errors="0" time="*"
timestamp="*" name="AllTests">
</testsuites>"""
GTEST_PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME)
SUPPORTS_TYPED_TESTS = 'TypedTest' in gtest_test_utils.Subprocess(
[GTEST_PROGRAM_PATH, GTEST_LIST_TESTS_FLAG], capture_stderr=False).output
class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
"""
Unit test for Google Test's XML output functionality.
"""
# This test currently breaks on platforms that do not support typed and
# type-parameterized tests, so we don't run it under them.
if SUPPORTS_TYPED_TESTS:
def testNonEmptyXmlOutput(self):
"""
Runs a test program that generates a non-empty XML output, and
tests that the XML output is expected.
"""
self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY_XML, 1)
def testEmptyXmlOutput(self):
"""Verifies XML output for a Google Test binary without actual tests.
Runs a test program that generates an empty XML output, and
tests that the XML output is expected.
"""
self._TestXmlOutput('gtest_no_test_unittest', EXPECTED_EMPTY_XML, 0)
def testTimestampValue(self):
"""Checks whether the timestamp attribute in the XML output is valid.
Runs a test program that generates an empty XML output, and checks if
the timestamp attribute in the testsuites tag is valid.
"""
actual = self._GetXmlOutput('gtest_no_test_unittest', [], 0)
date_time_str = actual.documentElement.getAttributeNode('timestamp').value
# datetime.strptime() is only available in Python 2.5+ so we have to
# parse the expected datetime manually.
match = re.match(r'(\d+)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)', date_time_str)
self.assertTrue(
re.match,
'XML datettime string %s has incorrect format' % date_time_str)
date_time_from_xml = datetime.datetime(
year=int(match.group(1)), month=int(match.group(2)),
day=int(match.group(3)), hour=int(match.group(4)),
minute=int(match.group(5)), second=int(match.group(6)))
time_delta = abs(datetime.datetime.now() - date_time_from_xml)
# timestamp value should be near the current local time
self.assertTrue(time_delta < datetime.timedelta(seconds=600),
'time_delta is %s' % time_delta)
actual.unlink()
def testDefaultOutputFile(self):
"""
Confirms that Google Test produces an XML output file with the expected
default name if no name is explicitly specified.
"""
output_file = os.path.join(gtest_test_utils.GetTempDir(),
GTEST_DEFAULT_OUTPUT_FILE)
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(
'gtest_no_test_unittest')
try:
os.remove(output_file)
except OSError, e:
if e.errno != errno.ENOENT:
raise
p = gtest_test_utils.Subprocess(
[gtest_prog_path, '%s=xml' % GTEST_OUTPUT_FLAG],
working_dir=gtest_test_utils.GetTempDir())
self.assert_(p.exited)
self.assertEquals(0, p.exit_code)
self.assert_(os.path.isfile(output_file))
def testSuppressedXmlOutput(self):
"""
Tests that no XML file is generated if the default XML listener is
shut down before RUN_ALL_TESTS is invoked.
"""
xml_path = os.path.join(gtest_test_utils.GetTempDir(),
GTEST_PROGRAM_NAME + 'out.xml')
if os.path.isfile(xml_path):
os.remove(xml_path)
command = [GTEST_PROGRAM_PATH,
'%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path),
'--shut_down_xml']
p = gtest_test_utils.Subprocess(command)
if p.terminated_by_signal:
# p.signal is avalable only if p.terminated_by_signal is True.
self.assertFalse(
p.terminated_by_signal,
'%s was killed by signal %d' % (GTEST_PROGRAM_NAME, p.signal))
else:
self.assert_(p.exited)
self.assertEquals(1, p.exit_code,
"'%s' exited with code %s, which doesn't match "
'the expected exit code %s.'
% (command, p.exit_code, 1))
self.assert_(not os.path.isfile(xml_path))
def testFilteredTestXmlOutput(self):
"""Verifies XML output when a filter is applied.
Runs a test program that executes only some tests and verifies that
non-selected tests do not show up in the XML output.
"""
self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_FILTERED_TEST_XML, 0,
extra_args=['%s=SuccessfulTest.*' % GTEST_FILTER_FLAG])
def _GetXmlOutput(self, gtest_prog_name, extra_args, expected_exit_code):
"""
Returns the xml output generated by running the program gtest_prog_name.
Furthermore, the program's exit code must be expected_exit_code.
"""
xml_path = os.path.join(gtest_test_utils.GetTempDir(),
gtest_prog_name + 'out.xml')
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(gtest_prog_name)
command = ([gtest_prog_path, '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path)] +
extra_args)
p = gtest_test_utils.Subprocess(command)
if p.terminated_by_signal:
self.assert_(False,
'%s was killed by signal %d' % (gtest_prog_name, p.signal))
else:
self.assert_(p.exited)
self.assertEquals(expected_exit_code, p.exit_code,
"'%s' exited with code %s, which doesn't match "
'the expected exit code %s.'
% (command, p.exit_code, expected_exit_code))
actual = minidom.parse(xml_path)
return actual
def _TestXmlOutput(self, gtest_prog_name, expected_xml,
expected_exit_code, extra_args=None):
"""
Asserts that the XML document generated by running the program
gtest_prog_name matches expected_xml, a string containing another
XML document. Furthermore, the program's exit code must be
expected_exit_code.
"""
actual = self._GetXmlOutput(gtest_prog_name, extra_args or [],
expected_exit_code)
expected = minidom.parseString(expected_xml)
self.NormalizeXml(actual.documentElement)
self.AssertEquivalentNodes(expected.documentElement,
actual.documentElement)
expected.unlink()
actual.unlink()
if __name__ == '__main__':
os.environ['GTEST_STACK_TRACE_DEPTH'] = '1'
gtest_test_utils.Main()
| mpl-2.0 |
jeremiahmarks/sl4a | python/src/Lib/weakref.py | 62 | 10087 | """Weak reference support for Python.
This module is an implementation of PEP 205:
http://www.python.org/dev/peps/pep-0205/
"""
# Naming convention: Variables named "wr" are weak reference objects;
# they are called this instead of "ref" to avoid name collisions with
# the module-global ref() function imported from _weakref.
import UserDict
from _weakref import (
getweakrefcount,
getweakrefs,
ref,
proxy,
CallableProxyType,
ProxyType,
ReferenceType)
from exceptions import ReferenceError
ProxyTypes = (ProxyType, CallableProxyType)
__all__ = ["ref", "proxy", "getweakrefcount", "getweakrefs",
"WeakKeyDictionary", "ReferenceError", "ReferenceType", "ProxyType",
"CallableProxyType", "ProxyTypes", "WeakValueDictionary"]
class WeakValueDictionary(UserDict.UserDict):
"""Mapping class that references values weakly.
Entries in the dictionary will be discarded when no strong
reference to the value exists anymore
"""
# We inherit the constructor without worrying about the input
# dictionary; since it uses our .update() method, we get the right
# checks (if the other dictionary is a WeakValueDictionary,
# objects are unwrapped on the way out, and we always wrap on the
# way in).
def __init__(self, *args, **kw):
def remove(wr, selfref=ref(self)):
self = selfref()
if self is not None:
del self.data[wr.key]
self._remove = remove
UserDict.UserDict.__init__(self, *args, **kw)
def __getitem__(self, key):
o = self.data[key]()
if o is None:
raise KeyError, key
else:
return o
def __contains__(self, key):
try:
o = self.data[key]()
except KeyError:
return False
return o is not None
def has_key(self, key):
try:
o = self.data[key]()
except KeyError:
return False
return o is not None
def __repr__(self):
return "<WeakValueDictionary at %s>" % id(self)
def __setitem__(self, key, value):
self.data[key] = KeyedRef(value, self._remove, key)
def copy(self):
new = WeakValueDictionary()
for key, wr in self.data.items():
o = wr()
if o is not None:
new[key] = o
return new
def get(self, key, default=None):
try:
wr = self.data[key]
except KeyError:
return default
else:
o = wr()
if o is None:
# This should only happen
return default
else:
return o
def items(self):
L = []
for key, wr in self.data.items():
o = wr()
if o is not None:
L.append((key, o))
return L
def iteritems(self):
for wr in self.data.itervalues():
value = wr()
if value is not None:
yield wr.key, value
def iterkeys(self):
return self.data.iterkeys()
def __iter__(self):
return self.data.iterkeys()
def itervaluerefs(self):
"""Return an iterator that yields the weak references to the values.
The references are not guaranteed to be 'live' at the time
they are used, so the result of calling the references needs
to be checked before being used. This can be used to avoid
creating references that will cause the garbage collector to
keep the values around longer than needed.
"""
return self.data.itervalues()
def itervalues(self):
for wr in self.data.itervalues():
obj = wr()
if obj is not None:
yield obj
def popitem(self):
while 1:
key, wr = self.data.popitem()
o = wr()
if o is not None:
return key, o
def pop(self, key, *args):
try:
o = self.data.pop(key)()
except KeyError:
if args:
return args[0]
raise
if o is None:
raise KeyError, key
else:
return o
def setdefault(self, key, default=None):
try:
wr = self.data[key]
except KeyError:
self.data[key] = KeyedRef(default, self._remove, key)
return default
else:
return wr()
def update(self, dict=None, **kwargs):
d = self.data
if dict is not None:
if not hasattr(dict, "items"):
dict = type({})(dict)
for key, o in dict.items():
d[key] = KeyedRef(o, self._remove, key)
if len(kwargs):
self.update(kwargs)
def valuerefs(self):
"""Return a list of weak references to the values.
The references are not guaranteed to be 'live' at the time
they are used, so the result of calling the references needs
to be checked before being used. This can be used to avoid
creating references that will cause the garbage collector to
keep the values around longer than needed.
"""
return self.data.values()
def values(self):
L = []
for wr in self.data.values():
o = wr()
if o is not None:
L.append(o)
return L
class KeyedRef(ref):
"""Specialized reference that includes a key corresponding to the value.
This is used in the WeakValueDictionary to avoid having to create
a function object for each key stored in the mapping. A shared
callback object can use the 'key' attribute of a KeyedRef instead
of getting a reference to the key from an enclosing scope.
"""
__slots__ = "key",
def __new__(type, ob, callback, key):
self = ref.__new__(type, ob, callback)
self.key = key
return self
def __init__(self, ob, callback, key):
super(KeyedRef, self).__init__(ob, callback)
class WeakKeyDictionary(UserDict.UserDict):
""" Mapping class that references keys weakly.
Entries in the dictionary will be discarded when there is no
longer a strong reference to the key. This can be used to
associate additional data with an object owned by other parts of
an application without adding attributes to those objects. This
can be especially useful with objects that override attribute
accesses.
"""
def __init__(self, dict=None):
self.data = {}
def remove(k, selfref=ref(self)):
self = selfref()
if self is not None:
del self.data[k]
self._remove = remove
if dict is not None: self.update(dict)
def __delitem__(self, key):
del self.data[ref(key)]
def __getitem__(self, key):
return self.data[ref(key)]
def __repr__(self):
return "<WeakKeyDictionary at %s>" % id(self)
def __setitem__(self, key, value):
self.data[ref(key, self._remove)] = value
def copy(self):
new = WeakKeyDictionary()
for key, value in self.data.items():
o = key()
if o is not None:
new[o] = value
return new
def get(self, key, default=None):
return self.data.get(ref(key),default)
def has_key(self, key):
try:
wr = ref(key)
except TypeError:
return 0
return wr in self.data
def __contains__(self, key):
try:
wr = ref(key)
except TypeError:
return 0
return wr in self.data
def items(self):
L = []
for key, value in self.data.items():
o = key()
if o is not None:
L.append((o, value))
return L
def iteritems(self):
for wr, value in self.data.iteritems():
key = wr()
if key is not None:
yield key, value
def iterkeyrefs(self):
"""Return an iterator that yields the weak references to the keys.
The references are not guaranteed to be 'live' at the time
they are used, so the result of calling the references needs
to be checked before being used. This can be used to avoid
creating references that will cause the garbage collector to
keep the keys around longer than needed.
"""
return self.data.iterkeys()
def iterkeys(self):
for wr in self.data.iterkeys():
obj = wr()
if obj is not None:
yield obj
def __iter__(self):
return self.iterkeys()
def itervalues(self):
return self.data.itervalues()
def keyrefs(self):
"""Return a list of weak references to the keys.
The references are not guaranteed to be 'live' at the time
they are used, so the result of calling the references needs
to be checked before being used. This can be used to avoid
creating references that will cause the garbage collector to
keep the keys around longer than needed.
"""
return self.data.keys()
def keys(self):
L = []
for wr in self.data.keys():
o = wr()
if o is not None:
L.append(o)
return L
def popitem(self):
while 1:
key, value = self.data.popitem()
o = key()
if o is not None:
return o, value
def pop(self, key, *args):
return self.data.pop(ref(key), *args)
def setdefault(self, key, default=None):
return self.data.setdefault(ref(key, self._remove),default)
def update(self, dict=None, **kwargs):
d = self.data
if dict is not None:
if not hasattr(dict, "items"):
dict = type({})(dict)
for key, value in dict.items():
d[ref(key, self._remove)] = value
if len(kwargs):
self.update(kwargs)
| apache-2.0 |
dermoth/gramps | gramps/plugins/tool/check.py | 1 | 129149 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2007 Donald N. Allingham
# Copyright (C) 2008 Brian G. Matherly
# Copyright (C) 2010 Jakim Friant
# Copyright (C) 2011 Tim G L Lyons
# Copyright (C) 2012 Michiel D. Nauta
#
# 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
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
"""Tools/Database Repair/Check and Repair Database"""
# pylint: disable=too-many-statements,too-many-locals,too-many-branches
# pylint: disable=wrong-import-position,too-many-public-methods,no-self-use
# pylint: disable=too-many-arguments
# -------------------------------------------------------------------------
#
# python modules
#
# -------------------------------------------------------------------------
import os
from io import StringIO
from collections import defaultdict
import time
# ------------------------------------------------------------------------
#
# Set up logging
#
# ------------------------------------------------------------------------
import logging
# -------------------------------------------------------------------------
#
# gtk modules
#
# -------------------------------------------------------------------------
from gi.repository import Gtk
# -------------------------------------------------------------------------
#
# Gramps modules
#
# -------------------------------------------------------------------------
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
ngettext = glocale.translation.ngettext # else "nearby" comments are ignored
from gramps.gen.lib import (Citation, Event, EventType, Family, Media,
Name, Note, Person, Place, Repository, Source,
StyledText, Tag)
from gramps.gen.db import DbTxn, CLASS_TO_KEY_MAP
from gramps.gen.config import config
from gramps.gen.utils.id import create_id
from gramps.gen.utils.db import family_name
from gramps.gen.utils.unknown import make_unknown
from gramps.gen.utils.file import (media_path_full, find_file)
from gramps.gui.managedwindow import ManagedWindow
from gramps.gen.utils.file import create_checksum
from gramps.gui.plug import tool
from gramps.gui.dialog import OkDialog, MissingMediaDialog
from gramps.gen.display.name import displayer as _nd
from gramps.gui.glade import Glade
from gramps.gen.errors import HandleError
# table for handling control chars in notes.
# All except 09, 0A, 0D are replaced with space.
strip_dict = dict.fromkeys(list(range(9)) + list(range(11, 13)) +
list(range(14, 32)), " ")
class ProgressMeter:
def __init__(self, *args, **kwargs):
pass
def set_pass(self, *args):
pass
def step(self):
pass
def close(self):
pass
# -------------------------------------------------------------------------
#
# Low Level repair
#
# -------------------------------------------------------------------------
def cross_table_duplicates(db, uistate):
"""
Function to find the presence of identical handles that occur in different
database tables.
Assumes there are no intable duplicates, see low_level function.
:param db: the database to check
:type db: :class:`gen.db.read.DbBsddbRead`
:returns: the presence of cross table duplicate handles
:rtype: bool
"""
if uistate:
parent = uistate.window
else:
parent = None
progress = ProgressMeter(_('Checking Database'), '', parent=parent)
progress.set_pass(_('Looking for cross table duplicates'), 9)
logging.info('Looking for cross table duplicates')
total_nr_handles = 0
all_handles = set([])
for get_handles_func in [db.get_person_handles,
db.get_family_handles,
db.get_event_handles,
db.get_place_handles,
db.get_source_handles,
db.get_citation_handles,
db.get_media_handles,
db.get_repository_handles,
db.get_note_handles]:
handle_list = get_handles_func()
total_nr_handles += len(handle_list)
all_handles.update(handle_list)
progress.step()
progress.close()
num_errors = total_nr_handles - len(all_handles)
if num_errors == 0:
logging.info(' OK: No cross table duplicates')
else:
logging.warning(' FAIL: Found %d cross table duplicates',
num_errors)
return total_nr_handles > len(all_handles)
# -------------------------------------------------------------------------
#
# runTool
#
# -------------------------------------------------------------------------
class Check(tool.BatchTool):
def __init__(self, dbstate, user, options_class, name, callback=None):
uistate = user.uistate
tool.BatchTool.__init__(self, dbstate, user, options_class, name)
if self.fail:
return
cli = uistate is None
if uistate:
from gramps.gui.utils import ProgressMeter as PM
global ProgressMeter
ProgressMeter = PM
if self.db.readonly:
# TODO: split plugin in a check and repair part to support
# checking of a read only database
return
# The low-level repair is bypassing the transaction mechanism.
# As such, we run it before starting the transaction.
# We only do this for the dbdir backend.
if self.db.__class__.__name__ == 'DbBsddb':
if cross_table_duplicates(self.db, uistate):
CheckReport(uistate, _(
"Your Family Tree contains cross table duplicate handles."
"\n "
"This is bad and can be fixed by making a backup of your\n"
"Family Tree and importing that backup in an empty family"
"\n"
"tree. The rest of the checking is skipped, the Check and"
"\n"
"Repair tool should be run anew on this new Family Tree."),
cli)
return
with DbTxn(_("Check Integrity"), self.db, batch=True) as trans:
self.db.disable_signals()
checker = CheckIntegrity(dbstate, uistate, trans)
# start with empty objects, broken links can be corrected below
# then. This is done before fixing encoding and missing photos,
# since otherwise we will be trying to fix empty records which are
# then going to be deleted.
checker.cleanup_empty_objects()
checker.fix_encoding()
checker.fix_alt_place_names()
checker.fix_ctrlchars_in_notes()
checker.cleanup_missing_photos(cli)
checker.cleanup_deleted_name_formats()
prev_total = -1
total = 0
while prev_total != total:
prev_total = total
checker.check_for_broken_family_links()
checker.check_parent_relationships()
checker.cleanup_empty_families(cli)
checker.cleanup_duplicate_spouses()
total = checker.family_errors()
checker.fix_duplicated_grampsid()
checker.check_events()
checker.check_person_references()
checker.check_family_references()
checker.check_place_references()
checker.check_source_references()
checker.check_citation_references()
checker.check_media_references()
checker.check_repo_references()
checker.check_note_references()
checker.check_tag_references()
checker.check_checksum()
checker.check_media_sourceref()
# for bsddb the check_backlinks doesn't work in 'batch' mode because
# the table used for backlinks is closed.
with DbTxn(_("Check Backlink Integrity"), self.db,
batch=False) as checker.trans:
checker.check_backlinks()
# rebuilding reference maps needs to be done outside of a transaction
# to avoid nesting transactions.
if checker.bad_backlinks:
checker.progress.set_pass(_('Rebuilding reference maps...'), 6)
logging.info('Rebuilding reference maps...')
self.db.reindex_reference_map(checker.callback)
else:
logging.info(' OK: no backlink problems found')
self.db.enable_signals()
self.db.request_rebuild()
errs = checker.build_report(uistate)
if errs:
CheckReport(uistate, checker.text.getvalue(), cli)
# -------------------------------------------------------------------------
#
#
#
# -------------------------------------------------------------------------
class CheckIntegrity:
def __init__(self, dbstate, uistate, trans):
self.uistate = uistate
if self.uistate:
self.parent_window = self.uistate.window
else:
self.parent_window = None
self.db = dbstate.db
self.trans = trans
self.bad_photo = []
self.replaced_photo = []
self.removed_photo = []
self.empty_family = []
self.broken_links = []
self.duplicate_links = []
self.broken_parent_links = []
self.fam_rel = []
self.invalid_events = set()
self.invalid_birth_events = set()
self.invalid_death_events = set()
self.invalid_person_references = set()
self.invalid_family_references = set()
self.invalid_place_references = set()
self.invalid_source_references = set()
self.invalid_citation_references = set()
self.invalid_repo_references = set()
self.invalid_media_references = set()
self.invalid_note_references = set()
self.invalid_tag_references = set()
self.invalid_dates = []
self.removed_name_format = []
self.empty_objects = defaultdict(list)
self.replaced_sourceref = []
self.place_errors = 0
self.duplicated_gramps_ids = 0
self.bad_backlinks = 0
self.text = StringIO()
self.last_img_dir = config.get('behavior.addmedia-image-dir')
self.progress = ProgressMeter(_('Checking Database'), '',
parent=self.parent_window)
self.explanation = Note(_(
'Objects referenced by this note were referenced but '
'missing so that is why they have been created '
'when you ran Check and Repair on %s.') %
time.strftime('%x %X', time.localtime()))
self.explanation.set_handle(create_id())
def family_errors(self):
return (len(self.broken_parent_links) +
len(self.broken_links) +
len(self.empty_family) +
len(self.duplicate_links))
def cleanup_deleted_name_formats(self):
"""
Permanently remove deleted name formats from db.
When user deletes custom name format those are not removed only marked
as "inactive". This method does the cleanup of the name format table,
as well as fixes the display_as, sort_as values for each Name in the
db.
"""
self.progress.set_pass(_('Looking for invalid name format references'),
self.db.get_number_of_people())
logging.info('Looking for invalid name format references')
deleted_name_formats = [number for (number, name, dummy, act)
in self.db.name_formats if not act]
# remove the invalid references from all Name objects
for person_handle in self.db.get_person_handles():
person = self.db.get_person_from_handle(person_handle)
p_changed = False
name = person.get_primary_name()
if name.get_sort_as() in deleted_name_formats:
name.set_sort_as(Name.DEF)
p_changed = True
if name.get_display_as() in deleted_name_formats:
name.set_display_as(Name.DEF)
p_changed = True
if p_changed:
person.set_primary_name(name)
a_changed = False
name_list = []
for name in person.get_alternate_names():
if name.get_sort_as() in deleted_name_formats:
name.set_sort_as(Name.DEF)
a_changed = True
if name.get_display_as() in deleted_name_formats:
name.set_display_as(Name.DEF)
a_changed = True
name_list.append(name)
if a_changed:
person.set_alternate_names(name_list)
if p_changed or a_changed:
self.db.commit_person(person, self.trans)
self.removed_name_format.append(person_handle)
self.progress.step()
# update the custom name name format table
for number in deleted_name_formats:
_nd.del_name_format(number)
self.db.name_formats = _nd.get_name_format(only_custom=True,
only_active=False)
if len(self.removed_name_format) == 0:
logging.info(' OK: no invalid name formats found found')
def cleanup_duplicate_spouses(self):
self.progress.set_pass(_('Looking for duplicate spouses'),
self.db.get_number_of_people())
logging.info('Looking for duplicate spouses')
previous_errors = len(self.duplicate_links)
for handle in self.db.get_person_handles():
pers = self.db.get_person_from_handle(handle)
splist = pers.get_family_handle_list()
if len(splist) != len(set(splist)):
new_list = []
for value in splist:
if value not in new_list:
new_list.append(value)
self.duplicate_links.append((handle, value))
pers.set_family_handle_list(new_list)
self.db.commit_person(pers, self.trans)
self.progress.step()
if previous_errors == len(self.duplicate_links):
logging.info(' OK: no duplicate spouses found')
def fix_encoding(self):
self.progress.set_pass(_('Looking for character encoding errors'),
self.db.get_number_of_media())
logging.info('Looking for character encoding errors')
error_count = 0
for handle in self.db.get_media_handles():
data = self.db.get_raw_media_data(handle)
if not isinstance(data[2], str) or not isinstance(data[4], str):
obj = self.db.get_media_from_handle(handle)
if not isinstance(data[2], str):
obj.path = obj.path.decode('utf-8')
logging.warning(' FAIL: encoding error on media object '
'"%(gid)s" path "%(path)s"',
{'gid': obj.gramps_id, 'path': obj.path})
if not isinstance(data[4], str):
obj.desc = obj.desc.decode('utf-8')
logging.warning(' FAIL: encoding error on media object '
'"%(gid)s" description "%(desc)s"',
{'gid': obj.gramps_id, 'desc': obj.desc})
self.db.commit_media(obj, self.trans)
error_count += 1
# Once we are here, fix the mime string if not str
if not isinstance(data[3], str):
obj = self.db.get_media_from_handle(handle)
try:
if data[3] == str(data[3]):
obj.mime = str(data[3])
else:
obj.mime = ""
except:
obj.mime = ""
self.db.commit_media(obj, self.trans)
logging.warning(' FAIL: encoding error on media object '
'"%(desc)s" mime "%(mime)s"',
{'desc': obj.desc, 'mime': obj.mime})
error_count += 1
self.progress.step()
if error_count == 0:
logging.info(' OK: no encoding errors found')
def fix_ctrlchars_in_notes(self):
self.progress.set_pass(_('Looking for ctrl characters in notes'),
self.db.get_number_of_notes())
logging.info('Looking for ctrl characters in notes')
error_count = 0
for handle in self.db.get_note_handles():
note = self.db.get_note_from_handle(handle)
stext = note.get_styledtext()
old_text = str(stext)
new_text = old_text.translate(strip_dict)
if old_text != new_text:
logging.warning(' FAIL: control characters found in note'
' "%s"', note.get_gramps_id())
error_count += 1
# Commit only if ctrl char found.
note.set_styledtext(StyledText(text=new_text,
tags=stext.get_tags()))
self.db.commit_note(note, self.trans)
self.progress.step()
if error_count == 0:
logging.info(' OK: no ctrl characters in notes found')
def fix_alt_place_names(self):
"""
This scans all places and cleans up alternative names. It removes
Blank names, names that are duplicates of the primary name, and
duplicates in the alt_names list.
"""
self.progress.set_pass(_('Looking for bad alternate place names'),
self.db.get_number_of_places())
logging.info('Looking for bad alternate place names')
for handle in self.db.get_place_handles():
place = self.db.get_place_from_handle(handle)
fixed_alt_names = []
fixup = False
for name in place.get_alternative_names():
if not name.value or \
name == place.name or \
name in fixed_alt_names:
fixup = True
continue
fixed_alt_names.append(name)
if fixup:
place.set_alternative_names(fixed_alt_names)
self.db.commit_place(place, self.trans)
self.place_errors += 1
self.progress.step()
if self.place_errors == 0:
logging.info(' OK: no bad alternate places found')
else:
logging.info(' %d bad alternate places found and fixed',
self.place_errors)
def check_for_broken_family_links(self):
# Check persons referenced by the family objects
fhandle_list = self.db.get_family_handles()
self.progress.set_pass(_('Looking for broken family links'),
len(fhandle_list) +
self.db.get_number_of_people())
logging.info('Looking for broken family links')
previous_errors = len(self.broken_parent_links + self.broken_links)
for family_handle in fhandle_list:
family = self.db.get_family_from_handle(family_handle)
father_handle = family.get_father_handle()
mother_handle = family.get_mother_handle()
if father_handle:
try:
father = self.db.get_person_from_handle(father_handle)
except HandleError:
# The person referenced by the father handle does not exist
# in the database
# This is tested by TestcaseGenerator where the mother is
# "Broken6"
family.set_father_handle(None)
self.db.commit_family(family, self.trans)
self.broken_parent_links.append((father_handle,
family_handle))
logging.warning(" FAIL: family '%(fam_gid)s' "
"father handle '%(hand)s' does not exist",
{'fam_gid': family.gramps_id,
'hand': father_handle})
father_handle = None
if mother_handle:
try:
mother = self.db.get_person_from_handle(mother_handle)
except HandleError:
# The person referenced by the mother handle does not exist
# in the database
# This is tested by TestcaseGenerator where the mother is
# "Broken7"
family.set_mother_handle(None)
self.db.commit_family(family, self.trans)
self.broken_parent_links.append((mother_handle,
family_handle))
logging.warning(" FAIL: family '%(fam_gid)s' "
"mother handle '%(hand)s' does not exist",
{'fam_gid': family.gramps_id,
'hand': mother_handle})
mother_handle = None
if father_handle and father and \
family_handle not in father.get_family_handle_list():
# The referenced father has no reference back to the family
# This is tested by TestcaseGenerator where the father is
# "Broken1"
self.broken_parent_links.append((father_handle, family_handle))
father.add_family_handle(family_handle)
self.db.commit_person(father, self.trans)
logging.warning(" FAIL: family '%(fam_gid)s' father "
"'%(hand)s' does not refer back to the family",
{'fam_gid': family.gramps_id,
'hand': father_handle})
if mother_handle and mother and \
family_handle not in mother.get_family_handle_list():
# The referenced mother has no reference back to the family.
# This is tested by TestcaseGenerator where the father is
# "Broken4"
self.broken_parent_links.append((mother_handle, family_handle))
mother.add_family_handle(family_handle)
self.db.commit_person(mother, self.trans)
logging.warning(" FAIL: family '%(fam_gid)s' mother "
"'%(hand)s' does not refer back to the family",
{'fam_gid': family.gramps_id,
'hand': mother_handle})
for child_ref in family.get_child_ref_list():
child_handle = child_ref.ref
try:
child = self.db.get_person_from_handle(child_handle)
except HandleError:
# The person referenced by the child handle
# does not exist in the database
# This is tested by TestcaseGenerator where the father
# is "Broken20"
logging.warning(" FAIL: family '%(fam_gid)s' child "
"'%(hand)s' does not exist in the "
"database",
{'fam_gid': family.gramps_id,
'hand': child_handle})
family.remove_child_ref(child_ref)
self.db.commit_family(family, self.trans)
self.broken_links.append((child_handle, family_handle))
else:
if child_handle in [father_handle, mother_handle]:
# The child is one of the parents: impossible Remove
# such child from the family
# This is tested by TestcaseGenerator where the father
# is "Broken19"
logging.warning(" FAIL: family '%(fam_gid)s' "
"child '%(child_gid)s' is one of the "
"parents",
{'fam_gid': family.gramps_id,
'child_gid': child.gramps_id})
family.remove_child_ref(child_ref)
self.db.commit_family(family, self.trans)
self.broken_links.append((child_handle, family_handle))
continue
if family_handle == child.get_main_parents_family_handle():
continue
if family_handle not in \
child.get_parent_family_handle_list():
# The referenced child has no reference to the family
# This is tested by TestcaseGenerator where the father
# is "Broken8"
logging.warning(
" FAIL: family '%(fam_gid)s' "
"child '%(child_gid)s' has no reference"
" to the family. Reference added",
{'fam_gid': family.gramps_id,
'child_gid': child.gramps_id})
child.add_parent_family_handle(family_handle)
self.db.commit_person(child, self.trans)
new_ref_list = []
new_ref_handles = []
replace = False
for child_ref in family.get_child_ref_list():
child_handle = child_ref.ref
if child_handle in new_ref_handles:
replace = True
else:
new_ref_list.append(child_ref)
new_ref_handles.append(child_handle)
if replace:
family.set_child_ref_list(new_ref_list)
self.db.commit_family(family, self.trans)
self.progress.step()
# Check persons membership in referenced families
for person_handle in self.db.get_person_handles():
person = self.db.get_person_from_handle(person_handle)
phandle_list = person.get_parent_family_handle_list()
new_list = list(set(phandle_list))
if len(phandle_list) != len(new_list):
person.set_parent_family_handle_list(new_list)
self.db.commit_person(person, self.trans)
for par_family_handle in person.get_parent_family_handle_list():
try:
family = self.db.get_family_from_handle(par_family_handle)
except HandleError:
person.remove_parent_family_handle(par_family_handle)
self.db.commit_person(person, self.trans)
continue
for child_handle in [child_ref.ref for child_ref
in family.get_child_ref_list()]:
if child_handle == person_handle:
break
else:
# Person is not a child in the referenced parent family
# This is tested by TestcaseGenerator where the father
# is "Broken9"
logging.warning(" FAIL: family '%(fam_gid)s' person "
"'%(pers_gid)s' is not a child in the "
"referenced parent family",
{'fam_gid': family.gramps_id,
'pers_gid': person.gramps_id})
person.remove_parent_family_handle(par_family_handle)
self.db.commit_person(person, self.trans)
self.broken_links.append((person_handle, family_handle))
for family_handle in person.get_family_handle_list():
try:
family = self.db.get_family_from_handle(family_handle)
except HandleError:
# The referenced family does not exist in database
# This is tested by TestcaseGenerator where the father
# is "Broken20"
logging.warning(" FAIL: person '%(pers_gid)s' refers "
"to family '%(hand)s' which is not in the "
"database",
{'pers_gid': person.gramps_id,
'hand': family_handle})
person.remove_family_handle(family_handle)
self.db.commit_person(person, self.trans)
self.broken_links.append((person_handle, family_handle))
continue
if family.get_father_handle() == person_handle:
continue
if family.get_mother_handle() == person_handle:
continue
# The person is not a member of the referenced family
# This is tested by TestcaseGenerator where the father is
# "Broken2" and the family misses the link to the father, and
# where the mother is "Broken3" and the family misses the link
# to the mother
logging.warning(" FAIL: family '%(fam_gid)s' person "
"'%(pers_gid)s' is not member of the "
"referenced family",
{'fam_gid': family.gramps_id,
'pers_gid': person.gramps_id})
person.remove_family_handle(family_handle)
self.db.commit_person(person, self.trans)
self.broken_links.append((person_handle, family_handle))
self.progress.step()
if previous_errors == len(self.broken_parent_links +
self.broken_links):
logging.info(' OK: no broken family links found')
def cleanup_missing_photos(self, cli=0):
self.progress.set_pass(_('Looking for unused objects'),
len(self.db.get_media_handles()))
logging.info('Looking for missing photos')
missmedia_action = 0
# ---------------------------------------------------------------------
def remove_clicked():
# File is lost => remove all references and the object itself
for handle in self.db.get_person_handles(sort_handles=False):
person = self.db.get_person_from_handle(handle)
if person.has_media_reference(objectid):
person.remove_media_references([objectid])
self.db.commit_person(person, self.trans)
for handle in self.db.get_family_handles():
family = self.db.get_family_from_handle(handle)
if family.has_media_reference(objectid):
family.remove_media_references([objectid])
self.db.commit_family(family, self.trans)
for handle in self.db.get_event_handles():
event = self.db.get_event_from_handle(handle)
if event.has_media_reference(objectid):
event.remove_media_references([objectid])
self.db.commit_event(event, self.trans)
for handle in self.db.get_source_handles():
source = self.db.get_source_from_handle(handle)
if source.has_media_reference(objectid):
source.remove_media_references([objectid])
self.db.commit_source(source, self.trans)
for handle in self.db.get_citation_handles():
citation = self.db.get_citation_from_handle(handle)
if citation.has_media_reference(objectid):
citation.remove_media_references([objectid])
self.db.commit_citation(citation, self.trans)
for handle in self.db.get_place_handles():
place = self.db.get_place_from_handle(handle)
if place.has_media_reference(objectid):
place.remove_media_references([objectid])
self.db.commit_place(place, self.trans)
self.removed_photo.append(objectid)
self.db.remove_media(objectid, self.trans)
logging.warning(' FAIL: media object and all references to '
'it removed')
def leave_clicked():
self.bad_photo.append(objectid)
logging.warning(' FAIL: references to missing file kept')
def select_clicked():
# File is lost => select a file to replace the lost one
def fs_close_window(dummy):
self.bad_photo.append(objectid)
logging.warning(' FAIL: references to missing file '
'kept')
def fs_ok_clicked(obj):
name = fs_top.get_filename()
if os.path.isfile(name):
obj = self.db.get_media_from_handle(objectid)
obj.set_path(name)
self.db.commit_media(obj, self.trans)
self.replaced_photo.append(objectid)
self.last_img_dir = os.path.dirname(name)
logging.warning(' FAIL: media object reselected to '
'"%s"', name)
else:
self.bad_photo.append(objectid)
logging.warning(' FAIL: references to missing file '
'kept')
fs_top = Gtk.FileChooserDialog(
"%s - Gramps" % _("Select file"),
parent=self.parent_window,
buttons=(_('_Cancel'), Gtk.ResponseType.CANCEL,
_('_OK'), Gtk.ResponseType.OK))
fs_top.set_current_folder(self.last_img_dir)
response = fs_top.run()
if response == Gtk.ResponseType.OK:
fs_ok_clicked(fs_top)
elif response == Gtk.ResponseType.CANCEL:
fs_close_window(fs_top)
fs_top.destroy()
# --------------------------------------------------------------------
for objectid in self.db.get_media_handles():
obj = self.db.get_media_from_handle(objectid)
photo_name = media_path_full(self.db, obj.get_path())
photo_desc = obj.get_description()
if photo_name is not None and photo_name != "" \
and not find_file(photo_name):
if cli:
logging.warning(" FAIL: media file %s was not found.",
photo_name)
self.bad_photo.append(objectid)
else:
if missmedia_action == 0:
logging.warning(' FAIL: media object "%(desc)s" '
'reference to missing file "%(name)s" '
'found',
{'desc': photo_desc,
'name': photo_name})
mmd = MissingMediaDialog(
_("Media object could not be found"),
_("The file:\n%(file_name)s\nis referenced in "
"the database, but no longer exists.\n"
"The file may have been deleted or moved to "
"a different location.\n"
"You may choose to either remove the "
"reference from the database,\n"
"keep the reference to the missing file, "
"or select a new file.")
% {'file_name': '<b>%s</b>' % photo_name},
remove_clicked, leave_clicked, select_clicked,
parent=self.uistate.window)
missmedia_action = mmd.default_action
elif missmedia_action == 1:
logging.warning(' FAIL: media object "%(desc)s" '
'reference to missing file "%(name)s" '
'found',
{'desc': photo_desc,
'name': photo_name})
remove_clicked()
elif missmedia_action == 2:
logging.warning(' FAIL: media object "%(desc)s" '
'reference to missing file "%(name)s" '
'found',
{'desc': photo_desc,
'name': photo_name})
leave_clicked()
elif missmedia_action == 3:
logging.warning(' FAIL: media object "%(desc)s" '
'reference to missing file "%(name)s" '
'found',
{'desc': photo_desc,
'name': photo_name})
select_clicked()
self.progress.step()
if len(self.bad_photo + self.removed_photo) == 0:
logging.info(' OK: no missing photos found')
def cleanup_empty_objects(self):
# the position of the change column in the primary objects
CHANGE_PERSON = 17
CHANGE_FAMILY = 12
CHANGE_EVENT = 10
CHANGE_SOURCE = 8
CHANGE_CITATION = 9
CHANGE_PLACE = 11
CHANGE_MEDIA = 8
CHANGE_REPOS = 7
CHANGE_NOTE = 5
empty_person_data = Person().serialize()
empty_family_data = Family().serialize()
empty_event_data = Event().serialize()
empty_source_data = Source().serialize()
empty_citation_data = Citation().serialize()
empty_place_data = Place().serialize()
empty_media_data = Media().serialize()
empty_repos_data = Repository().serialize()
empty_note_data = Note().serialize()
_db = self.db
def _empty(empty, flag):
''' Closure for dispatch table, below '''
def _fx(value):
return self._check_empty(value, empty, flag)
return _fx
table = (
# Dispatch table for cleaning up empty objects. Each entry is
# a tuple containing:
# 0. Type of object being cleaned up
# 1. function to read the object from the database
# 2. function returning cursor over the object type
# 3. function returning number of objects of this type
# 4. text identifying the object being cleaned up
# 5. function to check if the data is empty
# 6. function to remove the object, if empty
('persons',
_db.get_person_from_handle,
_db.get_person_cursor,
_db.get_number_of_people,
_('Looking for empty people records'),
_empty(empty_person_data, CHANGE_PERSON),
_db.remove_person),
('families',
_db.get_family_from_handle,
_db.get_family_cursor,
_db.get_number_of_families,
_('Looking for empty family records'),
_empty(empty_family_data, CHANGE_FAMILY),
_db.remove_family),
('events',
_db.get_event_from_handle,
_db.get_event_cursor,
_db.get_number_of_events,
_('Looking for empty event records'),
_empty(empty_event_data, CHANGE_EVENT),
_db.remove_event),
('sources',
_db.get_source_from_handle,
_db.get_source_cursor,
_db.get_number_of_sources,
_('Looking for empty source records'),
_empty(empty_source_data, CHANGE_SOURCE),
_db.remove_source),
('citations',
_db.get_citation_from_handle,
_db.get_citation_cursor,
_db.get_number_of_citations,
_('Looking for empty citation records'),
_empty(empty_citation_data, CHANGE_CITATION),
_db.remove_citation),
('places',
_db.get_place_from_handle,
_db.get_place_cursor,
_db.get_number_of_places,
_('Looking for empty place records'),
_empty(empty_place_data, CHANGE_PLACE),
_db.remove_place),
('media',
_db.get_media_from_handle,
_db.get_media_cursor,
_db.get_number_of_media,
_('Looking for empty media records'),
_empty(empty_media_data, CHANGE_MEDIA),
_db.remove_media),
('repos',
_db.get_repository_from_handle,
_db.get_repository_cursor,
_db.get_number_of_repositories,
_('Looking for empty repository records'),
_empty(empty_repos_data, CHANGE_REPOS),
_db.remove_repository),
('notes',
_db.get_note_from_handle,
_db.get_note_cursor,
_db.get_number_of_notes,
_('Looking for empty note records'),
_empty(empty_note_data, CHANGE_NOTE),
_db.remove_note),
)
# Now, iterate over the table, dispatching the functions
for (the_type, dummy, cursor_func, total_func,
text, check_func, remove_func) in table:
with cursor_func() as cursor:
total = total_func()
self.progress.set_pass(text, total)
logging.info(text)
for handle, data in cursor:
self.progress.step()
if check_func(data):
# we cannot remove here as that would destroy cursor
# so save the handles for later removal
logging.warning(' FAIL: empty %(type)s record with '
'handle "%(hand)s" was found',
{'type': the_type, 'hand': handle})
self.empty_objects[the_type].append(handle)
# now remove
for handle in self.empty_objects[the_type]:
remove_func(handle, self.trans)
if len(self.empty_objects[the_type]) == 0:
logging.info(' OK: no empty %s found', the_type)
def _check_empty(self, data, empty_data, changepos):
"""compare the data with the data of an empty object
change, handle and gramps_id are not compared """
if changepos is not None:
return (data[2:changepos] == empty_data[2:changepos] and
data[changepos + 1:] == empty_data[changepos + 1:])
else:
return data[2:] == empty_data[2:]
def cleanup_empty_families(self, dummy):
fhandle_list = self.db.get_family_handles()
self.progress.set_pass(_('Looking for empty families'),
len(fhandle_list))
logging.info('Looking for empty families')
previous_errors = len(self.empty_family)
for family_handle in fhandle_list:
self.progress.step()
family = self.db.get_family_from_handle(family_handle)
family_id = family.get_gramps_id()
father_handle = family.get_father_handle()
mother_handle = family.get_mother_handle()
if not father_handle and not mother_handle and \
len(family.get_child_ref_list()) == 0:
self.empty_family.append(family_id)
self.delete_empty_family(family_handle)
if previous_errors == len(self.empty_family):
logging.info(' OK: no empty families found')
def delete_empty_family(self, family_handle):
for key in self.db.get_person_handles(sort_handles=False):
child = self.db.get_person_from_handle(key)
changed = False
changed |= child.remove_parent_family_handle(family_handle)
changed |= child.remove_family_handle(family_handle)
if changed:
self.db.commit_person(child, self.trans)
self.db.remove_family(family_handle, self.trans)
def check_parent_relationships(self):
"""Repair father=female or mother=male in hetero families
"""
fhandle_list = self.db.get_family_handles()
self.progress.set_pass(_('Looking for broken parent relationships'),
len(fhandle_list))
logging.info('Looking for broken parent relationships')
previous_errors = len(self.fam_rel)
for family_handle in fhandle_list:
self.progress.step()
family = self.db.get_family_from_handle(family_handle)
father_handle = family.get_father_handle()
if father_handle:
fgender = self.db.get_person_from_handle(
father_handle).get_gender()
else:
fgender = None
mother_handle = family.get_mother_handle()
if mother_handle:
mgender = self.db.get_person_from_handle(
mother_handle).get_gender()
else:
mgender = None
if (fgender == Person.FEMALE or
mgender == Person.MALE) and fgender != mgender:
# swap. note: (at most) one handle may be None
logging.warning(' FAIL: the family "%s" has a father=female'
' or mother=male in a different sex family',
family.gramps_id)
family.set_father_handle(mother_handle)
family.set_mother_handle(father_handle)
self.db.commit_family(family, self.trans)
self.fam_rel.append(family_handle)
if previous_errors == len(self.fam_rel):
logging.info(' OK: no broken parent relationships found')
def check_events(self):
'''Looking for event problems'''
self.progress.set_pass(_('Looking for event problems'),
self.db.get_number_of_people() +
self.db.get_number_of_families())
logging.info('Looking for event problems')
for key in self.db.get_person_handles(sort_handles=False):
self.progress.step()
person = self.db.get_person_from_handle(key)
birth_ref = person.get_birth_ref()
none_handle = False
if birth_ref:
newref = birth_ref
if not birth_ref.ref:
none_handle = True
birth_ref.ref = create_id()
birth_handle = birth_ref.ref
try:
birth = self.db.get_event_from_handle(birth_handle)
except HandleError:
# The birth event referenced by the birth handle
# does not exist in the database
# This is tested by TestcaseGenerator person "Broken11"
make_unknown(birth_handle, self.explanation.handle,
self.class_event, self.commit_event,
self.trans, type=EventType.BIRTH)
logging.warning(' FAIL: the person "%(gid)s" refers to '
'a birth event "%(hand)s" which does not '
'exist in the database',
{'gid': person.gramps_id,
'hand': birth_handle})
self.invalid_events.add(key)
else:
if int(birth.get_type()) != EventType.BIRTH:
# Birth event was not of the type "Birth"
# This is tested by TestcaseGenerator person "Broken14"
logging.warning(' FAIL: the person "%(gid)s" refers'
' to a birth event which is of type '
'"%(type)s" instead of Birth',
{'gid': person.gramps_id,
'type': int(birth.get_type())})
birth.set_type(EventType(EventType.BIRTH))
self.db.commit_event(birth, self.trans)
self.invalid_birth_events.add(key)
if none_handle:
person.set_birth_ref(newref)
self.db.commit_person(person, self.trans)
none_handle = False
death_ref = person.get_death_ref()
if death_ref:
newref = death_ref
if not death_ref.ref:
none_handle = True
death_ref.ref = create_id()
death_handle = death_ref.ref
try:
death = self.db.get_event_from_handle(death_handle)
except HandleError:
# The death event referenced by the death handle
# does not exist in the database
# This is tested by TestcaseGenerator person "Broken12"
logging.warning(' FAIL: the person "%(gid)s" refers to '
'a death event "%(hand)s" which does not '
'exist in the database',
{'gid': person.gramps_id,
'hand': death_handle})
make_unknown(death_handle, self.explanation.handle,
self.class_event, self.commit_event,
self.trans, type=EventType.DEATH)
self.invalid_events.add(key)
else:
if int(death.get_type()) != EventType.DEATH:
# Death event was not of the type "Death"
# This is tested by TestcaseGenerator person "Broken15"
logging.warning(
' FAIL: the person "%(gid)s" refers to a death '
'event which is of type "%(type)s" instead of '
'Death',
{'gid': person.gramps_id,
'type': int(death.get_type())})
death.set_type(EventType(EventType.DEATH))
self.db.commit_event(death, self.trans)
self.invalid_death_events.add(key)
if none_handle:
person.set_death_ref(newref)
self.db.commit_person(person, self.trans)
none_handle = False
newlist = []
if person.get_event_ref_list():
for event_ref in person.get_event_ref_list():
newlist.append(event_ref)
if not event_ref.ref:
none_handle = True
event_ref.ref = create_id()
event_handle = event_ref.ref
try:
self.db.get_event_from_handle(event_handle)
except HandleError:
# The event referenced by the person
# does not exist in the database
# TODO: There is no better way?
# This is tested by TestcaseGenerator person "Broken11"
# This is tested by TestcaseGenerator person "Broken12"
# This is tested by TestcaseGenerator person "Broken13"
logging.warning(
' FAIL: the person "%(gid)s" refers to an event'
' "%(hand)s" which does not exist in the database',
{'gid': person.gramps_id,
'hand': event_handle})
make_unknown(event_handle, self.explanation.handle,
self.class_event,
self.commit_event, self.trans)
self.invalid_events.add(key)
if none_handle:
person.set_event_ref_list(newlist)
self.db.commit_person(person, self.trans)
elif not isinstance(person.get_event_ref_list(), list):
# event_list is None or other garbage
logging.warning(' FAIL: the person "%s" has an event ref '
'list which is invalid', (person.gramps_id))
person.set_event_ref_list([])
self.db.commit_person(person, self.trans)
self.invalid_events.add(key)
for key in self.db.get_family_handles():
self.progress.step()
family = self.db.get_family_from_handle(key)
if family.get_event_ref_list():
none_handle = False
newlist = []
for event_ref in family.get_event_ref_list():
newlist.append(event_ref)
if not event_ref.ref:
none_handle = True
event_ref.ref = create_id()
event_handle = event_ref.ref
try:
self.db.get_event_from_handle(event_handle)
except HandleError:
# The event referenced by the family
# does not exist in the database
logging.warning(' FAIL: the family "%(gid)s" refers'
' to an event "%(hand)s" which does '
'not exist in the database',
{'gid': family.gramps_id,
'hand': event_handle})
make_unknown(event_handle, self.explanation.handle,
self.class_event, self.commit_event,
self.trans)
self.invalid_events.add(key)
if none_handle:
family.set_event_ref_list(newlist)
self.db.commit_family(family, self.trans)
elif not isinstance(family.get_event_ref_list(), list):
# event_list is None or other garbage
logging.warning(' FAIL: the family "%s" has an event ref '
'list which is invalid', (family.gramps_id))
family.set_event_ref_list([])
self.db.commit_family(family, self.trans)
self.invalid_events.add(key)
if len(self.invalid_birth_events) + len(self.invalid_death_events) + \
len(self.invalid_events) == 0:
logging.info(' OK: no event problems found')
def check_backlinks(self):
'''Looking for backlink reference problems'''
total = self.db.get_total()
self.progress.set_pass(_('Looking for backlink reference problems') +
' (1)', total)
logging.info('Looking for backlink reference problems')
# dict of object handles indexed by forward link created here
my_blinks = defaultdict(list)
my_items = 0 # count of my backlinks for progress meter
# dict of object handles indexed by forward link from db
db_blinks = {}
db_items = 0 # count of db backlinks for progress meter
# first we assemble our own backlinks table, and while we have the
# handle, gather up a second table with the db's backlinks
for obj_class in CLASS_TO_KEY_MAP.keys():
for handle in self.db.method("iter_%s_handles", obj_class)():
self.progress.step()
blinks = list(self.db.find_backlink_handles(handle))
db_blinks[(obj_class, handle)] = blinks
db_items += len(blinks)
pri_obj = self.db.method('get_%s_from_handle',
obj_class)(handle)
handle_list = pri_obj.get_referenced_handles_recursively()
my_items += len(handle_list)
for item in handle_list:
my_blinks[item].append((obj_class, handle))
# Now we go through our backlinks and the dbs table comparing them
# check that each real reference has a backlink in the db table
self.progress.set_pass(_('Looking for backlink reference problems') +
' (2)', my_items)
for key, blinks in my_blinks.items():
for item in blinks:
self.progress.step()
if key not in db_blinks:
# object has reference to something not in db;
# should have been found in previous checks
logging.warning(' Fail: reference to an object %(obj)s'
' not in the db by %(ref)s!',
{'obj': key, 'ref': item})
continue
if item not in db_blinks[key]:
# Object has reference with no cooresponding backlink
self.bad_backlinks += 1
pri_obj = self.db.method('get_%s_from_handle',
key[0])(key[1])
logging.warning(' FAIL: the "%(cls)s" [%(gid)s] '
'has a "%(cls2)s" reference'
' with no corresponding backlink.',
{'gid': pri_obj.gramps_id,
'cls': key[0], 'cls2': item[0]})
# Now we go through the db table and make checks against ours
# Check for db backlinks that don't have a reference object at all
self.progress.set_pass(_('Looking for backlink reference problems') +
' (3)', db_items)
for key, blinks in db_blinks.items():
for item in blinks:
self.progress.step()
if item not in db_blinks:
# backlink to object entirely missing
self.bad_backlinks += 1
pri_obj = self.db.method('get_%s_from_handle',
key[0])(key[1])
logging.warning(' FAIL: the "%(cls)s" [%(gid)s] '
'has a backlink to a missing'
' "%(cls2)s" object.',
{'gid': pri_obj.gramps_id,
'cls': key[0], 'cls2': item[0]})
continue
# Check if the object has a reference to the backlinked one
if key not in my_blinks or item not in my_blinks[key]:
# backlink to object which doesn't have reference
self.bad_backlinks += 1
pri_obj = self.db.method('get_%s_from_handle',
key[0])(key[1])
logging.warning(' FAIL: the "%(cls)s" [%(gid)s] '
'has a backlink to a "%(cls2)s"'
' with no corresponding reference.',
{'gid': pri_obj.gramps_id,
'cls': key[0], 'cls2': item[0]})
def callback(self, *args):
self.progress.step()
def check_person_references(self):
'''Looking for person reference problems'''
plist = self.db.get_person_handles()
self.progress.set_pass(_('Looking for person reference problems'),
len(plist))
logging.info('Looking for person reference problems')
for key in plist:
self.progress.step()
none_handle = False
newlist = []
person = self.db.get_person_from_handle(key)
for pref in person.get_person_ref_list():
newlist.append(pref)
if not pref.ref:
none_handle = True
pref.ref = create_id()
try:
self.db.get_person_from_handle(pref.ref)
except HandleError:
# The referenced person does not exist in the database
make_unknown(pref.ref, self.explanation.handle,
self.class_person, self.commit_person,
self.trans)
self.invalid_person_references.add(key)
if none_handle:
person.set_person_ref_list(newlist)
self.db.commit_person(person, self.trans)
if len(self.invalid_person_references) == 0:
logging.info(' OK: no event problems found')
def check_family_references(self):
'''Looking for family reference problems'''
plist = self.db.get_person_handles()
self.progress.set_pass(_('Looking for family reference problems'),
len(plist))
logging.info('Looking for family reference problems')
for key in plist:
self.progress.step()
person = self.db.get_person_from_handle(key)
for ordinance in person.get_lds_ord_list():
family_handle = ordinance.get_family_handle()
if family_handle:
try:
self.db.get_family_from_handle(family_handle)
except HandleError:
# The referenced family does not exist in the database
make_unknown(family_handle, self.explanation.handle,
self.class_family, self.commit_family,
self.trans, db=self.db)
self.invalid_family_references.add(key)
if len(self.invalid_family_references) == 0:
logging.info(' OK: no event problems found')
def check_repo_references(self):
'''Looking for repository reference problems'''
slist = self.db.get_source_handles()
self.progress.set_pass(_('Looking for repository reference problems'),
len(slist))
logging.info('Looking for repository reference problems')
for key in slist:
self.progress.step()
none_handle = False
newlist = []
source = self.db.get_source_from_handle(key)
for reporef in source.get_reporef_list():
newlist.append(reporef)
if not reporef.ref:
none_handle = True
reporef.ref = create_id()
try:
self.db.get_repository_from_handle(reporef.ref)
except HandleError:
# The referenced repository does not exist in the database
make_unknown(reporef.ref, self.explanation.handle,
self.class_repo, self.commit_repo, self.trans)
self.invalid_repo_references.add(key)
if none_handle:
source.set_reporef_list(newlist)
self.db.commit_source(source, self.trans)
if len(self.invalid_repo_references) == 0:
logging.info(' OK: no repository reference problems found')
def check_place_references(self):
'''Looking for place reference problems'''
plist = self.db.get_person_handles()
flist = self.db.get_family_handles()
elist = self.db.get_event_handles()
llist = self.db.get_place_handles()
self.progress.set_pass(
_('Looking for place reference problems'),
len(elist) + len(plist) + len(flist) + len(llist))
logging.info('Looking for place reference problems')
for key in llist:
self.progress.step()
none_handle = False
newlist = []
place = self.db.get_place_from_handle(key)
for placeref in place.get_placeref_list():
newlist.append(placeref)
if not placeref.ref:
none_handle = True
placeref.ref = create_id()
try:
self.db.get_place_from_handle(placeref.ref)
except HandleError:
# The referenced place does not exist in the database
make_unknown(placeref.ref, self.explanation.handle,
self.class_place, self.commit_place,
self.trans)
logging.warning(' FAIL: the place "%(gid)s" refers '
'to a parent place "%(hand)s" which '
'does not exist in the database',
{'gid': place.gramps_id,
'hand': placeref.ref})
self.invalid_place_references.add(key)
if none_handle:
place.set_placeref_list(newlist)
self.db.commit_place(place, self.trans)
# check persons -> the LdsOrd references a place
for key in plist:
self.progress.step()
person = self.db.get_person_from_handle(key)
for ordinance in person.lds_ord_list:
place_handle = ordinance.get_place_handle()
if place_handle:
try:
place = self.db.get_place_from_handle(place_handle)
except HandleError:
# The referenced place does not exist in the database
# This is tested by TestcaseGenerator person "Broken17"
# This is tested by TestcaseGenerator person "Broken18"
make_unknown(place_handle, self.explanation.handle,
self.class_place, self.commit_place,
self.trans)
logging.warning(' FAIL: the person "%(gid)s" refers'
' to an LdsOrd place "%(hand)s" which '
'does not exist in the database',
{'gid': person.gramps_id,
'hand': place_handle})
self.invalid_place_references.add(key)
# check families -> the LdsOrd references a place
for key in flist:
self.progress.step()
family = self.db.get_family_from_handle(key)
for ordinance in family.lds_ord_list:
place_handle = ordinance.get_place_handle()
if place_handle:
try:
place = self.db.get_place_from_handle(place_handle)
except HandleError:
# The referenced place does not exist in the database
make_unknown(place_handle, self.explanation.handle,
self.class_place, self.commit_place,
self.trans)
logging.warning(' FAIL: the family "%(gid)s" refers'
' to an LdsOrd place "%(hand)s" which '
'does not exist in the database',
{'gid': family.gramps_id,
'hand': place_handle})
self.invalid_place_references.add(key)
# check events
for key in elist:
self.progress.step()
event = self.db.get_event_from_handle(key)
place_handle = event.get_place_handle()
if place_handle:
try:
place = self.db.get_place_from_handle(place_handle)
except HandleError:
# The referenced place does not exist in the database
make_unknown(place_handle, self.explanation.handle,
self.class_place, self.commit_place,
self.trans)
logging.warning(' FAIL: the event "%(gid)s" refers '
'to an LdsOrd place "%(hand)s" which '
'does not exist in the database',
{'gid': event.gramps_id,
'hand': place_handle})
self.invalid_place_references.add(key)
if len(self.invalid_place_references) == 0:
logging.info(' OK: no place reference problems found')
def check_citation_references(self):
'''Looking for citation reference problems'''
known_handles = self.db.get_citation_handles()
total = (
self.db.get_number_of_people() +
self.db.get_number_of_families() +
self.db.get_number_of_events() +
self.db.get_number_of_places() +
self.db.get_number_of_citations() +
self.db.get_number_of_sources() +
self.db.get_number_of_media() +
self.db.get_number_of_repositories()
)
self.progress.set_pass(_('Looking for citation reference problems'),
total)
logging.info('Looking for citation reference problems')
for handle in self.db.get_person_handles():
self.progress.step()
person = self.db.get_person_from_handle(handle)
handle_list = person.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Citation':
if not item[1]:
new_handle = create_id()
person.replace_citation_references(None, new_handle)
self.db.commit_person(person, self.trans)
self.invalid_citation_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_citation_references.add(item[1])
for handle in self.db.get_family_handles():
self.progress.step()
family = self.db.get_family_from_handle(handle)
handle_list = family.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Citation':
if not item[1]:
new_handle = create_id()
family.replace_citation_references(None, new_handle)
self.db.commit_family(family, self.trans)
self.invalid_citation_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_citation_references.add(item[1])
for handle in self.db.get_place_handles():
self.progress.step()
place = self.db.get_place_from_handle(handle)
handle_list = place.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Citation':
if not item[1]:
new_handle = create_id()
place.replace_citation_references(None, new_handle)
self.db.commit_place(place, self.trans)
self.invalid_citation_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_citation_references.add(item[1])
for handle in self.db.get_citation_handles():
self.progress.step()
citation = self.db.get_citation_from_handle(handle)
handle_list = citation.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Citation':
if not item[1]:
new_handle = create_id()
citation.replace_citation_references(None, new_handle)
self.db.commit_citation(citation, self.trans)
self.invalid_citation_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_citation_references.add(item[1])
for handle in self.db.get_repository_handles():
self.progress.step()
repository = self.db.get_repository_from_handle(handle)
handle_list = repository.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Citation':
if not item[1]:
new_handle = create_id()
repository.replace_citation_references(None,
new_handle)
self.db.commit_repository(repository, self.trans)
self.invalid_citation_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_citation_references.add(item[1])
for handle in self.db.get_media_handles():
self.progress.step()
obj = self.db.get_media_from_handle(handle)
handle_list = obj.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Citation':
if not item[1]:
new_handle = create_id()
obj.replace_citation_references(None, new_handle)
self.db.commit_media(obj, self.trans)
self.invalid_citation_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_citation_references.add(item[1])
for handle in self.db.get_event_handles():
self.progress.step()
event = self.db.get_event_from_handle(handle)
handle_list = event.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Citation':
if not item[1]:
new_handle = create_id()
event.replace_citation_references(None, new_handle)
self.db.commit_event(event, self.trans)
self.invalid_citation_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_citation_references.add(item[1])
for bad_handle in self.invalid_citation_references:
created = make_unknown(bad_handle, self.explanation.handle,
self.class_citation, self.commit_citation,
self.trans,
source_class_func=self.class_source,
source_commit_func=self.commit_source,
source_class_arg=create_id())
self.invalid_source_references.add(created[0].handle)
if len(self.invalid_citation_references) == 0:
logging.info(' OK: no citation reference problems found')
def check_source_references(self):
'''Looking for source reference problems'''
clist = self.db.get_citation_handles()
self.progress.set_pass(_('Looking for source reference problems'),
len(clist))
logging.info('Looking for source reference problems')
for key in clist:
self.progress.step()
citation = self.db.get_citation_from_handle(key)
source_handle = citation.get_reference_handle()
if not source_handle:
source_handle = create_id()
citation.set_reference_handle(source_handle)
self.db.commit_citation(citation, self.trans)
if source_handle:
try:
self.db.get_source_from_handle(source_handle)
except HandleError:
# The referenced source does not exist in the database
make_unknown(source_handle, self.explanation.handle,
self.class_source, self.commit_source,
self.trans)
logging.warning(' FAIL: the citation "%(gid)s" refers '
'to source "%(hand)s" which does not exist'
' in the database',
{'gid': citation.gramps_id,
'hand': source_handle})
self.invalid_source_references.add(key)
if len(self.invalid_source_references) == 0:
logging.info(' OK: no source reference problems found')
def check_media_references(self):
'''Looking for media object reference problems'''
known_handles = self.db.get_media_handles(False)
total = (
self.db.get_number_of_people() +
self.db.get_number_of_families() +
self.db.get_number_of_events() +
self.db.get_number_of_places() +
self.db.get_number_of_citations() +
self.db.get_number_of_sources()
)
self.progress.set_pass(_('Looking for media object reference '
'problems'), total)
logging.info('Looking for media object reference problems')
for handle in self.db.get_person_handles():
self.progress.step()
person = self.db.get_person_from_handle(handle)
handle_list = person.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Media':
if not item[1]:
new_handle = create_id()
person.replace_media_references(None, new_handle)
self.db.commit_person(person, self.trans)
self.invalid_media_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_media_references.add(item[1])
for handle in self.db.get_family_handles():
self.progress.step()
family = self.db.get_family_from_handle(handle)
handle_list = family.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Media':
if not item[1]:
new_handle = create_id()
family.replace_media_references(None, new_handle)
self.db.commit_family(family, self.trans)
self.invalid_media_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_media_references.add(item[1])
for handle in self.db.get_place_handles():
self.progress.step()
place = self.db.get_place_from_handle(handle)
handle_list = place.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Media':
if not item[1]:
new_handle = create_id()
place.replace_media_references(None, new_handle)
self.db.commit_place(place, self.trans)
self.invalid_media_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_media_references.add(item[1])
for handle in self.db.get_event_handles():
self.progress.step()
event = self.db.get_event_from_handle(handle)
handle_list = event.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Media':
if not item[1]:
new_handle = create_id()
event.replace_media_references(None, new_handle)
self.db.commit_event(event, self.trans)
self.invalid_media_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_media_references.add(item[1])
for handle in self.db.get_citation_handles():
self.progress.step()
citation = self.db.get_citation_from_handle(handle)
handle_list = citation.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Media':
if not item[1]:
new_handle = create_id()
citation.replace_media_references(None, new_handle)
self.db.commit_citation(citation, self.trans)
self.invalid_media_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_media_references.add(item[1])
for handle in self.db.get_source_handles():
self.progress.step()
source = self.db.get_source_from_handle(handle)
handle_list = source.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Media':
if not item[1]:
new_handle = create_id()
source.replace_media_references(None, new_handle)
self.db.commit_source(source, self.trans)
self.invalid_media_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_media_references.add(item[1])
for bad_handle in self.invalid_media_references:
make_unknown(bad_handle, self.explanation.handle, self.class_media,
self.commit_media, self.trans)
if len(self.invalid_media_references) == 0:
logging.info(' OK: no media reference problems found')
def check_note_references(self):
'''Looking for note reference problems'''
# Here I assume check note_references runs after all the next checks.
missing_references = (len(self.invalid_person_references) +
len(self.invalid_family_references) +
len(self.invalid_birth_events) +
len(self.invalid_death_events) +
len(self.invalid_events) +
len(self.invalid_place_references) +
len(self.invalid_citation_references) +
len(self.invalid_source_references) +
len(self.invalid_repo_references) +
len(self.invalid_media_references))
if missing_references:
self.db.add_note(self.explanation, self.trans, set_gid=True)
known_handles = self.db.get_note_handles()
total = (self.db.get_number_of_people() +
self.db.get_number_of_families() +
self.db.get_number_of_events() +
self.db.get_number_of_places() +
self.db.get_number_of_media() +
self.db.get_number_of_citations() +
self.db.get_number_of_sources() +
self.db.get_number_of_repositories())
self.progress.set_pass(_('Looking for note reference problems'),
total)
logging.info('Looking for note reference problems')
for handle in self.db.get_person_handles():
self.progress.step()
person = self.db.get_person_from_handle(handle)
handle_list = person.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Note':
if not item[1]:
new_handle = create_id()
person.replace_note_references(None, new_handle)
self.db.commit_person(person, self.trans)
self.invalid_note_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_note_references.add(item[1])
for handle in self.db.get_family_handles():
self.progress.step()
family = self.db.get_family_from_handle(handle)
handle_list = family.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Note':
if not item[1]:
new_handle = create_id()
family.replace_note_references(None, new_handle)
self.db.commit_family(family, self.trans)
self.invalid_note_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_note_references.add(item[1])
for handle in self.db.get_place_handles():
self.progress.step()
place = self.db.get_place_from_handle(handle)
handle_list = place.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Note':
if not item[1]:
new_handle = create_id()
place.replace_note_references(None, new_handle)
self.db.commit_place(place, self.trans)
self.invalid_note_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_note_references.add(item[1])
for handle in self.db.get_citation_handles():
self.progress.step()
citation = self.db.get_citation_from_handle(handle)
handle_list = citation.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Note':
if not item[1]:
new_handle = create_id()
citation.replace_note_references(None, new_handle)
self.db.commit_citation(citation, self.trans)
self.invalid_note_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_note_references.add(item[1])
for handle in self.db.get_source_handles():
self.progress.step()
source = self.db.get_source_from_handle(handle)
handle_list = source.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Note':
if not item[1]:
new_handle = create_id()
source.replace_note_references(None, new_handle)
self.db.commit_source(source, self.trans)
self.invalid_note_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_note_references.add(item[1])
for handle in self.db.get_media_handles():
self.progress.step()
obj = self.db.get_media_from_handle(handle)
handle_list = obj.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Note':
if not item[1]:
new_handle = create_id()
obj.replace_note_references(None, new_handle)
self.db.commit_media(obj, self.trans)
self.invalid_note_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_note_references.add(item[1])
for handle in self.db.get_event_handles():
self.progress.step()
event = self.db.get_event_from_handle(handle)
handle_list = event.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Note':
if not item[1]:
new_handle = create_id()
event.replace_note_references(None, new_handle)
self.db.commit_event(event, self.trans)
self.invalid_note_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_note_references.add(item[1])
for handle in self.db.get_repository_handles():
self.progress.step()
repo = self.db.get_repository_from_handle(handle)
handle_list = repo.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Note':
if not item[1]:
new_handle = create_id()
repo.replace_note_references(None, new_handle)
self.db.commit_repository(repo, self.trans)
self.invalid_note_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_note_references.add(item[1])
for bad_handle in self.invalid_note_references:
make_unknown(bad_handle, self.explanation.handle,
self.class_note, self.commit_note, self.trans)
if len(self.invalid_note_references) == 0:
logging.info(' OK: no note reference problems found')
else:
if not missing_references:
self.db.add_note(self.explanation, self.trans, set_gid=True)
def check_checksum(self):
''' fix media checksums '''
self.progress.set_pass(_('Updating checksums on media'),
len(self.db.get_media_handles()))
for objectid in self.db.get_media_handles():
self.progress.step()
obj = self.db.get_media_from_handle(objectid)
full_path = media_path_full(self.db, obj.get_path())
new_checksum = create_checksum(full_path)
if new_checksum != obj.checksum:
logging.info('checksum: updating ' + obj.gramps_id)
obj.checksum = new_checksum
self.db.commit_media(obj, self.trans)
def check_tag_references(self):
'''Looking for tag reference problems'''
known_handles = self.db.get_tag_handles()
total = (self.db.get_number_of_people() +
self.db.get_number_of_families() +
self.db.get_number_of_media() +
self.db.get_number_of_notes() +
self.db.get_number_of_events() +
self.db.get_number_of_citations() +
self.db.get_number_of_sources() +
self.db.get_number_of_places() +
self.db.get_number_of_repositories())
self.progress.set_pass(_('Looking for tag reference problems'),
total)
logging.info('Looking for tag reference problems')
for handle in self.db.get_person_handles():
self.progress.step()
person = self.db.get_person_from_handle(handle)
handle_list = person.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Tag':
if not item[1]:
new_handle = create_id()
person.replace_tag_references(None, new_handle)
self.db.commit_person(person, self.trans)
self.invalid_tag_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_tag_references.add(item[1])
for handle in self.db.get_family_handles():
self.progress.step()
family = self.db.get_family_from_handle(handle)
handle_list = family.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Tag':
if not item[1]:
new_handle = create_id()
family.replace_tag_references(None, new_handle)
self.db.commit_family(family, self.trans)
self.invalid_tag_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_tag_references.add(item[1])
for handle in self.db.get_media_handles():
self.progress.step()
obj = self.db.get_media_from_handle(handle)
handle_list = obj.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Tag':
if not item[1]:
new_handle = create_id()
obj.replace_tag_references(None, new_handle)
self.db.commit_media(obj, self.trans)
self.invalid_tag_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_tag_references.add(item[1])
for handle in self.db.get_note_handles():
self.progress.step()
note = self.db.get_note_from_handle(handle)
handle_list = note.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Tag':
if not item[1]:
new_handle = create_id()
note.replace_tag_references(None, new_handle)
self.db.commit_note(note, self.trans)
self.invalid_tag_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_tag_references.add(item[1])
for handle in self.db.get_event_handles():
self.progress.step()
event = self.db.get_event_from_handle(handle)
handle_list = event.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Tag':
if not item[1]:
new_handle = create_id()
event.replace_tag_references(None, new_handle)
self.db.commit_event(event, self.trans)
self.invalid_tag_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_tag_references.add(item[1])
for handle in self.db.get_citation_handles():
self.progress.step()
citation = self.db.get_citation_from_handle(handle)
handle_list = citation.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Tag':
if not item[1]:
new_handle = create_id()
citation.replace_tag_references(None, new_handle)
self.db.commit_citation(citation, self.trans)
self.invalid_tag_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_tag_references.add(item[1])
for handle in self.db.get_source_handles():
self.progress.step()
source = self.db.get_source_from_handle(handle)
handle_list = source.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Tag':
if not item[1]:
new_handle = create_id()
source.replace_tag_references(None, new_handle)
self.db.commit_source(source, self.trans)
self.invalid_tag_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_tag_references.add(item[1])
for handle in self.db.get_place_handles():
self.progress.step()
place = self.db.get_place_from_handle(handle)
handle_list = place.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Tag':
if not item[1]:
new_handle = create_id()
place.replace_tag_references(None, new_handle)
self.db.commit_place(place, self.trans)
self.invalid_tag_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_tag_references.add(item[1])
for handle in self.db.get_repository_handles():
self.progress.step()
repository = self.db.get_repository_from_handle(handle)
handle_list = repository.get_referenced_handles_recursively()
for item in handle_list:
if item[0] == 'Tag':
if not item[1]:
new_handle = create_id()
repository.replace_tag_references(None, new_handle)
self.db.commit_repository(repository, self.trans)
self.invalid_tag_references.add(new_handle)
elif item[1] not in known_handles:
self.invalid_tag_references.add(item[1])
for bad_handle in self.invalid_tag_references:
make_unknown(bad_handle, None, self.class_tag,
self.commit_tag, self.trans)
if len(self.invalid_tag_references) == 0:
logging.info(' OK: no tag reference problems found')
def check_media_sourceref(self):
"""
This repairs a problem with database upgrade from database schema
version 15 to 16. Mediarefs on source primary objects can contain
sourcerefs, and these were not converted to citations.
"""
total = (self.db.get_number_of_sources())
self.progress.set_pass(_('Looking for media source reference '
'problems'), total)
logging.info('Looking for media source reference problems')
for handle in self.db.get_source_handles():
self.progress.step()
source = self.db.get_source_from_handle(handle)
new_media_ref_list = []
citation_changed = False
for media_ref in source.get_media_list():
citation_list = media_ref.get_citation_list()
new_citation_list = []
for citation_handle in citation_list:
# Either citation_handle is a handle, in which case it has
# been converted, or it is a 6-tuple, in which case it now
# needs to be converted.
if len(citation_handle) == 6:
if len(citation_handle) == 6:
sourceref = citation_handle
else:
sourceref = eval(citation_handle)
new_citation = Citation()
new_citation.set_date_object(sourceref[0])
new_citation.set_privacy(sourceref[1])
new_citation.set_note_list(sourceref[2])
new_citation.set_confidence_level(sourceref[3])
new_citation.set_reference_handle(sourceref[4])
new_citation.set_page(sourceref[5])
citation_handle = create_id()
new_citation.set_handle(citation_handle)
self.replaced_sourceref.append(handle)
citation_changed = True
logging.warning(' FAIL: the source "%s" has a media'
' reference with a source citation '
'which is invalid', (source.gramps_id))
self.db.add_citation(new_citation, self.trans)
new_citation_list.append(citation_handle)
media_ref.set_citation_list(new_citation_list)
new_media_ref_list.append(media_ref)
if citation_changed:
source.set_media_list(new_media_ref_list)
self.db.commit_source(source, self.trans)
if len(self.replaced_sourceref) > 0:
logging.info(' OK: no broken source citations on mediarefs '
'found')
def fix_duplicated_grampsid(self):
"""
This searches for duplicated Gramps ID within each of the major
classes. It does not check across classes. If duplicates are
found, a new Gramps ID is assigned.
"""
total = (
self.db.get_number_of_citations() +
self.db.get_number_of_events() +
self.db.get_number_of_families() +
self.db.get_number_of_media() +
self.db.get_number_of_notes() +
self.db.get_number_of_people() +
self.db.get_number_of_places() +
self.db.get_number_of_repositories() +
self.db.get_number_of_sources()
)
self.progress.set_pass(_('Looking for Duplicated Gramps ID '
'problems'), total)
logging.info('Looking for Duplicated Gramps ID problems')
gid_list = []
for citation in self.db.iter_citations():
self.progress.step()
ogid = gid = citation.get_gramps_id()
if gid in gid_list:
gid = self.db.find_next_citation_gramps_id()
citation.set_gramps_id(gid)
self.db.commit_citation(citation, self.trans)
logging.warning(' FAIL: Duplicated Gramps ID found, '
'Original: "%s" changed to: "%s"', ogid, gid)
self.duplicated_gramps_ids += 1
gid_list.append(gid)
gid_list = []
for event in self.db.iter_events():
self.progress.step()
ogid = gid = event.get_gramps_id()
if gid in gid_list:
gid = self.db.find_next_event_gramps_id()
event.set_gramps_id(gid)
self.db.commit_event(event, self.trans)
logging.warning(' FAIL: Duplicated Gramps ID found, '
'Original: "%s" changed to: "%s"', ogid, gid)
self.duplicated_gramps_ids += 1
gid_list.append(gid)
gid_list = []
for family in self.db.iter_families():
self.progress.step()
ogid = gid = family.get_gramps_id()
if gid in gid_list:
gid = self.db.find_next_family_gramps_id()
family.set_gramps_id(gid)
self.db.commit_family(family, self.trans)
logging.warning(' FAIL: Duplicated Gramps ID found, '
'Original: "%s" changed to: "%s"', ogid, gid)
self.duplicated_gramps_ids += 1
gid_list.append(gid)
gid_list = []
for media in self.db.iter_media():
self.progress.step()
ogid = gid = media.get_gramps_id()
if gid in gid_list:
gid = self.db.find_next_media_gramps_id()
media.set_gramps_id(gid)
self.db.commit_media(media, self.trans)
logging.warning(' FAIL: Duplicated Gramps ID found, '
'Original: "%s" changed to: "%s"', ogid, gid)
self.duplicated_gramps_ids += 1
gid_list.append(gid)
gid_list = []
for note in self.db.iter_notes():
ogid = gid = note.get_gramps_id()
if gid in gid_list:
gid = self.db.find_next_note_gramps_id()
note.set_gramps_id(gid)
self.db.commit_note(note, self.trans)
logging.warning(' FAIL: Duplicated Gramps ID found, '
'Original: "%s" changed to: "%s"', ogid, gid)
self.duplicated_gramps_ids += 1
gid_list.append(gid)
gid_list = []
for person in self.db.iter_people():
self.progress.step()
ogid = gid = person.get_gramps_id()
if gid in gid_list:
gid = self.db.find_next_person_gramps_id()
person.set_gramps_id(gid)
self.db.commit_person(person, self.trans)
logging.warning(' FAIL: Duplicated Gramps ID found, '
'Original: "%s" changed to: "%s"', ogid, gid)
self.duplicated_gramps_ids += 1
gid_list.append(gid)
gid_list = []
for place in self.db.iter_places():
self.progress.step()
ogid = gid = place.get_gramps_id()
if gid in gid_list:
gid = self.db.find_next_place_gramps_id()
place.set_gramps_id(gid)
self.db.commit_place(place, self.trans)
logging.warning(' FAIL: Duplicated Gramps ID found, '
'Original: "%s" changed to: "%s"', ogid, gid)
self.duplicated_gramps_ids += 1
gid_list.append(gid)
gid_list = []
for repository in self.db.iter_repositories():
self.progress.step()
ogid = gid = repository.get_gramps_id()
if gid in gid_list:
gid = self.db.find_next_repository_gramps_id()
repository.set_gramps_id(gid)
self.db.commit_repository(repository, self.trans)
logging.warning(' FAIL: Duplicated Gramps ID found, '
'Original: "%s" changed to: "%s"', ogid, gid)
self.duplicated_gramps_ids += 1
gid_list.append(gid)
gid_list = []
for source in self.db.iter_sources():
self.progress.step()
ogid = gid = source.get_gramps_id()
if gid in gid_list:
gid = self.db.find_next_source_gramps_id()
source.set_gramps_id(gid)
self.db.commit_source(source, self.trans)
logging.warning(' FAIL: Duplicated Gramps ID found, '
'Original: "%s" changed to: "%s"', ogid, gid)
self.duplicated_gramps_ids += 1
gid_list.append(gid)
def class_person(self, handle):
person = Person()
person.set_handle(handle)
return person
def commit_person(self, person, trans, dummy):
self.db.add_person(person, trans, set_gid=True)
def class_family(self, handle):
family = Family()
family.set_handle(handle)
return family
def commit_family(self, family, trans, dummy):
self.db.add_family(family, trans, set_gid=True)
def class_event(self, handle):
event = Event()
event.set_handle(handle)
return event
def commit_event(self, event, trans, dummy):
self.db.add_event(event, trans, set_gid=True)
def class_place(self, handle):
place = Place()
place.set_handle(handle)
return place
def commit_place(self, place, trans, dummy):
self.db.add_place(place, trans, set_gid=True)
def class_source(self, handle):
source = Source()
source.set_handle(handle)
return source
def commit_source(self, source, trans, dummy):
self.db.add_source(source, trans, set_gid=True)
def class_citation(self, handle):
citation = Citation()
citation.set_handle(handle)
return citation
def commit_citation(self, citation, trans, dummy):
self.db.add_citation(citation, trans, set_gid=True)
def class_repo(self, handle):
repo = Repository()
repo.set_handle(handle)
return repo
def commit_repo(self, repo, trans, dummy):
self.db.add_repository(repo, trans, set_gid=True)
def class_media(self, handle):
obj = Media()
obj.set_handle(handle)
return obj
def commit_media(self, obj, trans, dummy):
self.db.add_media(obj, trans, set_gid=True)
def class_note(self, handle):
note = Note()
note.set_handle(handle)
return note
def commit_note(self, note, trans, dummy):
self.db.add_note(note, trans, set_gid=True)
def class_tag(self, handle):
tag = Tag()
tag.set_handle(handle)
return tag
def commit_tag(self, tag, trans, dummy):
self.db.add_tag(tag, trans)
def build_report(self, uistate=None):
''' build the report from various counters'''
self.progress.close()
bad_photos = len(self.bad_photo)
replaced_photos = len(self.replaced_photo)
removed_photos = len(self.removed_photo)
photos = bad_photos + replaced_photos + removed_photos
efam = len(self.empty_family)
blink = len(self.broken_links)
plink = len(self.broken_parent_links)
slink = len(self.duplicate_links)
rel = len(self.fam_rel)
event_invalid = len(self.invalid_events)
birth_invalid = len(self.invalid_birth_events)
death_invalid = len(self.invalid_death_events)
person = birth_invalid + death_invalid
person_references = len(self.invalid_person_references)
family_references = len(self.invalid_family_references)
invalid_dates = len(self.invalid_dates)
place_references = len(self.invalid_place_references)
citation_references = len(self.invalid_citation_references)
source_references = len(self.invalid_source_references)
repo_references = len(self.invalid_repo_references)
media_references = len(self.invalid_media_references)
note_references = len(self.invalid_note_references)
tag_references = len(self.invalid_tag_references)
name_format = len(self.removed_name_format)
replaced_sourcerefs = len(self.replaced_sourceref)
dup_gramps_ids = self.duplicated_gramps_ids
empty_objs = sum(len(obj) for obj in self.empty_objects.values())
errors = (photos + efam + blink + plink + slink + rel +
event_invalid + person + self.place_errors +
person_references + family_references + place_references +
citation_references + repo_references + media_references +
note_references + tag_references + name_format + empty_objs +
invalid_dates + source_references + dup_gramps_ids +
self.bad_backlinks)
if errors == 0:
if uistate:
OkDialog(_("No errors were found"),
_('The database has passed internal checks'),
parent=uistate.window)
else:
print(_("No errors were found: the database has passed "
"internal checks."))
return 0
if blink > 0:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext("{quantity} broken child/family link was fixed\n",
"{quantity} broken child/family links were fixed\n",
blink).format(quantity=blink)
)
for (person_handle, family_handle) in self.broken_links:
try:
person = self.db.get_person_from_handle(person_handle)
except HandleError:
cname = _("Non existing child")
else:
cname = person.get_primary_name().get_name()
try:
family = self.db.get_family_from_handle(family_handle)
except HandleError:
pname = _("Unknown")
else:
pname = family_name(family, self.db)
self.text.write('\t')
self.text.write(
_("%(person)s was removed from the family of %(family)s\n")
% {'person': cname, 'family': pname}
)
if plink > 0:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext("{quantity} broken spouse/family link was fixed\n",
"{quantity} broken spouse/family links were fixed\n",
plink).format(quantity=plink)
)
for (person_handle, family_handle) in self.broken_parent_links:
try:
person = self.db.get_person_from_handle(person_handle)
except HandleError:
cname = _("Non existing person")
else:
cname = person.get_primary_name().get_name()
try:
family = self.db.get_family_from_handle(family_handle)
except HandleError:
pname = _("Unknown")
else:
pname = family_name(family, self.db)
self.text.write('\t')
self.text.write(
_("%(person)s was restored to the family of %(family)s\n")
% {'person': cname, 'family': pname}
)
if slink > 0:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext("{quantity} duplicate "
"spouse/family link was found\n",
"{quantity} duplicate "
"spouse/family links were found\n",
slink).format(quantity=slink)
)
for (person_handle, family_handle) in self.broken_parent_links:
try:
person = self.db.get_person_from_handle(person_handle)
except HandleError:
cname = _("Non existing person")
else:
cname = person.get_primary_name().get_name()
try:
family = self.db.get_family_from_handle(family_handle)
except HandleError:
pname = _("None")
else:
pname = family_name(family, self.db)
self.text.write('\t')
self.text.write(
_("%(person)s was restored to the family of %(family)s\n")
% {'person': cname, 'family': pname}
)
if efam:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext("{quantity} family "
"with no parents or children found, removed.\n",
"{quantity} families "
"with no parents or children found, removed.\n",
efam).format(quantity=efam)
)
if efam == 1:
self.text.write("\t%s\n" % self.empty_family[0])
if rel:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext("{quantity} corrupted family relationship fixed\n",
"{quantity} corrupted family relationships fixed\n",
rel).format(quantity=rel)
)
if self.place_errors:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext("{quantity} place alternate name fixed\n",
"{quantity} place alternate names fixed\n",
self.place_errors).format(quantity=self.place_errors)
)
if person_references:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext(
"{quantity} person was referenced but not found\n",
"{quantity} persons were referenced, but not found\n",
person_references).format(quantity=person_references)
)
if family_references:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext("{quantity} family was "
"referenced but not found\n",
"{quantity} families were "
"referenced, but not found\n",
family_references).format(quantity=family_references)
)
if invalid_dates:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext("{quantity} date was corrected\n",
"{quantity} dates were corrected\n",
invalid_dates).format(quantity=invalid_dates)
)
if repo_references:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext(
"{quantity} repository was "
"referenced but not found\n",
"{quantity} repositories were "
"referenced, but not found\n",
repo_references).format(quantity=repo_references)
)
if photos:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext("{quantity} media object was "
"referenced but not found\n",
"{quantity} media objects were "
"referenced, but not found\n",
photos).format(quantity=photos)
)
if bad_photos:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext(
"Reference to {quantity} missing media object was kept\n",
"References to {quantity} media objects were kept\n",
bad_photos).format(quantity=bad_photos)
)
if replaced_photos:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext("{quantity} missing media object was replaced\n",
"{quantity} missing media objects were replaced\n",
replaced_photos).format(quantity=replaced_photos)
)
if removed_photos:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext("{quantity} missing media object was removed\n",
"{quantity} missing media objects were removed\n",
removed_photos).format(quantity=removed_photos)
)
if event_invalid:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext("{quantity} event was referenced but not found\n",
"{quantity} events were referenced, but not found\n",
event_invalid).format(quantity=event_invalid)
)
if birth_invalid:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext("{quantity} invalid birth event name was fixed\n",
"{quantity} invalid birth event names were fixed\n",
birth_invalid).format(quantity=birth_invalid)
)
if death_invalid:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext("{quantity} invalid death event name was fixed\n",
"{quantity} invalid death event names were fixed\n",
death_invalid).format(quantity=death_invalid)
)
if place_references:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext("{quantity} place was referenced but not found\n",
"{quantity} places were referenced, but not found\n",
place_references).format(quantity=place_references)
)
if citation_references:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext(
"{quantity} citation was referenced but not found\n",
"{quantity} citations were referenced, but not found\n",
citation_references
).format(quantity=citation_references)
)
if source_references:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext(
"{quantity} source was referenced but not found\n",
"{quantity} sources were referenced, but not found\n",
source_references).format(quantity=source_references)
)
if media_references:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext(
"{quantity} media object was referenced but not found\n",
"{quantity} media objects were referenced,"
" but not found\n",
media_references).format(quantity=media_references)
)
if note_references:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext("{quantity} note object was "
"referenced but not found\n",
"{quantity} note objects were "
"referenced, but not found\n",
note_references).format(quantity=note_references)
)
if tag_references:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext("{quantity} tag object was "
"referenced but not found\n",
"{quantity} tag objects were "
"referenced, but not found\n",
tag_references).format(quantity=tag_references)
)
if tag_references:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext("{quantity} tag object was "
"referenced but not found\n",
"{quantity} tag objects were "
"referenced, but not found\n",
tag_references).format(quantity=tag_references)
)
if name_format:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext("{quantity} invalid name format "
"reference was removed\n",
"{quantity} invalid name format "
"references were removed\n",
name_format).format(quantity=name_format)
)
if replaced_sourcerefs:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext(
"{quantity} invalid source citation was fixed\n",
"{quantity} invalid source citations were fixed\n",
replaced_sourcerefs
).format(quantity=replaced_sourcerefs)
)
if dup_gramps_ids > 0:
self.text.write(
# translators: leave all/any {...} untranslated
ngettext("{quantity} Duplicated Gramps ID fixed\n",
"{quantity} Duplicated Gramps IDs fixed\n",
dup_gramps_ids).format(quantity=dup_gramps_ids)
)
if empty_objs > 0:
self.text.write(_(
"%(empty_obj)d empty objects removed:\n"
" %(person)d person objects\n"
" %(family)d family objects\n"
" %(event)d event objects\n"
" %(source)d source objects\n"
" %(media)d media objects\n"
" %(place)d place objects\n"
" %(repo)d repository objects\n"
" %(note)d note objects\n") % {
'empty_obj': empty_objs,
'person': len(self.empty_objects['persons']),
'family': len(self.empty_objects['families']),
'event': len(self.empty_objects['events']),
'source': len(self.empty_objects['sources']),
'media': len(self.empty_objects['media']),
'place': len(self.empty_objects['places']),
'repo': len(self.empty_objects['repos']),
'note': len(self.empty_objects['notes'])
}
)
if self.bad_backlinks:
self.text.write(_("%d bad backlinks were fixed;\n")
% self.bad_backlinks +
_("All reference maps have been rebuilt.") + '\n')
return errors
# -------------------------------------------------------------------------
#
# Display the results
#
# -------------------------------------------------------------------------
class CheckReport(ManagedWindow):
""" Report out the results """
def __init__(self, uistate, text, cli=0):
if cli:
print(text)
if uistate:
ManagedWindow.__init__(self, uistate, [], self)
topdialog = Glade()
topdialog.get_object("close").connect('clicked', self.close)
window = topdialog.toplevel
textwindow = topdialog.get_object("textwindow")
textwindow.get_buffer().set_text(text)
self.set_window(window,
# topdialog.get_widget("title"),
topdialog.get_object("title"),
_("Integrity Check Results"))
self.setup_configs('interface.checkreport', 450, 400)
self.show()
def build_menu_names(self, obj):
return (_('Check and Repair'), None)
# ------------------------------------------------------------------------
#
#
#
# ------------------------------------------------------------------------
class CheckOptions(tool.ToolOptions):
"""
Defines options and provides handling interface.
"""
def __init__(self, name, person_id=None):
tool.ToolOptions.__init__(self, name, person_id)
| gpl-2.0 |
codeman38/toggldesktop | third_party/googletest-read-only/scripts/fuse_gtest_files.py | 2577 | 8813 | #!/usr/bin/env python
#
# Copyright 2009, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""fuse_gtest_files.py v0.2.0
Fuses Google Test source code into a .h file and a .cc file.
SYNOPSIS
fuse_gtest_files.py [GTEST_ROOT_DIR] OUTPUT_DIR
Scans GTEST_ROOT_DIR for Google Test source code, and generates
two files: OUTPUT_DIR/gtest/gtest.h and OUTPUT_DIR/gtest/gtest-all.cc.
Then you can build your tests by adding OUTPUT_DIR to the include
search path and linking with OUTPUT_DIR/gtest/gtest-all.cc. These
two files contain everything you need to use Google Test. Hence
you can "install" Google Test by copying them to wherever you want.
GTEST_ROOT_DIR can be omitted and defaults to the parent
directory of the directory holding this script.
EXAMPLES
./fuse_gtest_files.py fused_gtest
./fuse_gtest_files.py path/to/unpacked/gtest fused_gtest
This tool is experimental. In particular, it assumes that there is no
conditional inclusion of Google Test headers. Please report any
problems to googletestframework@googlegroups.com. You can read
http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide for
more information.
"""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import re
import sets
import sys
# We assume that this file is in the scripts/ directory in the Google
# Test root directory.
DEFAULT_GTEST_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..')
# Regex for matching '#include "gtest/..."'.
INCLUDE_GTEST_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(gtest/.+)"')
# Regex for matching '#include "src/..."'.
INCLUDE_SRC_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(src/.+)"')
# Where to find the source seed files.
GTEST_H_SEED = 'include/gtest/gtest.h'
GTEST_SPI_H_SEED = 'include/gtest/gtest-spi.h'
GTEST_ALL_CC_SEED = 'src/gtest-all.cc'
# Where to put the generated files.
GTEST_H_OUTPUT = 'gtest/gtest.h'
GTEST_ALL_CC_OUTPUT = 'gtest/gtest-all.cc'
def VerifyFileExists(directory, relative_path):
"""Verifies that the given file exists; aborts on failure.
relative_path is the file path relative to the given directory.
"""
if not os.path.isfile(os.path.join(directory, relative_path)):
print 'ERROR: Cannot find %s in directory %s.' % (relative_path,
directory)
print ('Please either specify a valid project root directory '
'or omit it on the command line.')
sys.exit(1)
def ValidateGTestRootDir(gtest_root):
"""Makes sure gtest_root points to a valid gtest root directory.
The function aborts the program on failure.
"""
VerifyFileExists(gtest_root, GTEST_H_SEED)
VerifyFileExists(gtest_root, GTEST_ALL_CC_SEED)
def VerifyOutputFile(output_dir, relative_path):
"""Verifies that the given output file path is valid.
relative_path is relative to the output_dir directory.
"""
# Makes sure the output file either doesn't exist or can be overwritten.
output_file = os.path.join(output_dir, relative_path)
if os.path.exists(output_file):
# TODO(wan@google.com): The following user-interaction doesn't
# work with automated processes. We should provide a way for the
# Makefile to force overwriting the files.
print ('%s already exists in directory %s - overwrite it? (y/N) ' %
(relative_path, output_dir))
answer = sys.stdin.readline().strip()
if answer not in ['y', 'Y']:
print 'ABORTED.'
sys.exit(1)
# Makes sure the directory holding the output file exists; creates
# it and all its ancestors if necessary.
parent_directory = os.path.dirname(output_file)
if not os.path.isdir(parent_directory):
os.makedirs(parent_directory)
def ValidateOutputDir(output_dir):
"""Makes sure output_dir points to a valid output directory.
The function aborts the program on failure.
"""
VerifyOutputFile(output_dir, GTEST_H_OUTPUT)
VerifyOutputFile(output_dir, GTEST_ALL_CC_OUTPUT)
def FuseGTestH(gtest_root, output_dir):
"""Scans folder gtest_root to generate gtest/gtest.h in output_dir."""
output_file = file(os.path.join(output_dir, GTEST_H_OUTPUT), 'w')
processed_files = sets.Set() # Holds all gtest headers we've processed.
def ProcessFile(gtest_header_path):
"""Processes the given gtest header file."""
# We don't process the same header twice.
if gtest_header_path in processed_files:
return
processed_files.add(gtest_header_path)
# Reads each line in the given gtest header.
for line in file(os.path.join(gtest_root, gtest_header_path), 'r'):
m = INCLUDE_GTEST_FILE_REGEX.match(line)
if m:
# It's '#include "gtest/..."' - let's process it recursively.
ProcessFile('include/' + m.group(1))
else:
# Otherwise we copy the line unchanged to the output file.
output_file.write(line)
ProcessFile(GTEST_H_SEED)
output_file.close()
def FuseGTestAllCcToFile(gtest_root, output_file):
"""Scans folder gtest_root to generate gtest/gtest-all.cc in output_file."""
processed_files = sets.Set()
def ProcessFile(gtest_source_file):
"""Processes the given gtest source file."""
# We don't process the same #included file twice.
if gtest_source_file in processed_files:
return
processed_files.add(gtest_source_file)
# Reads each line in the given gtest source file.
for line in file(os.path.join(gtest_root, gtest_source_file), 'r'):
m = INCLUDE_GTEST_FILE_REGEX.match(line)
if m:
if 'include/' + m.group(1) == GTEST_SPI_H_SEED:
# It's '#include "gtest/gtest-spi.h"'. This file is not
# #included by "gtest/gtest.h", so we need to process it.
ProcessFile(GTEST_SPI_H_SEED)
else:
# It's '#include "gtest/foo.h"' where foo is not gtest-spi.
# We treat it as '#include "gtest/gtest.h"', as all other
# gtest headers are being fused into gtest.h and cannot be
# #included directly.
# There is no need to #include "gtest/gtest.h" more than once.
if not GTEST_H_SEED in processed_files:
processed_files.add(GTEST_H_SEED)
output_file.write('#include "%s"\n' % (GTEST_H_OUTPUT,))
else:
m = INCLUDE_SRC_FILE_REGEX.match(line)
if m:
# It's '#include "src/foo"' - let's process it recursively.
ProcessFile(m.group(1))
else:
output_file.write(line)
ProcessFile(GTEST_ALL_CC_SEED)
def FuseGTestAllCc(gtest_root, output_dir):
"""Scans folder gtest_root to generate gtest/gtest-all.cc in output_dir."""
output_file = file(os.path.join(output_dir, GTEST_ALL_CC_OUTPUT), 'w')
FuseGTestAllCcToFile(gtest_root, output_file)
output_file.close()
def FuseGTest(gtest_root, output_dir):
"""Fuses gtest.h and gtest-all.cc."""
ValidateGTestRootDir(gtest_root)
ValidateOutputDir(output_dir)
FuseGTestH(gtest_root, output_dir)
FuseGTestAllCc(gtest_root, output_dir)
def main():
argc = len(sys.argv)
if argc == 2:
# fuse_gtest_files.py OUTPUT_DIR
FuseGTest(DEFAULT_GTEST_ROOT_DIR, sys.argv[1])
elif argc == 3:
# fuse_gtest_files.py GTEST_ROOT_DIR OUTPUT_DIR
FuseGTest(sys.argv[1], sys.argv[2])
else:
print __doc__
sys.exit(1)
if __name__ == '__main__':
main()
| bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.